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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28,364 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 26,27 | 17,32 | forward | LayerNorm | 27,32 | 27,32 | class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
FILL_FUNC_BODY | class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
FILL_FUNC_BODY | 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 | 112 | 66 | 178 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,365 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 257,258 | 256,267 | forward | Log | 258,267 | 258,267 | class Log(nn.Module):
def forward(self, x, x_mask, reverse=False, **kwargs):
FILL_FUNC_BODY | class Log(nn.Module):
def forward(self, x, x_mask, reverse=False, **kwargs):
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 | 38 | 95 | 133 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,366 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 207,208 | 184,229 | forward | ResBlock1 | 208,222 | 208,222 | class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_paddi... | class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_paddi... | for c1, c2 in zip(self.convs1, self.convs2):
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c1(xt)
xt = F.leaky_relu(xt, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt... | for c1, c2 in zip(self.convs1, self.convs2):
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c1(xt)
xt = F.leaky_relu(xt, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt... | 57 | 482 | 179 | 661 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,367 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 251,252 | 229,256 | remove_weight_norm | ResBlock2 | 252,256 | 252,256 | class ResBlock2(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
super(ResBlock2, self).__init__()
self.convs = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(k... | class ResBlock2(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
super(ResBlock2, self).__init__()
self.convs = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(k... | for l in self.convs:
remove_weight_norm(l)
| for l in self.convs:
remove_weight_norm(l)
| 5 | 315 | 26 | 341 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,368 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 321,322 | 295,343 | forward | ResidualCouplingLayer | 322,343 | 322,343 | class ResidualCouplingLayer(nn.Module):
def __init__(self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=0,
gin_channels=0,
mean_only=False):
assert channels % 2 == 0, "channels should be divisible by 2"
super().__init__()
self.c... | class ResidualCouplingLayer(nn.Module):
def __init__(self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=0,
gin_channels=0,
mean_only=False):
assert channels % 2 == 0, "channels should be divisible by 2"
super().__init__()
self.c... | x0, x1 = torch.split(x, [self.half_channels]*2, 1)
h = self.pre(x0) * x_mask
h = self.enc(h, x_mask, g=g)
stats = self.post(h) * x_mask
if not self.mean_only:
m, logs = torch.split(stats, [self.half_channels]*2, 1)
else:
m = stats
logs = torch.zeros_like(m)
if not reverse:... | x0, x1 = torch.split(x, [self.half_channels]*2, 1)
h = self.pre(x0) * x_mask
h = self.enc(h, x_mask, g=g)
stats = self.post(h) * x_mask
if not self.mean_only:
m, logs = torch.split(stats, [self.half_channels]*2, 1)
else:
m = stats
logs = torch.zeros_like(m)
if not reverse:... | 78 | 360 | 281 | 641 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,369 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 145,146 | 108,184 | forward | WN | 146,175 | 146,175 | class WN(torch.nn.Module):
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
super(WN, self).__init__()
assert(kernel_size % 2 == 1)
self.hidden_channels =hidden_channels
self.kernel_size = kernel_size,
self.dilation_rate = dilation_rate
se... | class WN(torch.nn.Module):
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
super(WN, self).__init__()
assert(kernel_size % 2 == 1)
self.hidden_channels =hidden_channels
self.kernel_size = kernel_size,
self.dilation_rate = dilation_rate
se... | output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:,cond_off... | output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:,cond_off... | 83 | 683 | 372 | 1,055 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,370 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/text/cantonese.py | 43,44 | 1,60 | latin_to_ipa | 44,49 | 44,49 | import re
import cn2an
import opencc
converter = opencc.OpenCC('jyutjyu')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ei˥'),
('B', 'biː˥'),
('C', 'siː˥'),
('D', 'tiː˥'),
('E', 'iː˥'),
('F', 'e˥fuː˨˩'),
('G', 'tsiː˥'),
('H',... | import re
import cn2an
import opencc
converter = opencc.OpenCC('jyutjyu')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ei˥'),
('B', 'biː˥'),
('C', 'siː˥'),
('D', 'tiː˥'),
('E', 'iː˥'),
('F', 'e˥fuː˨˩'),
('G', 'tsiː˥'),
('H',... | for regex, replacement in _latin_to_ipa:
text = re.sub(regex, replacement, text)
return text
| for regex, replacement in _latin_to_ipa:
text = re.sub(regex, replacement, text)
return text
| 12 | 771 | 41 | 812 | import re
import cn2an
import opencc
converter = opencc.OpenCC('jyutjyu')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ei˥'),
('B', 'biː˥'),
('C', 'siː˥'),
('D', 'tiː˥'),
('E', 'iː˥'),
('F', 'e˥fuː˨˩'),
('G', 'tsiː˥'),
('H',... | import re
import cn2an
import opencc
converter = opencc.OpenCC('jyutjyu')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ei˥'),
('B', 'biː˥'),
('C', 'siː˥'),
('D', 'tiː˥'),
('E', 'iː˥'),
('F', 'e˥fuː˨˩'),
('G', 'tsiː˥'),
('H',... | |
28,375 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/text/ngu_dialect.py | 21,22 | 1,31 | ngu_dialect_to_ipa | 22,31 | 22,31 | import re
import opencc
dialects = {'SZ': 'suzhou', 'WX': 'wuxi', 'CZ': 'changzhou', 'HZ': 'hangzhou',
'SX': 'shaoxing', 'NB': 'ningbo', 'JJ': 'jingjiang', 'YX': 'yixing',
'JD': 'jiading', 'ZR': 'zhenru', 'PH': 'pinghu', 'TX': 'tongxiang',
'JS': 'jiashan', 'HN': 'xiashi', 'LP': 'li... | import re
import opencc
dialects = {'SZ': 'suzhou', 'WX': 'wuxi', 'CZ': 'changzhou', 'HZ': 'hangzhou',
'SX': 'shaoxing', 'NB': 'ningbo', 'JJ': 'jingjiang', 'YX': 'yixing',
'JD': 'jiading', 'ZR': 'zhenru', 'PH': 'pinghu', 'TX': 'tongxiang',
'JS': 'jiashan', 'HN': 'xiashi', 'LP': 'li... | dialect = dialects[dialect]
text = converters[dialect].convert(text).replace('-','').replace('$',' ')
text = re.sub(r'[、;:]', ',', text)
text = re.sub(r'\s*,\s*', ', ', text)
text = re.sub(r'\s*。\s*', '. ', text)
text = re.sub(r'\s*?\s*', '? ', text)
text = re.sub(r'\s*!\s*', '! ', text)
... | dialect = dialects[dialect]
text = converters[dialect].convert(text).replace('-','').replace('$',' ')
text = re.sub(r'[、;:]', ',', text)
text = re.sub(r'\s*,\s*', ', ', text)
text = re.sub(r'\s*。\s*', '. ', text)
text = re.sub(r'\s*?\s*', '? ', text)
text = re.sub(r'\s*!\s*', '! ', text)
... | 43 | 307 | 176 | 483 | import re
import opencc
dialects = {'SZ': 'suzhou', 'WX': 'wuxi', 'CZ': 'changzhou', 'HZ': 'hangzhou',
'SX': 'shaoxing', 'NB': 'ningbo', 'JJ': 'jingjiang', 'YX': 'yixing',
'JD': 'jiading', 'ZR': 'zhenru', 'PH': 'pinghu', 'TX': 'tongxiang',
'JS': 'jiashan', 'HN': 'xiashi', 'LP': 'li... | import re
import opencc
dialects = {'SZ': 'suzhou', 'WX': 'wuxi', 'CZ': 'changzhou', 'HZ': 'hangzhou',
'SX': 'shaoxing', 'NB': 'ningbo', 'JJ': 'jingjiang', 'YX': 'yixing',
'JD': 'jiading', 'ZR': 'zhenru', 'PH': 'pinghu', 'TX': 'tongxiang',
'JS': 'jiashan', 'HN': 'xiashi', 'LP': 'li... | |
28,376 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/text/sanskrit.py | 52,53 | 1,63 | devanagari_to_ipa | 53,63 | 53,63 | import re
from indic_transliteration import sanscript
# List of (iast, ipa) pairs:
_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('a', 'ə'),
('ā', 'aː'),
('ī', 'iː'),
('ū', 'uː'),
('ṛ', 'ɹ`'),
('ṝ', 'ɹ`ː'),
('ḷ', 'l`'),
('ḹ', 'l`ː'),
('e', 'eː'),
('o', 'oː'),
(... | import re
from indic_transliteration import sanscript
# List of (iast, ipa) pairs:
_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('a', 'ə'),
('ā', 'aː'),
('ī', 'iː'),
('ū', 'uː'),
('ṛ', 'ɹ`'),
('ṝ', 'ɹ`ː'),
('ḷ', 'l`'),
('ḹ', 'l`ː'),
('e', 'eː'),
('o', 'oː'),
(... | text = text.replace('ॐ', 'ओम्')
text = re.sub(r'\s*।\s*$', '.', text)
text = re.sub(r'\s*।\s*', ', ', text)
text = re.sub(r'\s*॥', '.', text)
text = sanscript.transliterate(text, sanscript.DEVANAGARI, sanscript.IAST)
for regex, replacement in _iast_to_ipa:
text = re.sub(regex, replacemen... | text = text.replace('ॐ', 'ओम्')
text = re.sub(r'\s*।\s*$', '.', text)
text = re.sub(r'\s*।\s*', ', ', text)
text = re.sub(r'\s*॥', '.', text)
text = sanscript.transliterate(text, sanscript.DEVANAGARI, sanscript.IAST)
for regex, replacement in _iast_to_ipa:
text = re.sub(regex, replacemen... | 45 | 579 | 212 | 791 | import re
from indic_transliteration import sanscript
# List of (iast, ipa) pairs:
_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('a', 'ə'),
('ā', 'aː'),
('ī', 'iː'),
('ū', 'uː'),
('ṛ', 'ɹ`'),
('ṝ', 'ɹ`ː'),
('ḷ', 'l`'),
('ḹ', 'l`ː'),
('e', 'eː'),
('o', 'oː'),
(... | import re
from indic_transliteration import sanscript
# List of (iast, ipa) pairs:
_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('a', 'ə'),
('ā', 'aː'),
('ī', 'iː'),
('ū', 'uː'),
('ṛ', 'ɹ`'),
('ṝ', 'ɹ`ː'),
('ḷ', 'l`'),
('ḹ', 'l`ː'),
('e', 'eː'),
('o', 'oː'),
(... | |
28,377 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/text/shanghainese.py | 54,55 | 1,65 | shanghainese_to_ipa | 55,65 | 55,65 | import re
import cn2an
import opencc
converter = opencc.OpenCC('zaonhe')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ᴇ'),
('B', 'bi'),
('C', 'si'),
('D', 'di'),
('E', 'i'),
('F', 'ᴇf'),
('G', 'dʑi'),
('H', 'ᴇtɕʰ'),
('I'... | import re
import cn2an
import opencc
converter = opencc.OpenCC('zaonhe')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ᴇ'),
('B', 'bi'),
('C', 'si'),
('D', 'di'),
('E', 'i'),
('F', 'ᴇf'),
('G', 'dʑi'),
('H', 'ᴇtɕʰ'),
('I'... | text = number_to_shanghainese(text.upper())
text = converter.convert(text).replace('-','').replace('$',' ')
text = re.sub(r'[A-Z]', lambda x: latin_to_ipa(x.group())+' ', text)
text = re.sub(r'[、;:]', ',', text)
text = re.sub(r'\s*,\s*', ', ', text)
text = re.sub(r'\s*。\s*', '. ', text)
text... | text = number_to_shanghainese(text.upper())
text = converter.convert(text).replace('-','').replace('$',' ')
text = re.sub(r'[A-Z]', lambda x: latin_to_ipa(x.group())+' ', text)
text = re.sub(r'[、;:]', ',', text)
text = re.sub(r'\s*,\s*', ', ', text)
text = re.sub(r'\s*。\s*', '. ', text)
text... | 51 | 584 | 216 | 800 | import re
import cn2an
import opencc
converter = opencc.OpenCC('zaonhe')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ᴇ'),
('B', 'bi'),
('C', 'si'),
('D', 'di'),
('E', 'i'),
('F', 'ᴇf'),
('G', 'dʑi'),
('H', 'ᴇtɕʰ'),
('I'... | import re
import cn2an
import opencc
converter = opencc.OpenCC('zaonhe')
# List of (Latin alphabet, ipa) pairs:
_latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
('A', 'ᴇ'),
('B', 'bi'),
('C', 'si'),
('D', 'di'),
('E', 'i'),
('F', 'ᴇf'),
('G', 'dʑi'),
('H', 'ᴇtɕʰ'),
('I'... | |
28,378 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/text/thai.py | 38,39 | 1,45 | num_to_thai | 39,41 | 39,41 | import re
from num_thai.thainumbers import NumThai
num = NumThai()
# List of (Latin alphabet, Thai) pairs:
_latin_to_thai = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('a', 'เอ'),
('b','บี'),
('c','ซี'),
('d','ดี'),
('e','อี'),
('f','เอฟ'),
('g','จี'),
('h','เอช'),
... | import re
from num_thai.thainumbers import NumThai
num = NumThai()
# List of (Latin alphabet, Thai) pairs:
_latin_to_thai = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('a', 'เอ'),
('b','บี'),
('c','ซี'),
('d','ดี'),
('e','อี'),
('f','เอฟ'),
('g','จี'),
('h','เอช'),
... | return re.sub(r'(?:\d+(?:,?\d+)?)+(?:\.\d+(?:,?\d+)?)?', lambda x: ''.join(num.NumberToTextThai(float(x.group(0).replace(',', '')))), text)
| return re.sub(r'(?:\d+(?:,?\d+)?)+(?:\.\d+(?:,?\d+)?)?', lambda x: ''.join(num.NumberToTextThai(float(x.group(0).replace(',', '')))), text)
| 7 | 478 | 76 | 554 | import re
from num_thai.thainumbers import NumThai
num = NumThai()
# List of (Latin alphabet, Thai) pairs:
_latin_to_thai = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('a', 'เอ'),
('b','บี'),
('c','ซี'),
('d','ดี'),
('e','อี'),
('f','เอฟ'),
('g','จี'),
('h','เอช'),
... | import re
from num_thai.thainumbers import NumThai
num = NumThai()
# List of (Latin alphabet, Thai) pairs:
_latin_to_thai = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('a', 'เอ'),
('b','บี'),
('c','ซี'),
('d','ดี'),
('e','อี'),
('f','เอฟ'),
('g','จี'),
('h','เอช'),
... | |
28,380 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/utils.py | 40,41 | 1,76 | load_checkpoint | 41,64 | 41,64 | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... | checkpoint_dict = load(checkpoint_path, map_location='cpu')
iteration = checkpoint_dict['iteration']
saved_state_dict = checkpoint_dict['model']
if hasattr(model, 'module'):
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
new_state_dict= {}
for k, v in state_dict.items... | checkpoint_dict = load(checkpoint_path, map_location='cpu')
iteration = checkpoint_dict['iteration']
saved_state_dict = checkpoint_dict['model']
if hasattr(model, 'module'):
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
new_state_dict= {}
for k, v in state_dict.items... | 58 | 416 | 277 | 693 | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... | |
28,381 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/utils.py | 21,22 | 8,40 | values | HParams | 22,24 | 22,24 | class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
def items(self):
return self.__dict__.items()
def values(self):
FILL_FUNC_BODY def __len__(self):
return... | class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
def items(self):
return self.__dict__.items()
def values(self):
FILL_FUNC_BODY def __len__(self):
return... | return self.__dict__.values()
| return self.__dict__.values()
| 2 | 220 | 13 | 233 | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... | import logging
from json import loads
from torch import load, FloatTensor
from numpy import float32
import librosa
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
... |
28,418 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/bottle_plugins/error_plugin.py | 5,6 | 1,23 | error_plugin | 10,23 | 6,23 | from bottle import response
import logging
def error_plugin(callback):
FILL_FUNC_BODY | from bottle import response
import logging
def error_plugin(callback):
"""
Bottle plugin to handle exceptions
https://stackoverflow.com/a/32764250
"""
FILL_FUNC_BODY |
def wrapper(*args, **kwargs):
try:
actual_response = callback(*args, **kwargs)
except Exception as e:
logging.error(str(e))
actual_response = {
"error": str(e)
}
response.status = 500
return actual_response
ret... | """
Bottle plugin to handle exceptions
https://stackoverflow.com/a/32764250
"""
def wrapper(*args, **kwargs):
try:
actual_response = callback(*args, **kwargs)
except Exception as e:
logging.error(str(e))
actual_response = {
"error"... | 26 | 62 | 97 | 159 | from bottle import response
import logging
def error_plugin(callback):
FILL_FUNC_BODY | from bottle import response
import logging
def error_plugin(callback):
"""
Bottle plugin to handle exceptions
https://stackoverflow.com/a/32764250
"""
FILL_FUNC_BODY | |
28,419 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/bottle_plugins/logger_plugin.py | 5,6 | 1,24 | logger_plugin | 13,24 | 6,24 | from bottle import request, response
import logging
def logger_plugin(callback):
FILL_FUNC_BODY | from bottle import request, response
import logging
def logger_plugin(callback):
"""
Bottle plugin to use logging module
http://bottlepy.org/docs/dev/plugindev.html
Wrap a Bottle request so that a log line is emitted after it's handled.
(This decorator can be extended to take the desired logger a... |
def wrapper(*args, **kwargs):
actual_response = callback(*args, **kwargs)
if not request.url.endswith("/health"):
logging.info('%s %s %s %s' % (request.remote_addr,
request.method,
request.url,
... | """
Bottle plugin to use logging module
http://bottlepy.org/docs/dev/plugindev.html
Wrap a Bottle request so that a log line is emitted after it's handled.
(This decorator can be extended to take the desired logger as a param.)
"""
def wrapper(*args, **kwargs):
actual_response = ca... | 23 | 108 | 102 | 210 | from bottle import request, response
import logging
def logger_plugin(callback):
FILL_FUNC_BODY | from bottle import request, response
import logging
def logger_plugin(callback):
"""
Bottle plugin to use logging module
http://bottlepy.org/docs/dev/plugindev.html
Wrap a Bottle request so that a log line is emitted after it's handled.
(This decorator can be extended to take the desired logger a... | |
28,420 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/bottle_plugins/prometheus_plugin.py | 18,19 | 1,67 | prometheus_plugin | 23,67 | 19,67 | import logging
import os
import urllib.parse
from bottle import request
from dtos import V1RequestBase, V1ResponseBase
from metrics import start_metrics_http_server, REQUEST_COUNTER, REQUEST_DURATION
PROMETHEUS_ENABLED = os.environ.get('PROMETHEUS_ENABLED', 'false').lower() == 'true'
PROMETHEUS_PORT = int(os.environ.... | import logging
import os
import urllib.parse
from bottle import request
from dtos import V1RequestBase, V1ResponseBase
from metrics import start_metrics_http_server, REQUEST_COUNTER, REQUEST_DURATION
PROMETHEUS_ENABLED = os.environ.get('PROMETHEUS_ENABLED', 'false').lower() == 'true'
PROMETHEUS_PORT = int(os.environ.... | def wrapper(*args, **kwargs):
actual_response = callback(*args, **kwargs)
if PROMETHEUS_ENABLED:
try:
export_metrics(actual_response)
except Exception as e:
logging.warning("Error exporting metrics: " + str(e))
return actual_response
... | """
Bottle plugin to expose Prometheus metrics
http://bottlepy.org/docs/dev/plugindev.html
"""
def wrapper(*args, **kwargs):
actual_response = callback(*args, **kwargs)
if PROMETHEUS_ENABLED:
try:
export_metrics(actual_response)
except Excepti... | 109 | 224 | 452 | 676 | import logging
import os
import urllib.parse
from bottle import request
from dtos import V1RequestBase, V1ResponseBase
from metrics import start_metrics_http_server, REQUEST_COUNTER, REQUEST_DURATION
PROMETHEUS_ENABLED = os.environ.get('PROMETHEUS_ENABLED', 'false').lower() == 'true'
PROMETHEUS_PORT = int(os.environ.... | import logging
import os
import urllib.parse
from bottle import request
from dtos import V1RequestBase, V1ResponseBase
from metrics import start_metrics_http_server, REQUEST_COUNTER, REQUEST_DURATION
PROMETHEUS_ENABLED = os.environ.get('PROMETHEUS_ENABLED', 'false').lower() == 'true'
PROMETHEUS_PORT = int(os.environ.... | |
28,421 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/build_package.py | 68,69 | 1,111 | run_pyinstaller | 69,81 | 69,81 | import os
import platform
import shutil
import subprocess
import sys
import zipfile
import requests
def clean_files():
try:
shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'build'))
except Exception:
pass
try:
shutil.rmtree(os.path.join(os.path.di... | import os
import platform
import shutil
import subprocess
import sys
import zipfile
import requests
def clean_files():
try:
shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'build'))
except Exception:
pass
try:
shutil.rmtree(os.path.join(os.path.di... | sep = ';' if os.name == 'nt' else ':'
result = subprocess.run([sys.executable, "-m", "PyInstaller",
"--icon", "resources/flaresolverr_logo.ico",
"--add-data", f"package.json{sep}.",
"--add-data", f"{os.path.join('dist_chrome'... | sep = ';' if os.name == 'nt' else ':'
result = subprocess.run([sys.executable, "-m", "PyInstaller",
"--icon", "resources/flaresolverr_logo.ico",
"--add-data", f"package.json{sep}.",
"--add-data", f"{os.path.join('dist_chrome'... | 35 | 1,249 | 205 | 1,454 | import os
import platform
import shutil
import subprocess
import sys
import zipfile
import requests
def clean_files():
try:
shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'build'))
except Exception:
pass
try:
shutil.rmtree(os.path.join(os.path.di... | import os
import platform
import shutil
import subprocess
import sys
import zipfile
import requests
def clean_files():
try:
shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'build'))
except Exception:
pass
try:
shutil.rmtree(os.path.join(os.path.di... | |
28,422 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/flaresolverr.py | 29,31 | 1,123 | index | 34,38 | 31,38 | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | res = flaresolverr_service.index_endpoint()
return utils.object_to_dict(res)
| """
Show welcome message
"""
res = flaresolverr_service.index_endpoint()
return utils.object_to_dict(res)
| 5 | 1,247 | 36 | 1,283 | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | |
28,423 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/flaresolverr.py | 21,22 | 17,26 | default_error_handler | JSONErrorBottle | 22,26 | 22,26 | class JSONErrorBottle(Bottle):
"""
Handle 404 errors
"""
def default_error_handler(self, res):
FILL_FUNC_BODY | class JSONErrorBottle(Bottle):
"""
Handle 404 errors
"""
def default_error_handler(self, res):
FILL_FUNC_BODY | response.content_type = 'application/json'
return json.dumps(dict(error=res.body, status_code=res.status_code))
| response.content_type = 'application/json'
return json.dumps(dict(error=res.body, status_code=res.status_code))
| 6 | 49 | 45 | 94 | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... |
28,424 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/flaresolverr.py | 119,120 | 118,122 | run | WaitressServerPoll | 120,122 | 120,122 | class WaitressServerPoll(ServerAdapter):
def run(self, handler):
FILL_FUNC_BODY | class WaitressServerPoll(ServerAdapter):
def run(self, handler):
FILL_FUNC_BODY | from waitress import serve
serve(handler, host=self.host, port=self.port, asyncore_use_poll=True)
| from waitress import serve
serve(handler, host=self.host, port=self.port, asyncore_use_poll=True)
| 8 | 31 | 37 | 68 | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... | import json
import logging
import os
import sys
import certifi
from bottle import run, response, Bottle, request, ServerAdapter
from bottle_plugins.error_plugin import error_plugin
from bottle_plugins.logger_plugin import logger_plugin
from bottle_plugins import prometheus_plugin
from dtos import V1RequestBase
import... |
28,426 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/metrics.py | 25,26 | 1,33 | start_metrics_http_server | 26,33 | 26,33 | import logging
from prometheus_client import Counter, Histogram, start_http_server
import time
REQUEST_COUNTER = Counter(
name='flaresolverr_request',
documentation='Total requests with result',
labelnames=['domain', 'result']
)
REQUEST_DURATION = Histogram(
name='flaresolverr_request_duration',
d... | import logging
from prometheus_client import Counter, Histogram, start_http_server
import time
REQUEST_COUNTER = Counter(
name='flaresolverr_request',
documentation='Total requests with result',
labelnames=['domain', 'result']
)
REQUEST_DURATION = Histogram(
name='flaresolverr_request_duration',
d... | logging.info(f"Serving Prometheus exporter on http://0.0.0.0:{prometheus_port}/metrics")
from threading import Thread
Thread(
target=serve,
kwargs=dict(port=prometheus_port),
daemon=True,
).start()
| logging.info(f"Serving Prometheus exporter on http://0.0.0.0:{prometheus_port}/metrics")
from threading import Thread
Thread(
target=serve,
kwargs=dict(port=prometheus_port),
daemon=True,
).start()
| 14 | 204 | 88 | 292 | import logging
from prometheus_client import Counter, Histogram, start_http_server
import time
REQUEST_COUNTER = Counter(
name='flaresolverr_request',
documentation='Total requests with result',
labelnames=['domain', 'result']
)
REQUEST_DURATION = Histogram(
name='flaresolverr_request_duration',
d... | import logging
from prometheus_client import Counter, Histogram, start_http_server
import time
REQUEST_COUNTER = Counter(
name='flaresolverr_request',
documentation='Total requests with result',
labelnames=['domain', 'result']
)
REQUEST_DURATION = Histogram(
name='flaresolverr_request_duration',
d... | |
28,427 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/sessions.py | 18,19 | 12,22 | lifetime | Session | 19,22 | 19,22 | @dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
def lifetime(self) -> timedelta:
FILL_FUNC_BODY | @dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
def lifetime(self) -> timedelta:
FILL_FUNC_BODY | return datetime.now() - self.created_at
| return datetime.now() - self.created_at
| 4 | 53 | 18 | 71 | import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Tuple
from uuid import uuid1
from selenium.webdriver.chrome.webdriver import WebDriver
import utils
@dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
... | import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Tuple
from uuid import uuid1
from selenium.webdriver.chrome.webdriver import WebDriver
import utils
@dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
... |
28,428 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/sessions.py | 72,73 | 22,83 | get | SessionsStorage | 73,81 | 73,81 | class SessionsStorage:
"""SessionsStorage creates, stores and process all the sessions"""
def __init__(self):
self.sessions = {}
def create(self, session_id: Optional[str] = None, proxy: Optional[dict] = None,
force_new: Optional[bool] = False) -> Tuple[Session, bool]:
"""cr... | class SessionsStorage:
"""SessionsStorage creates, stores and process all the sessions"""
def __init__(self):
self.sessions = {}
def create(self, session_id: Optional[str] = None, proxy: Optional[dict] = None,
force_new: Optional[bool] = False) -> Tuple[Session, bool]:
"""cr... | session, fresh = self.create(session_id)
if ttl is not None and not fresh and session.lifetime() > ttl:
logging.debug(f'session\'s lifetime has expired, so the session is recreated (session_id={session_id})')
session, fresh = self.create(session_id, force_new=True)
retu... | session, fresh = self.create(session_id)
if ttl is not None and not fresh and session.lifetime() > ttl:
logging.debug(f'session\'s lifetime has expired, so the session is recreated (session_id={session_id})')
session, fresh = self.create(session_id, force_new=True)
retu... | 34 | 559 | 106 | 665 | import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Tuple
from uuid import uuid1
from selenium.webdriver.chrome.webdriver import WebDriver
import utils
@dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
... | import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Tuple
from uuid import uuid1
from selenium.webdriver.chrome.webdriver import WebDriver
import utils
@dataclass
class Session:
session_id: str
driver: WebDriver
created_at: datetime
... |
28,429 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/devtool.py | 103,104 | 1,191 | test | 104,191 | 104,191 | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... | import sys, os
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
import undetected_chromedriver as uc
import threading
def collector(
driver: uc.Chrome,
stop_event: threading.Event,
on_event_coro: Optional[Callable[[List[str]], Awaitable[Any]]] = None,
... | import sys, os
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
import undetected_chromedriver as uc
import threading
def collector(
driver: uc.Chrome,
stop_event: threading.Event,
on_event_coro: Optional[Callable[[List[str]], Awaitable[Any]]] = None,
... | 202 | 741 | 958 | 1,699 | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... | |
28,430 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/devtool.py | 72,73 | 16,78 | _normalize_strings | Structure | 73,78 | 73,78 | class Structure(dict):
"""
This is a dict-like object structure, which you should subclass
Only properties defined in the class context are used on initialization.
See example
"""
_store = {}
def __init__(self, *a, **kw):
"""
Instantiate a new instance.
:param a:
... | class Structure(dict):
"""
This is a dict-like object structure, which you should subclass
Only properties defined in the class context are used on initialization.
See example
"""
_store = {}
def __init__(self, *a, **kw):
"""
Instantiate a new instance.
:param a:
... | for k, v in self.copy().items():
if isinstance(v, (str)):
self[k] = v.strip()
| for k, v in self.copy().items():
if isinstance(v, (str)):
self[k] = v.strip()
| 11 | 457 | 43 | 500 | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... | import asyncio
from collections.abc import Mapping
from collections.abc import Sequence
from functools import wraps
import logging
import threading
import time
import traceback
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import List
from typing import Optional
class Str... |
28,431 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/options.py | 42,44 | 11,86 | _merge_nested | ChromeOptions | 48,56 | 44,56 | class ChromeOptions(_ChromiumOptions):
_session = None
_user_data_dir = None
@property
def user_data_dir(self):
return self._user_data_dir
@user_data_dir.setter
def user_data_dir(self, path: str):
"""
Sets the browser profile folder to use, or creates a new profile
... | class ChromeOptions(_ChromiumOptions):
_session = None
_user_data_dir = None
@property
def user_data_dir(self):
return self._user_data_dir
@user_data_dir.setter
def user_data_dir(self, path: str):
"""
Sets the browser profile folder to use, or creates a new profile
... | for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
ChromeOptions._merge_nested(a[key], b[key])
continue
a[key] = b[key]
return a
| """
merges b into a
leaf values in a are overwritten with values from b
"""
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
ChromeOptions._merge_nested(a[key], b[key])
continu... | 22 | 682 | 81 | 763 | #!/usr/bin/env python3
# this module is part of undetected_chromedriver
import json
import os
from selenium.webdriver.chromium.options import ChromiumOptions as _ChromiumOptions
class ChromeOptions(_ChromiumOptions):
_session = None
_user_data_dir = None
@property
def user_data_dir(self):
... | #!/usr/bin/env python3
# this module is part of undetected_chromedriver
import json
import os
from selenium.webdriver.chromium.options import ChromiumOptions as _ChromiumOptions
class ChromeOptions(_ChromiumOptions):
_session = None
_user_data_dir = None
@property
def user_data_dir(self):
... |
28,432 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/webelement.py | 67,68 | 1,87 | _recursive_children | 78,87 | 68,87 | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | results = _results or set()
for element in element.children():
if tag:
if element.tag_name == tag:
results.add(element)
else:
results.add(element)
results |= _recursive_children(element, tag, results)
return results
| """
returns all children of <element> recursively
:param element: `WebElement` object.
find children below this <element>
:param tag: str = None.
if provided, return only <tag> elements. example: 'a', or 'img'
:param _results: do not use!
"""
results = _results or s... | 25 | 800 | 84 | 884 | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | |
28,433 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/webelement.py | 44,46 | 27,67 | attrs | UCWebElement | 46,60 | 46,60 | class UCWebElement(WebElement):
"""
Custom WebElement class which makes it easier to view elements when
working in an interactive environment.
standard webelement repr:
<selenium.webdriver.remote.webelement.WebElement (session="85ff0f671512fa535630e71ee951b1f2", element="6357cb55-92c3-4c0f-9416-b17... | class UCWebElement(WebElement):
"""
Custom WebElement class which makes it easier to view elements when
working in an interactive environment.
standard webelement repr:
<selenium.webdriver.remote.webelement.WebElement (session="85ff0f671512fa535630e71ee951b1f2", element="6357cb55-92c3-4c0f-9416-b17... | if not self._attrs:
self._attrs = self._parent.execute_script(
"""
var items = {};
for (index = 0; index < arguments[0].attributes.length; ++index)
{
items[arguments[0].attributes[index].name] = arguments[0].attribute... | if not self._attrs:
self._attrs = self._parent.execute_script(
"""
var items = {};
for (index = 0; index < arguments[0].attributes.length; ++index)
{
items[arguments[0].attributes[index].name] = arguments[0].attribute... | 31 | 343 | 126 | 469 | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... |
28,434 | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr | /home/hieuvd/dung_repo/raw/stars_02/FlareSolverr_FlareSolverr/FlareSolverr/src/undetected_chromedriver/webelement.py | 12,15 | 7,27 | children | WebElement | 19,27 | 15,27 | class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive=False
) -> List[selenium.webdriver.remote.webelement.WebElement]:
FILL_FUNC_BODY | class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive=False
) -> List[selenium.webdriver.remote.webelement.WebElement]:
"""
returns direct child ele... | script = "return [... arguments[0].children]"
if tag:
script += ".filter( node => node.tagName === '%s')" % tag.upper()
if recursive:
return list(_recursive_children(self, tag))
return list(self._parent.execute_script(script, self))
| """
returns direct child elements of current element
:param tag: str, if supplied, returns <tag> nodes only
"""
script = "return [... arguments[0].children]"
if tag:
script += ".filter( node => node.tagName === '%s')" % tag.upper()
if recursive:
... | 25 | 133 | 90 | 223 | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... | from typing import List
from selenium.webdriver.common.by import By
import selenium.webdriver.remote.webelement
class WebElement(selenium.webdriver.remote.webelement.WebElement):
def click_safe(self):
super().click()
self._parent.reconnect(0.1)
def children(
self, tag=None, recursive... |
29,406 | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM/agent/pal_inference.py | 297,299 | 272,302 | answer | GenericRuntime | 299,302 | 299,302 | class GenericRuntime:
"""Adapted from https://github.com/reasoning-machines/pal."""
GLOBAL_DICT: dict = {}
LOCAL_DICT = None
HEADERS: List = []
def __init__(self):
self._global_vars = copy.copy(self.GLOBAL_DICT)
self._local_vars = copy.copy(
self.LOCAL_DICT) if self.LOC... | class GenericRuntime:
"""Adapted from https://github.com/reasoning-machines/pal."""
GLOBAL_DICT: dict = {}
LOCAL_DICT = None
HEADERS: List = []
def __init__(self):
self._global_vars = copy.copy(self.GLOBAL_DICT)
self._local_vars = copy.copy(
self.LOCAL_DICT) if self.LOC... | return self._global_vars['answer']
| return self._global_vars['answer']
| 2 | 280 | 16 | 296 | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
29,407 | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM/agent/pal_inference.py | 335,336 | 302,378 | generate | PALInterface | 336,352 | 336,352 | class PALInterface:
"""PAL interface wrap fun:`generate_interactive` to extract and execute
generated code.
Adapted from https://github.com/reasoning-machines/pal
Args:
model (AutoModelForCausalLM)
tokenizer (AutoTokenizer)
generation_config (GenerationConfig): Decode strategie... | class PALInterface:
"""PAL interface wrap fun:`generate_interactive` to extract and execute
generated code.
Adapted from https://github.com/reasoning-machines/pal
Args:
model (AutoModelForCausalLM)
tokenizer (AutoTokenizer)
generation_config (GenerationConfig): Decode strategie... | # The api will generate response word by word
# we only need the last generation as the final results
for cur_gen in generate_interactive(
model=self.model,
tokenizer=self.tokenizer,
prompt=prompt,
additional_eos_token_id=self.addit... | # The api will generate response word by word
# we only need the last generation as the final results
for cur_gen in generate_interactive(
model=self.model,
tokenizer=self.tokenizer,
prompt=prompt,
additional_eos_token_id=self.addit... | 45 | 609 | 169 | 778 | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
29,408 | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM | /home/hieuvd/dung_repo/raw/stars_02/InternLM_InternLM/InternLM/agent/pal_inference.py | 128,129 | 114,139 | timeout_handler | Timeout | 129,131 | 129,131 | class Timeout:
"""Timer to execute code.
Adapted from https://github.com/reasoning-machines/pal
Args:
seconds (float): The maximum seconds to execute code
error_message (str)
"""
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.er... | class Timeout:
"""Timer to execute code.
Adapted from https://github.com/reasoning-machines/pal
Args:
seconds (float): The maximum seconds to execute code
error_message (str)
"""
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.er... | raise TimeoutError(self.error_message)
| raise TimeoutError(self.error_message)
| 2 | 195 | 16 | 211 | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | # flake8: noqa
# This file is modified from:
# hhttps://github.com/reasoning-machines/pal/blob/main/pal/core/interface.py
#
# Copyright 2022 PAL Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
29,463 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/main.py | 5,6 | 1,12 | main | 6,10 | 6,10 | from src.application import TikTokDownloader
from asyncio import run
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
run(main())
| from src.application import TikTokDownloader
from asyncio import run
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
run(main())
| async with TikTokDownloader() as downloader:
await downloader.run()
| async with TikTokDownloader() as downloader:
await downloader.run()
| 7 | 51 | 28 | 79 | from src.application import TikTokDownloader
from asyncio import run
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
run(main())
| from src.application import TikTokDownloader
from asyncio import run
async def main():
FILL_FUNC_BODYif __name__ == "__main__":
run(main())
| |
29,464 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/custom/function.py | 43,44 | 1,85 | illegal_nickname | 45,52 | 44,52 | from asyncio import sleep
from random import randint
from typing import TYPE_CHECKING
# from time import time
from .static import GENERAL
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = [
"wait",
"failure_handling",
"illegal_nickname",
"condition_filter",
"suspend",
"ver... | from asyncio import sleep
from random import randint
from typing import TYPE_CHECKING
# from time import time
from .static import GENERAL
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = [
"wait",
"failure_handling",
"illegal_nickname",
"condition_filter",
"suspend",
"ver... | # 询问用户
return input("当前 账号昵称/标识 或者 合集标题/标识 不是有效的文件夹名称,请输入临时的账号标识或者合集标识:")
# 使用当前时间戳作为账号昵称/标识或者合集标题/标识
# 需要将第 5 行代码取消注释
# return str(time())[:10]
| """当 账号昵称/标识 或者 合集标题/标识 过滤非法字符后不是有效的文件夹名称时,如何处理异常"""
# 询问用户
return input("当前 账号昵称/标识 或者 合集标题/标识 不是有效的文件夹名称,请输入临时的账号标识或者合集标识:")
# 使用当前时间戳作为账号昵称/标识或者合集标题/标识
# 需要将第 5 行代码取消注释
# return str(time())[:10]
| 17 | 855 | 119 | 974 | from asyncio import sleep
from random import randint
from typing import TYPE_CHECKING
# from time import time
from .static import GENERAL
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = [
"wait",
"failure_handling",
"illegal_nickname",
"condition_filter",
"suspend",
"ver... | from asyncio import sleep
from random import randint
from typing import TYPE_CHECKING
# from time import time
from .static import GENERAL
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = [
"wait",
"failure_handling",
"illegal_nickname",
"condition_filter",
"suspend",
"ver... | |
29,465 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/encrypt/verifyFp.py | 15,17 | 12,47 | get_verify_fp | VerifyFp | 17,47 | 17,47 | class VerifyFp:
"""代码参考: https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/utils.py"""
@staticmethod
def get_verify_fp(timestamp: int = None):
FILL_FUNC_BODY | class VerifyFp:
"""代码参考: https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/utils.py"""
@staticmethod
def get_verify_fp(timestamp: int = None):
FILL_FUNC_BODY | base_str = digits + ascii_uppercase + ascii_lowercase
t = len(base_str)
milliseconds = timestamp or int(round(time() * 1000))
base36 = ""
# 转换为 base36
while milliseconds > 0:
milliseconds, remainder = divmod(milliseconds, 36)
if remainder < 10:
... | base_str = digits + ascii_uppercase + ascii_lowercase
t = len(base_str)
milliseconds = timestamp or int(round(time() * 1000))
base36 = ""
# 转换为 base36
while milliseconds > 0:
milliseconds, remainder = divmod(milliseconds, 36)
if remainder < 10:
... | 110 | 80 | 356 | 436 | from random import random
from string import ascii_lowercase
from string import ascii_uppercase
from string import digits
from time import time
from rich import print
__all__ = ["VerifyFp", ]
class VerifyFp:
"""代码参考: https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/utils.py"""
@staticmethod
... | from random import random
from string import ascii_lowercase
from string import ascii_uppercase
from string import digits
from time import time
from rich import print
__all__ = ["VerifyFp", ]
class VerifyFp:
"""代码参考: https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/utils.py"""
@staticmethod
... |
29,467 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/collects.py | 27,28 | 11,67 | generate_params | Collects | 28,35 | 28,35 | class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
cursor=0,
count=10,
*args,
**kwargs,
):
super().__init__(params, cookie,... | class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
cursor=0,
count=10,
*args,
**kwargs,
):
super().__init__(params, cookie,... | return self.params | {
"cursor": self.cursor,
"count": self.count,
"version_code": "170400",
"version_name": "17.4.0",
}
| return self.params | {
"cursor": self.cursor,
"count": self.count,
"version_code": "170400",
"version_name": "17.4.0",
}
| 13 | 384 | 67 | 451 | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Collects", "CollectsDetail", ]
class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Collects", "CollectsDetail", ]
class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... |
29,468 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/collects.py | 94,109 | 67,126 | run | CollectsDetail | 109,126 | 109,126 | class CollectsDetail(Collects):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
collects_id: str = "",
pages: int = None,
cursor=0,
count=10,
*args,
... | class CollectsDetail(Collects):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
collects_id: str = "",
pages: int = None,
cursor=0,
count=10,
*args,
... | return await super().run(
referer,
single_page,
data_key,
error_text or f"收藏夹 {self.collects_id} 为空",
cursor,
has_more,
params,
data,
method,
headers,
proxy,
*args,
... | return await super().run(
referer,
single_page,
data_key,
error_text or f"收藏夹 {self.collects_id} 为空",
cursor,
has_more,
params,
data,
method,
headers,
proxy,
*args,
... | 21 | 416 | 109 | 525 | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Collects", "CollectsDetail", ]
class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Collects", "CollectsDetail", ]
class Collects(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... |
29,469 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/hashtag.py | 22,23 | 12,24 | run | HashTag | 23,24 | 23,24 | class HashTag(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
*args,
**kwargs,
):
super().__init__(params, cookie, proxy, *args, **kwargs, )
async def run(self, *ar... | class HashTag(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
*args,
**kwargs,
):
super().__init__(params, cookie, proxy, *args, **kwargs, )
async def run(self, *ar... | self.console.print("该功能暂不开放!", style=WARNING)
| self.console.print("该功能暂不开放!", style=WARNING)
| 2 | 97 | 20 | 117 | from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["HashTag"]
class HashTag(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = ... | from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["HashTag"]
class HashTag(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = ... |
29,470 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/live.py | 38,39 | 11,80 | with_web_rid | Live | 39,65 | 39,65 | class Live(API):
live_api = "https://live.douyin.com/webcast/room/web/enter/"
live_api_share = "https://webcast.amemv.com/webcast/room/reflow/info/"
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
web_rid=Non... | class Live(API):
live_api = "https://live.douyin.com/webcast/room/web/enter/"
live_api_share = "https://webcast.amemv.com/webcast/room/reflow/info/"
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
web_rid=Non... | self.set_referer("https://live.douyin.com/")
params = {
"aid": "6383",
"app_name": "douyin_web",
"live_id": "1",
"device_platform": "web",
"language": "zh-CN",
"enter_from": "link_share",
"cookie_enabled": "true",
... | self.set_referer("https://live.douyin.com/")
params = {
"aid": "6383",
"app_name": "douyin_web",
"live_id": "1",
"device_platform": "web",
"language": "zh-CN",
"enter_from": "link_share",
"cookie_enabled": "true",
... | 47 | 464 | 292 | 756 | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Live"]
class Live(API):
live_api = "https://live.douyin.com/webcast/room/web/enter/"
live_api_share = "https://webcast.amemv.com/webcast/room/reflow/info/"
def __init__(self,
... | from typing import TYPE_CHECKING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Live"]
class Live(API):
live_api = "https://live.douyin.com/webcast/room/web/enter/"
live_api_share = "https://webcast.amemv.com/webcast/room/reflow/info/"
def __init__(self,
... |
29,471 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/search.py | 53,54 | 13,56 | run | Search | 54,56 | 54,56 | class Search(API):
search_params = (
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/web/general/search/single/",
count=15,
channel="aweme_general",
type="general",
),
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/web/... | class Search(API):
search_params = (
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/web/general/search/single/",
count=15,
channel="aweme_general",
type="general",
),
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/web/... | self.console.print("该功能暂不开放!", style=WARNING)
return self.response
| self.console.print("该功能暂不开放!", style=WARNING)
return self.response
| 4 | 389 | 27 | 416 | from types import SimpleNamespace
from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Search"]
class Search(API):
search_params = (
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/... | from types import SimpleNamespace
from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["Search"]
class Search(API):
search_params = (
SimpleNamespace(
api="https://www.douyin.com/aweme/v1/... |
29,472 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/interface/user.py | 22,23 | 12,24 | run | User | 23,24 | 23,24 | class User(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
*args,
**kwargs,
):
super().__init__(params, cookie, proxy, *args, **kwargs, )
async def run(self, *args,... | class User(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
*args,
**kwargs,
):
super().__init__(params, cookie, proxy, *args, **kwargs, )
async def run(self, *args,... | self.console.print("该功能暂不开放!", style=WARNING)
| self.console.print("该功能暂不开放!", style=WARNING)
| 2 | 96 | 20 | 116 | from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["User"]
class User(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... | from typing import TYPE_CHECKING
from src.custom import WARNING
from .template import API
if TYPE_CHECKING:
from src.config import Parameter
__all__ = ["User"]
class User(API):
def __init__(self,
params: "Parameter",
cookie: str = None,
proxy: str = None,
... |
29,473 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/storage/csv.py | 51,52 | 15,58 | title | CSVLogger | 52,56 | 52,56 | class CSVLogger(BaseTextLogger):
"""CSV 格式保存数据"""
__type = "csv"
encode = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def __init__(
self,
root: Path,
title_line: tuple,
field_keys: tuple,
console: "ColorfulConsole",
old=None,... | class CSVLogger(BaseTextLogger):
"""CSV 格式保存数据"""
__type = "csv"
encode = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def __init__(
self,
root: Path,
title_line: tuple,
field_keys: tuple,
console: "ColorfulConsole",
old=None,... | if getsize(self.path) == 0:
# 如果文件没有任何数据,则写入标题行
await self.save(self.title_line)
| if getsize(self.path) == 0:
# 如果文件没有任何数据,则写入标题行
await self.save(self.title_line)
| 8 | 395 | 47 | 442 | from csv import writer
from os.path import getsize
from pathlib import Path
from platform import system
from typing import TYPE_CHECKING
from .text import BaseTextLogger
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["CSVLogger"]
class CSVLogger(BaseTextLogger):
"""CSV 格式保存数据"""
__t... | from csv import writer
from os.path import getsize
from pathlib import Path
from platform import system
from typing import TYPE_CHECKING
from .text import BaseTextLogger
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["CSVLogger"]
class CSVLogger(BaseTextLogger):
"""CSV 格式保存数据"""
__t... |
29,475 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/storage/sqlite.py | 57,58 | 11,85 | update_sheet | SQLLogger | 58,70 | 58,70 | class SQLLogger(BaseSQLLogger):
"""SQLite 数据库保存数据"""
def __init__(
self,
root: Path,
db_name: str,
title_line: tuple,
title_type: tuple,
field_keys: tuple,
old=None,
name="Solo_Download",
*args,
... | class SQLLogger(BaseSQLLogger):
"""SQLite 数据库保存数据"""
def __init__(
self,
root: Path,
db_name: str,
title_line: tuple,
title_type: tuple,
field_keys: tuple,
old=None,
name="Solo_Download",
*args,
... | old_sheet, new_sheet = self.__clean_sheet_name(self.name)
mark = new_sheet.split("_", 1)
if not old_sheet or mark[-1] == old_sheet:
self.name = new_sheet
return
mark[-1] = old_sheet
old_sheet = "_".join(mark)
if await self.__check_sheet_exists(old_... | old_sheet, new_sheet = self.__clean_sheet_name(self.name)
mark = new_sheet.split("_", 1)
if not old_sheet or mark[-1] == old_sheet:
self.name = new_sheet
return
mark[-1] = old_sheet
old_sheet = "_".join(mark)
if await self.__check_sheet_exists(old_... | 37 | 713 | 159 | 872 | from pathlib import Path
from re import sub
from aiosqlite import connect
from .sql import BaseSQLLogger
__all__ = ["SQLLogger"]
class SQLLogger(BaseSQLLogger):
"""SQLite 数据库保存数据"""
def __init__(
self,
root: Path,
db_name: str,
title_line: tuple,
... | from pathlib import Path
from re import sub
from aiosqlite import connect
from .sql import BaseSQLLogger
__all__ = ["SQLLogger"]
class SQLLogger(BaseSQLLogger):
"""SQLite 数据库保存数据"""
def __init__(
self,
root: Path,
db_name: str,
title_line: tuple,
... |
29,476 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/storage/text.py | 31,34 | 8,41 | __rename_file | BaseTextLogger | 34,41 | 34,41 | class BaseTextLogger:
def __init__(self, *args, **kwargs):
self.field_keys = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def save(self, *args, **kwargs):
pass
@classmethod
def _rename(cls, root: P... | class BaseTextLogger:
def __init__(self, *args, **kwargs):
self.field_keys = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def save(self, *args, **kwargs):
pass
@classmethod
def _rename(cls, root: P... | if old_file.exists() and not new_file.exists():
try:
old_file.rename(new_file)
return True
except PermissionError:
return False
return True
| if old_file.exists() and not new_file.exists():
try:
old_file.rename(new_file)
return True
except PermissionError:
return False
return True
| 15 | 275 | 60 | 335 | from pathlib import Path
from src.tools import PrivateRetry
__all__ = ["BaseTextLogger"]
class BaseTextLogger:
def __init__(self, *args, **kwargs):
self.field_keys = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async... | from pathlib import Path
from src.tools import PrivateRetry
__all__ = ["BaseTextLogger"]
class BaseTextLogger:
def __init__(self, *args, **kwargs):
self.field_keys = []
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async... |
29,477 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/storage/xlsx.py | 49,50 | 15,57 | title | XLSXLogger | 50,55 | 50,55 | class XLSXLogger(BaseTextLogger):
"""XLSX 格式保存数据"""
__type = "xlsx"
def __init__(
self,
root: Path,
title_line: tuple,
field_keys: tuple,
console: "ColorfulConsole",
old=None,
name="Solo_Download",
*args,
... | class XLSXLogger(BaseTextLogger):
"""XLSX 格式保存数据"""
__type = "xlsx"
def __init__(
self,
root: Path,
title_line: tuple,
field_keys: tuple,
console: "ColorfulConsole",
old=None,
name="Solo_Download",
*args,
... | if not self.sheet["A1"].value:
# 如果文件没有任何数据,则写入标题行
for col, value in enumerate(self.title_line, start=1):
self.sheet.cell(row=1, column=col, value=value)
| if not self.sheet["A1"].value:
# 如果文件没有任何数据,则写入标题行
for col, value in enumerate(self.title_line, start=1):
self.sheet.cell(row=1, column=col, value=value)
| 14 | 378 | 75 | 453 | from pathlib import Path
from typing import TYPE_CHECKING
from openpyxl import Workbook
from openpyxl import load_workbook
from .text import BaseTextLogger
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["XLSXLogger"]
class XLSXLogger(BaseTextLogger):
"""XLSX 格式保存数据"""
__type = "xls... | from pathlib import Path
from typing import TYPE_CHECKING
from openpyxl import Workbook
from openpyxl import load_workbook
from .text import BaseTextLogger
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["XLSXLogger"]
class XLSXLogger(BaseTextLogger):
"""XLSX 格式保存数据"""
__type = "xls... |
29,478 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/browser.py | 55,56 | 29,88 | run | Browser | 56,79 | 56,79 | class Browser:
"""代码参考:https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/cli.py"""
browser = (
chrome,
chromium,
opera,
opera_gx,
brave,
edge,
vivaldi,
firefox,
librewolf,
safari)
platform = {
False: SimpleNam... | class Browser:
"""代码参考:https://github.com/Johnserf-Seed/f2/blob/main/f2/apps/douyin/cli.py"""
browser = (
chrome,
chromium,
opera,
opera_gx,
brave,
edge,
vivaldi,
firefox,
librewolf,
safari)
platform = {
False: SimpleNam... | browser = self.console.input(
"自动读取指定浏览器的 Cookie 并写入配置文件\n"
"支持浏览器:1 Chrome, 2 Chromium, 3 Opera, 4 Opera GX, 5 Brave, 6 Edge, 7 Vivaldi, 8 Firefox, 9 LibreWolf, "
"10 Safari\n"
"请关闭所有浏览器,然后输入浏览器序号:")
try:
cookie = self.__read_cookie(
... | browser = self.console.input(
"自动读取指定浏览器的 Cookie 并写入配置文件\n"
"支持浏览器:1 Chrome, 2 Chromium, 3 Opera, 4 Opera GX, 5 Brave, 6 Edge, 7 Vivaldi, 8 Firefox, 9 LibreWolf, "
"10 Safari\n"
"请关闭所有浏览器,然后输入浏览器序号:")
try:
cookie = self.__read_cookie(
... | 67 | 368 | 334 | 702 | from http.cookiejar import CookieJar
from types import SimpleNamespace
from typing import TYPE_CHECKING
from browser_cookie3 import (
chrome,
chromium,
opera,
opera_gx,
brave,
edge,
vivaldi,
firefox,
librewolf,
safari,
BrowserCookieError,
)
from src.custom import WARNING
fr... | from http.cookiejar import CookieJar
from types import SimpleNamespace
from typing import TYPE_CHECKING
from browser_cookie3 import (
chrome,
chromium,
opera,
opera_gx,
brave,
edge,
vivaldi,
firefox,
librewolf,
safari,
BrowserCookieError,
)
from src.custom import WARNING
fr... |
29,479 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/choose.py | 9,14 | 1,22 | choose | 14,22 | 14,22 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["choose"]
def choose(
title: str,
options: tuple | list,
console: "ColorfulConsole",
separate=None) -> str:
FILL_FUNC_BODY | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["choose"]
def choose(
title: str,
options: tuple | list,
console: "ColorfulConsole",
separate=None) -> str:
FILL_FUNC_BODY | screen = f"{title}:\n"
row = 0
for i, j in enumerate(options, start=1):
screen += f"{i: >2d}. {j}\n"
if separate and row in separate:
screen += f"{'=' * 25}\n"
row += 1
return console.input(screen)
| screen = f"{title}:\n"
row = 0
for i, j in enumerate(options, start=1):
screen += f"{i: >2d}. {j}\n"
if separate and row in separate:
screen += f"{'=' * 25}\n"
row += 1
return console.input(screen)
| 33 | 84 | 98 | 182 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["choose"]
def choose(
title: str,
options: tuple | list,
console: "ColorfulConsole",
separate=None) -> str:
FILL_FUNC_BODY | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.tools import ColorfulConsole
__all__ = ["choose"]
def choose(
title: str,
options: tuple | list,
console: "ColorfulConsole",
separate=None) -> str:
FILL_FUNC_BODY | |
29,480 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/console.py | 16,17 | 12,19 | input | ColorfulConsole | 17,19 | 17,19 | class ColorfulConsole(Console):
def print(self, *args, style=GENERAL, highlight=False, **kwargs):
super().print(*args, style=style, highlight=highlight, **kwargs)
def input(self, prompt="", style=PROMPT, *args, **kwargs):
FILL_FUNC_BODY | class ColorfulConsole(Console):
def print(self, *args, style=GENERAL, highlight=False, **kwargs):
super().print(*args, style=style, highlight=highlight, **kwargs)
def input(self, prompt="", style=PROMPT, *args, **kwargs):
FILL_FUNC_BODY | return super().input(
Text(prompt, style=style), *args, **kwargs)
| return super().input(
Text(prompt, style=style), *args, **kwargs)
| 6 | 83 | 26 | 109 | from rich.console import Console
from rich.text import Text
from src.custom import (
PROMPT,
GENERAL
)
__all__ = ["ColorfulConsole"]
class ColorfulConsole(Console):
def print(self, *args, style=GENERAL, highlight=False, **kwargs):
super().print(*args, style=style, highlight=highlight, **kwargs)
... | from rich.console import Console
from rich.text import Text
from src.custom import (
PROMPT,
GENERAL
)
__all__ = ["ColorfulConsole"]
class ColorfulConsole(Console):
def print(self, *args, style=GENERAL, highlight=False, **kwargs):
super().print(*args, style=style, highlight=highlight, **kwargs)
... |
29,481 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/file_switch.py | 10,12 | 9,16 | deal_config | FileSwitch | 12,16 | 12,16 | class FileSwitch:
@staticmethod
def deal_config(path: "Path"):
FILL_FUNC_BODY | class FileSwitch:
@staticmethod
def deal_config(path: "Path"):
FILL_FUNC_BODY | if path.exists():
path.unlink()
else:
path.touch()
| if path.exists():
path.unlink()
else:
path.touch()
| 5 | 33 | 28 | 61 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
__all__ = ["FileSwitch"]
class FileSwitch:
@staticmethod
def deal_config(path: "Path"):
FILL_FUNC_BODY | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
__all__ = ["FileSwitch"]
class FileSwitch:
@staticmethod
def deal_config(path: "Path"):
FILL_FUNC_BODY |
29,482 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/format.py | 12,13 | 1,42 | cookie_str_to_dict | 13,25 | 13,25 | from http.cookiejar import CookieJar
from re import compile
__all__ = [
"cookie_str_to_dict",
"cookie_dict_to_str",
"cookie_jar_to_dict",
"cookie_str_to_str",
]
def cookie_str_to_dict(cookie_str: str) -> dict:
FILL_FUNC_BODYdef cookie_str_to_str(cookie_str: str) -> str:
if not cookie_str:
... | from http.cookiejar import CookieJar
from re import compile
__all__ = [
"cookie_str_to_dict",
"cookie_dict_to_str",
"cookie_jar_to_dict",
"cookie_str_to_str",
]
def cookie_str_to_dict(cookie_str: str) -> dict:
FILL_FUNC_BODYdef cookie_str_to_str(cookie_str: str) -> str:
if not cookie_str:
... | if not cookie_str:
return {}
cookie = {}
pattern = compile(r"(?P<key>[^=;,]+)=(?P<value>[^;,]+)")
matches = pattern.finditer(cookie_str)
for match in matches:
key = match.group('key').strip()
value = match.group('value').strip()
cookie[key] = value
return cookie
... | if not cookie_str:
return {}
cookie = {}
pattern = compile(r"(?P<key>[^=;,]+)=(?P<value>[^;,]+)")
matches = pattern.finditer(cookie_str)
for match in matches:
key = match.group('key').strip()
value = match.group('value').strip()
cookie[key] = value
return cookie
... | 29 | 311 | 124 | 435 | from http.cookiejar import CookieJar
from re import compile
__all__ = [
"cookie_str_to_dict",
"cookie_dict_to_str",
"cookie_jar_to_dict",
"cookie_str_to_str",
]
def cookie_str_to_dict(cookie_str: str) -> dict:
FILL_FUNC_BODYdef cookie_str_to_str(cookie_str: str) -> str:
if not cookie_str:
... | from http.cookiejar import CookieJar
from re import compile
__all__ = [
"cookie_str_to_dict",
"cookie_dict_to_str",
"cookie_jar_to_dict",
"cookie_str_to_str",
]
def cookie_str_to_dict(cookie_str: str) -> dict:
FILL_FUNC_BODYdef cookie_str_to_str(cookie_str: str) -> str:
if not cookie_str:
... | |
29,483 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/list_pop.py | 4,5 | 1,6 | safe_pop | 5,6 | 5,6 | __all__ = ["safe_pop"]
def safe_pop(data: list):
FILL_FUNC_BODY | __all__ = ["safe_pop"]
def safe_pop(data: list):
FILL_FUNC_BODY | return data.pop() if data else None
| return data.pop() if data else None
| 6 | 32 | 12 | 44 | __all__ = ["safe_pop"]
def safe_pop(data: list):
FILL_FUNC_BODY | __all__ = ["safe_pop"]
def safe_pop(data: list):
FILL_FUNC_BODY | |
29,484 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/temporary.py | 6,7 | 1,8 | timestamp | 7,8 | 7,8 | from time import time
__all__ = ["timestamp"]
def timestamp() -> str:
FILL_FUNC_BODY | from time import time
__all__ = ["timestamp"]
def timestamp() -> str:
FILL_FUNC_BODY | return str(time())[:10]
| return str(time())[:10]
| 2 | 34 | 12 | 46 | from time import time
__all__ = ["timestamp"]
def timestamp() -> str:
FILL_FUNC_BODY | from time import time
__all__ = ["timestamp"]
def timestamp() -> str:
FILL_FUNC_BODY | |
29,485 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/src/tools/timer.py | 6,7 | 1,14 | run_time | 7,14 | 7,14 | from time import time
__all__ = ["run_time"]
def run_time(function):
FILL_FUNC_BODY | from time import time
__all__ = ["run_time"]
def run_time(function):
FILL_FUNC_BODY | def inner(self, *args, **kwargs):
start = time()
result = function(self, *args, **kwargs)
print(f"{function.__name__}运行耗时: {time() - start}s")
return result
return inner
| def inner(self, *args, **kwargs):
start = time()
result = function(self, *args, **kwargs)
print(f"{function.__name__}运行耗时: {time() - start}s")
return result
return inner
| 20 | 36 | 73 | 109 | from time import time
__all__ = ["run_time"]
def run_time(function):
FILL_FUNC_BODY | from time import time
__all__ = ["run_time"]
def run_time(function):
FILL_FUNC_BODY | |
29,486 | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader | /home/hieuvd/dung_repo/raw/stars_02/JoeanAmier_TikTokDownloader/TikTokDownloader/升级工具.py | 17,18 | 1,28 | update_params | 18,26 | 18,26 | # 本程序仅用于 5.3 更新至 5.4
# 已完成:更新配置文件参数
# 待完成:迁移旧版下载记录
from json import dump
from json import load
from platform import system
from src.config import Settings
from src.custom import PROJECT_ROOT
SETTING_ROOT = PROJECT_ROOT.joinpath("settings.json")
ENCODE = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def update... | # 本程序仅用于 5.3 更新至 5.4
# 已完成:更新配置文件参数
# 待完成:迁移旧版下载记录
from json import dump
from json import load
from platform import system
from src.config import Settings
from src.custom import PROJECT_ROOT
SETTING_ROOT = PROJECT_ROOT.joinpath("settings.json")
ENCODE = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def update... | with SETTING_ROOT.open("r+", encoding=ENCODE) as f:
old_data = load(f)
with SETTING_ROOT.open("w", encoding=ENCODE) as f:
new_data = Settings.default | old_data
dump(new_data, f, indent=4, ensure_ascii=False)
print("已更新配置文件!")
| with SETTING_ROOT.open("r+", encoding=ENCODE) as f:
old_data = load(f)
with SETTING_ROOT.open("w", encoding=ENCODE) as f:
new_data = Settings.default | old_data
dump(new_data, f, indent=4, ensure_ascii=False)
print("已更新配置文件!")
| 23 | 161 | 111 | 272 | # 本程序仅用于 5.3 更新至 5.4
# 已完成:更新配置文件参数
# 待完成:迁移旧版下载记录
from json import dump
from json import load
from platform import system
from src.config import Settings
from src.custom import PROJECT_ROOT
SETTING_ROOT = PROJECT_ROOT.joinpath("settings.json")
ENCODE = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def update... | # 本程序仅用于 5.3 更新至 5.4
# 已完成:更新配置文件参数
# 待完成:迁移旧版下载记录
from json import dump
from json import load
from platform import system
from src.config import Settings
from src.custom import PROJECT_ROOT
SETTING_ROOT = PROJECT_ROOT.joinpath("settings.json")
ENCODE = "UTF-8-SIG" if system() == "Windows" else "UTF-8"
def update... | |
29,505 | /home/hieuvd/dung_repo/raw/stars_02/KeepSafe_android-resource-remover/android-resource-remover | /home/hieuvd/dung_repo/raw/stars_02/KeepSafe_android-resource-remover/android-resource-remover/setup.py | 8,9 | 1,34 | read | 9,12 | 9,12 | import os
import sys
from setuptools import setup, find_packages
version = '0.1.7'
def read(f):
FILL_FUNC_BODYsetup(name='android-resource-remover',
version=version,
description=('Android resource remover'),
long_description='\n\n'.join((read('README.md'), read('CHANGELOG'))),
keywords=['andr... | import os
import sys
from setuptools import setup, find_packages
version = '0.1.7'
def read(f):
FILL_FUNC_BODYsetup(name='android-resource-remover',
version=version,
description=('Android resource remover'),
long_description='\n\n'.join((read('README.md'), read('CHANGELOG'))),
keywords=['andr... | return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
| return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
| 3 | 317 | 32 | 349 | import os
import sys
from setuptools import setup, find_packages
version = '0.1.7'
def read(f):
FILL_FUNC_BODYsetup(name='android-resource-remover',
version=version,
description=('Android resource remover'),
long_description='\n\n'.join((read('README.md'), read('CHANGELOG'))),
keywords=['andr... | import os
import sys
from setuptools import setup, find_packages
version = '0.1.7'
def read(f):
FILL_FUNC_BODYsetup(name='android-resource-remover',
version=version,
description=('Android resource remover'),
long_description='\n\n'.join((read('README.md'), read('CHANGELOG'))),
keywords=['andr... | |
29,549 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/setup.py | 31,32 | 20,57 | adjust | _RequirementWithComment | 46,57 | 32,57 | class _RequirementWithComment(Requirement):
strict_string = "# strict"
def __init__(self, *args: Any, comment: str = "", pip_argument: Optional[str] = None, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.comment = comment
if pip_argument is not None and not pip_argument:... | class _RequirementWithComment(Requirement):
strict_string = "# strict"
def __init__(self, *args: Any, comment: str = "", pip_argument: Optional[str] = None, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.comment = comment
if pip_argument is not None and not pip_argument:... | out = str(self)
if self.strict:
return f"{out} {self.strict_string}"
if unfreeze:
for operator, version in self.specs:
if operator in ("<", "<="):
# drop upper bound
return out.replace(f"{operator}{version},", "")
... | """Remove version restrictions unless they are strict.
>>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# anything").adjust(False)
'arrow<=1.2.2,>=1.2.0'
>>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# strict").adjust(False)
'arrow<=1.2.2,>=1.2.0 # st... | 29 | 428 | 103 | 531 | #!/usr/bin/env python
import glob
import os
import re
from functools import partial
from importlib.util import module_from_spec, spec_from_file_location
from itertools import chain
from pathlib import Path
from typing import Any, Iterable, Iterator, List, Optional, Tuple, Union
from pkg_resources import Requirement, y... | #!/usr/bin/env python
import glob
import os
import re
from functools import partial
from importlib.util import module_from_spec, spec_from_file_location
from itertools import chain
from pathlib import Path
from typing import Any, Iterable, Iterator, List, Optional, Tuple, Union
from pkg_resources import Requirement, y... |
29,550 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/accuracy.py | 108,111 | 31,151 | plot | BinaryAccuracy | 148,151 | 111,151 | class BinaryAccuracy(BinaryStatScores):
r"""Compute `Accuracy`_ for binary tasks.
.. math::
\text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
As input to ``forward`` and ``update`` the metric ... | class BinaryAccuracy(BinaryStatScores):
r"""Compute `Accuracy`_ for binary tasks.
.. math::
\text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
As input to ``forward`` and ``update`` the metric ... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,594 | 16 | 1,610 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,553 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/base.py | 22,23 | 19,33 | update | _ClassificationTaskWrapper | 24,28 | 23,28 | class _ClassificationTaskWrapper(Metric):
"""Base class for wrapper metrics for classification tasks."""
def update(self, *args: Any, **kwargs: Any) -> None:
FILL_FUNC_BODY def compute(self) -> None:
"""Compute metric."""
raise NotImplementedError(
f"{self.__class__.__name__} met... | class _ClassificationTaskWrapper(Metric):
"""Base class for wrapper metrics for classification tasks."""
def update(self, *args: Any, **kwargs: Any) -> None:
"""Update metric state."""
FILL_FUNC_BODY def compute(self) -> None:
"""Compute metric."""
raise NotImplementedError(
... | raise NotImplementedError(
f"{self.__class__.__name__} metric does not have a global `update` method. Use the task specific metric."
)
| """Update metric state."""
raise NotImplementedError(
f"{self.__class__.__name__} metric does not have a global `update` method. Use the task specific metric."
)
| 17 | 122 | 47 | 169 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,554 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/calibration_error.py | 129,130 | 41,189 | update | BinaryCalibrationError | 131,140 | 130,140 | class BinaryCalibrationError(Metric):
r"""`Top-label Calibration Error`_ for binary tasks.
The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
predicted output probabilities of the model matches the actual probabilities of the ground truth distribut... | class BinaryCalibrationError(Metric):
r"""`Top-label Calibration Error`_ for binary tasks.
The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
predicted output probabilities of the model matches the actual probabilities of the ground truth distribut... | if self.validate_args:
_binary_calibration_error_tensor_validation(preds, target, self.ignore_index)
preds, target = _binary_confusion_matrix_format(
preds, target, threshold=0.0, ignore_index=self.ignore_index, convert_to_labels=False
)
confidences, accuracies = ... | """Update metric states with predictions and targets."""
if self.validate_args:
_binary_calibration_error_tensor_validation(preds, target, self.ignore_index)
preds, target = _binary_confusion_matrix_format(
preds, target, threshold=0.0, ignore_index=self.ignore_index, con... | 22 | 1,794 | 146 | 1,940 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,556 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/f_beta.py | 695,698 | 597,738 | plot | BinaryF1Score | 735,738 | 698,738 | class BinaryF1Score(BinaryFBetaScore):
r"""Compute F-1 score for binary tasks.
.. math::
F_{1} = 2\frac{\text{precision} * \text{recall}}{(\text{precision}) + \text{recall}}
The metric is only proper defined when :math:`\text{TP} + \text{FP} \neq 0 \wedge \text{TP} + \text{FN} \neq 0`
where :m... | class BinaryF1Score(BinaryFBetaScore):
r"""Compute F-1 score for binary tasks.
.. math::
F_{1} = 2\frac{\text{precision} * \text{recall}}{(\text{precision}) + \text{recall}}
The metric is only proper defined when :math:`\text{TP} + \text{FP} \neq 0 \wedge \text{TP} + \text{FN} \neq 0`
where :m... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,850 | 16 | 1,866 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,563 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/group_fairness.py | 133,134 | 59,157 | update | BinaryGroupStatRates | 142,148 | 134,148 | class BinaryGroupStatRates(_AbstractGroupStatScores):
r"""Computes the true/false positives and true/false negatives rates for binary classification by group.
Related to `Type I and Type II errors`_.
Accepts the following input tensors:
- ``preds`` (int or float tensor): ``(N, ...)``. If preds is a f... | class BinaryGroupStatRates(_AbstractGroupStatScores):
r"""Computes the true/false positives and true/false negatives rates for binary classification by group.
Related to `Type I and Type II errors`_.
Accepts the following input tensors:
- ``preds`` (int or float tensor): ``(N, ...)``. If preds is a f... | group_stats = _binary_groups_stat_scores(
preds, target, groups, self.num_groups, self.threshold, self.ignore_index, self.validate_args
)
self._update_states(group_stats)
| """Update state with predictions, target and group identifiers.
Args:
preds: Tensor with predictions.
target: Tensor with true labels.
groups: Tensor with group identifiers. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
"""
group_s... | 12 | 1,259 | 70 | 1,329 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... |
29,564 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/group_fairness.py | 50,51 | 35,59 | _update_states | _AbstractGroupStatScores | 51,59 | 51,59 | class _AbstractGroupStatScores(Metric):
"""Create and update states for computing group stats tp, fp, tn and fn."""
tp: Tensor
fp: Tensor
tn: Tensor
fn: Tensor
def _create_states(self, num_groups: int) -> None:
default = lambda: torch.zeros(num_groups, dtype=torch.long)
self.ad... | class _AbstractGroupStatScores(Metric):
"""Create and update states for computing group stats tp, fp, tn and fn."""
tp: Tensor
fp: Tensor
tn: Tensor
fn: Tensor
def _create_states(self, num_groups: int) -> None:
default = lambda: torch.zeros(num_groups, dtype=torch.long)
self.ad... | for group, stats in enumerate(group_stats):
tp, fp, tn, fn = stats
self.tp[group] += tp
self.fp[group] += fp
self.tn[group] += tn
self.fn[group] += fn
| for group, stats in enumerate(group_stats):
tp, fp, tn, fn = stats
self.tp[group] += tp
self.fp[group] += fp
self.tn[group] += tn
self.fn[group] += fn
| 23 | 256 | 81 | 337 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... |
29,565 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/hamming.py | 112,113 | 35,160 | compute | BinaryHammingDistance | 114,117 | 113,117 | class BinaryHammingDistance(BinaryStatScores):
r"""Compute the average `Hamming distance`_ (also known as Hamming loss) for binary tasks.
.. math::
\text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
Where :math:`y` is a tensor of target values, :math:`\hat{... | class BinaryHammingDistance(BinaryStatScores):
r"""Compute the average `Hamming distance`_ (also known as Hamming loss) for binary tasks.
.. math::
\text{Hamming distance} = \frac{1}{N \cdot L} \sum_i^N \sum_l^L 1(y_{il} \neq \hat{y}_{il})
Where :math:`y` is a tensor of target values, :math:`\hat{... | tp, fp, tn, fn = self._final_state()
return _hamming_distance_reduce(tp, fp, tn, fn, average="binary", multidim_average=self.multidim_average)
| """Compute metric."""
tp, fp, tn, fn = self._final_state()
return _hamming_distance_reduce(tp, fp, tn, fn, average="binary", multidim_average=self.multidim_average)
| 13 | 1,627 | 66 | 1,693 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,568 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/precision_recall.py | 114,115 | 40,171 | compute | BinaryPrecision | 116,128 | 115,128 | class BinaryPrecision(BinaryStatScores):
r"""Compute `Precision`_ for binary tasks.
.. math:: \text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}
Where :math:`\text{TP}` and :math:`\text{FP}` represent the number of true positives and false positives
respectively. The metric is only proper defi... | class BinaryPrecision(BinaryStatScores):
r"""Compute `Precision`_ for binary tasks.
.. math:: \text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}
Where :math:`\text{TP}` and :math:`\text{FP}` represent the number of true positives and false positives
respectively. The metric is only proper defi... | tp, fp, tn, fn = self._final_state()
return _precision_recall_reduce(
"precision",
tp,
fp,
tn,
fn,
average="binary",
multidim_average=self.multidim_average,
zero_division=self.zero_division,
)
| """Compute metric."""
tp, fp, tn, fn = self._final_state()
return _precision_recall_reduce(
"precision",
tp,
fp,
tn,
fn,
average="binary",
multidim_average=self.multidim_average,
zero_division=self.ze... | 17 | 1,620 | 110 | 1,730 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,569 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/precision_recall.py | 574,575 | 500,631 | compute | BinaryRecall | 576,588 | 575,588 | class BinaryRecall(BinaryStatScores):
r"""Compute `Recall`_ for binary tasks.
.. math:: \text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}
Where :math:`\text{TP}` and :math:`\text{FN}` represent the number of true positives and false negatives
respectively. The metric is only proper defined when ... | class BinaryRecall(BinaryStatScores):
r"""Compute `Recall`_ for binary tasks.
.. math:: \text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}
Where :math:`\text{TP}` and :math:`\text{FN}` represent the number of true positives and false negatives
respectively. The metric is only proper defined when ... | tp, fp, tn, fn = self._final_state()
return _precision_recall_reduce(
"recall",
tp,
fp,
tn,
fn,
average="binary",
multidim_average=self.multidim_average,
zero_division=self.zero_division,
)
| """Compute metric."""
tp, fp, tn, fn = self._final_state()
return _precision_recall_reduce(
"recall",
tp,
fp,
tn,
fn,
average="binary",
multidim_average=self.multidim_average,
zero_division=self.zero_... | 17 | 1,607 | 110 | 1,717 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,574 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/classification/specificity.py | 106,109 | 31,149 | plot | BinarySpecificity | 146,149 | 109,149 | class BinarySpecificity(BinaryStatScores):
r"""Compute `Specificity`_ for binary tasks.
.. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
respectively. The metric is only prope... | class BinarySpecificity(BinaryStatScores):
r"""Compute `Specificity`_ for binary tasks.
.. math:: \text{Specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}}
Where :math:`\text{TN}` and :math:`\text{FP}` represent the number of true negatives and false positives
respectively. The metric is only prope... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,596 | 16 | 1,612 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,577 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/adjusted_mutual_info_score.py | 90,91 | 31,129 | plot | AdjustedMutualInfoScore | 128,129 | 91,129 | class AdjustedMutualInfoScore(MutualInfoScore):
r"""Compute `Adjusted Mutual Information Score`_.
.. math::
AMI(U,V) = \frac{MI(U,V) - E(MI(U,V))}{avg(H(U), H(V)) - E(MI(U,V))}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions, :math:`M_p(U,V)` is the
generaliz... | class AdjustedMutualInfoScore(MutualInfoScore):
r"""Compute `Adjusted Mutual Information Score`_.
.. math::
AMI(U,V) = \frac{MI(U,V) - E(MI(U,V))}{avg(H(U), H(V)) - E(MI(U,V))}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions, :math:`M_p(U,V)` is the
generaliz... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,295 | 12 | 1,307 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,578 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/adjusted_rand_score.py | 84,85 | 28,127 | compute | AdjustedRandScore | 86,88 | 85,88 | class AdjustedRandScore(Metric):
r"""Compute `Adjusted Rand Score`_ (also known as Adjusted Rand Index).
.. math::
ARS(U, V) = (\text{RS} - \text{Expected RS}) / (\text{Max RS} - \text{Expected RS})
The adjusted rand score :math:`\text{ARS}` is in essence the :math:`\text{RS}` (rand score) adjuste... | class AdjustedRandScore(Metric):
r"""Compute `Adjusted Rand Score`_ (also known as Adjusted Rand Index).
.. math::
ARS(U, V) = (\text{RS} - \text{Expected RS}) / (\text{Max RS} - \text{Expected RS})
The adjusted rand score :math:`\text{ARS}` is in essence the :math:`\text{RS}` (rand score) adjuste... | return adjusted_rand_score(dim_zero_cat(self.preds), dim_zero_cat(self.target))
| """Compute mutual information over state."""
return adjusted_rand_score(dim_zero_cat(self.preds), dim_zero_cat(self.target))
| 3 | 1,224 | 33 | 1,257 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,579 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/calinski_harabasz_score.py | 86,87 | 28,129 | compute | CalinskiHarabaszScore | 88,90 | 87,90 | class CalinskiHarabaszScore(Metric):
r"""Compute Calinski Harabasz Score (also known as variance ratio criterion) for clustering algorithms.
.. math::
CHS(X, L) = \frac{B(X, L) \cdot (n_\text{samples} - n_\text{labels})}{W(X, L) \cdot (n_\text{labels} - 1)}
where :math:`B(X, L)` is the between-clu... | class CalinskiHarabaszScore(Metric):
r"""Compute Calinski Harabasz Score (also known as variance ratio criterion) for clustering algorithms.
.. math::
CHS(X, L) = \frac{B(X, L) \cdot (n_\text{samples} - n_\text{labels})}{W(X, L) \cdot (n_\text{labels} - 1)}
where :math:`B(X, L)` is the between-clu... | return calinski_harabasz_score(dim_zero_cat(self.data), dim_zero_cat(self.labels))
| """Compute the Calinski Harabasz Score over all data and labels."""
return calinski_harabasz_score(dim_zero_cat(self.data), dim_zero_cat(self.labels))
| 3 | 1,275 | 37 | 1,312 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,580 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/davies_bouldin_score.py | 100,101 | 28,139 | plot | DaviesBouldinScore | 138,139 | 101,139 | class DaviesBouldinScore(Metric):
r"""Compute `Davies-Bouldin Score`_ for clustering algorithms.
Given the following quantities:
.. math::
S_i = \left( \frac{1}{T_i} \sum_{j=1}^{T_i} ||X_j - A_i||^2_2 \right)^{1/2}
where :math:`T_i` is the number of samples in cluster :math:`i`, :math:`X_j` i... | class DaviesBouldinScore(Metric):
r"""Compute `Davies-Bouldin Score`_ for clustering algorithms.
Given the following quantities:
.. math::
S_i = \left( \frac{1}{T_i} \sum_{j=1}^{T_i} ||X_j - A_i||^2_2 \right)^{1/2}
where :math:`T_i` is the number of samples in cluster :math:`i`, :math:`X_j` i... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,402 | 12 | 1,414 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,581 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/dunn_index.py | 79,80 | 28,129 | update | DunnIndex | 81,84 | 80,84 | class DunnIndex(Metric):
r"""Compute `Dunn Index`_.
.. math::
DI_m = \frac{\min_{1\leq i<j\leq m} \delta(C_i,C_j)}{\max_{1\leq k\leq m} \Delta_k}
Where :math:`C_i` is a cluster of tensors, :math:`C_j` is a cluster of tensors,
and :math:`\delta(C_i,C_j)` is the intercluster distance metric for ... | class DunnIndex(Metric):
r"""Compute `Dunn Index`_.
.. math::
DI_m = \frac{\min_{1\leq i<j\leq m} \delta(C_i,C_j)}{\max_{1\leq k\leq m} \Delta_k}
Where :math:`C_i` is a cluster of tensors, :math:`C_j` is a cluster of tensors,
and :math:`\delta(C_i,C_j)` is the intercluster distance metric for ... | self.data.append(data)
self.labels.append(labels)
| """Update state with predictions and targets."""
self.data.append(data)
self.labels.append(labels)
| 2 | 1,227 | 24 | 1,251 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,582 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/fowlkes_mallows_index.py | 80,81 | 28,123 | compute | FowlkesMallowsIndex | 82,84 | 81,84 | class FowlkesMallowsIndex(Metric):
r"""Compute `Fowlkes-Mallows Index`_.
.. math::
FMI(U,V) = \frac{TP}{\sqrt{(TP + FP) * (TP + FN)}}
Where :math:`TP` is the number of true positives, :math:`FP` is the number of false positives, and :math:`FN` is
the number of false negatives.
As input to... | class FowlkesMallowsIndex(Metric):
r"""Compute `Fowlkes-Mallows Index`_.
.. math::
FMI(U,V) = \frac{TP}{\sqrt{(TP + FP) * (TP + FN)}}
Where :math:`TP` is the number of true positives, :math:`FP` is the number of false positives, and :math:`FN` is
the number of false negatives.
As input to... | return fowlkes_mallows_index(dim_zero_cat(self.preds), dim_zero_cat(self.target))
| """Compute Fowlkes-Mallows index over state."""
return fowlkes_mallows_index(dim_zero_cat(self.preds), dim_zero_cat(self.target))
| 3 | 1,109 | 37 | 1,146 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,583 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/homogeneity_completeness_v_measure.py | 184,185 | 129,225 | plot | CompletenessScore | 222,225 | 185,225 | class CompletenessScore(Metric):
r"""Compute `Completeness Score`_.
A clustering result satisfies completeness if all the data points that are members of a given class are elements of
the same cluster. The metric is not symmetric, therefore swapping ``preds`` and ``target`` yields a different score.
T... | class CompletenessScore(Metric):
r"""Compute `Completeness Score`_.
A clustering result satisfies completeness if all the data points that are members of a given class are elements of
the same cluster. The metric is not symmetric, therefore swapping ``preds`` and ``target`` yields a different score.
T... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,091 | 16 | 1,107 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,584 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/homogeneity_completeness_v_measure.py | 79,80 | 32,129 | update | HomogeneityScore | 81,84 | 80,84 | class HomogeneityScore(Metric):
r"""Compute `Homogeneity Score`_.
The homogeneity score is a metric to measure the homogeneity of a clustering. A clustering result satisfies
homogeneity if all of its clusters contain only data points which are members of a single class. The metric is not
symmetric, the... | class HomogeneityScore(Metric):
r"""Compute `Homogeneity Score`_.
The homogeneity score is a metric to measure the homogeneity of a clustering. A clustering result satisfies
homogeneity if all of its clusters contain only data points which are members of a single class. The metric is not
symmetric, the... | self.preds.append(preds)
self.target.append(target)
| """Update state with predictions and targets."""
self.preds.append(preds)
self.target.append(target)
| 2 | 1,101 | 26 | 1,127 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,585 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/homogeneity_completeness_v_measure.py | 286,287 | 225,329 | compute | VMeasureScore | 288,290 | 287,290 | class VMeasureScore(Metric):
r"""Compute `V-Measure Score`_.
The V-measure is the harmonic mean between homogeneity and completeness:
..math::
v = \frac{(1 + \beta) * homogeneity * completeness}{\beta * homogeneity + completeness}
where :math:`\beta` is a weight parameter that defines the wei... | class VMeasureScore(Metric):
r"""Compute `V-Measure Score`_.
The V-measure is the harmonic mean between homogeneity and completeness:
..math::
v = \frac{(1 + \beta) * homogeneity * completeness}{\beta * homogeneity + completeness}
where :math:`\beta` is a weight parameter that defines the wei... | return v_measure_score(dim_zero_cat(self.preds), dim_zero_cat(self.target), beta=self.beta)
| """Compute rand score over state."""
return v_measure_score(dim_zero_cat(self.preds), dim_zero_cat(self.target), beta=self.beta)
| 4 | 1,218 | 39 | 1,257 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,586 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/mutual_info_score.py | 89,90 | 28,128 | plot | MutualInfoScore | 127,128 | 90,128 | class MutualInfoScore(Metric):
r"""Compute `Mutual Information Score`_.
.. math::
MI(U,V) = \sum_{i=1}^{|U|} \sum_{j=1}^{|V|} \frac{|U_i\cap V_j|}{N}
\log\frac{N|U_i\cap V_j|}{|U_i||V_j|}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions,
:math:`|U_i|` ... | class MutualInfoScore(Metric):
r"""Compute `Mutual Information Score`_.
.. math::
MI(U,V) = \sum_{i=1}^{|U|} \sum_{j=1}^{|V|} \frac{|U_i\cap V_j|}{N}
\log\frac{N|U_i\cap V_j|}{|U_i||V_j|}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions,
:math:`|U_i|` ... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,244 | 12 | 1,256 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,587 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/normalized_mutual_info_score.py | 89,90 | 31,128 | plot | NormalizedMutualInfoScore | 127,128 | 90,128 | class NormalizedMutualInfoScore(MutualInfoScore):
r"""Compute `Normalized Mutual Information Score`_.
.. math::
NMI(U,V) = \frac{MI(U,V)}{M_p(U,V)}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions, :math:`M_p(U,V)` is the
generalized mean of order :math:`p` of... | class NormalizedMutualInfoScore(MutualInfoScore):
r"""Compute `Normalized Mutual Information Score`_.
.. math::
NMI(U,V) = \frac{MI(U,V)}{M_p(U,V)}
Where :math:`U` is a tensor of target values, :math:`V` is a tensor of predictions, :math:`M_p(U,V)` is the
generalized mean of order :math:`p` of... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,228 | 12 | 1,240 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,588 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/clustering/rand_score.py | 87,88 | 28,126 | plot | RandScore | 125,126 | 88,126 | class RandScore(Metric):
r"""Compute `Rand Score`_ (alternatively known as Rand Index).
.. math::
RS(U, V) = \text{number of agreeing pairs} / \text{number of pairs}
The number of agreeing pairs is every :math:`(i, j)` pair of samples where :math:`i \in U` and :math:`j \in V`
(the predicted an... | class RandScore(Metric):
r"""Compute `Rand Score`_ (alternatively known as Rand Index).
.. math::
RS(U, V) = \text{number of agreeing pairs} / \text{number of pairs}
The number of agreeing pairs is every :math:`(i, j)` pair of samples where :math:`i \in U` and :math:`j \in V`
(the predicted an... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,151 | 12 | 1,163 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,592 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/audio/_deprecated.py | 62,70 | 1,128 | _signal_distortion_ratio | 91,102 | 70,102 | from typing import Any, Callable, Optional, Tuple
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.functional.audio.pit import permutation_invariant_training, pit_permutate
from torchmetrics.functional.audio.sdr import scale_invariant_signal_distortion_ratio, signal_distortion_ratio
fr... | from typing import Any, Callable, Optional, Tuple
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.functional.audio.pit import permutation_invariant_training, pit_permutate
from torchmetrics.functional.audio.sdr import scale_invariant_signal_distortion_ratio, signal_distortion_ratio
fr... | _deprecated_root_import_func("signal_distortion_ratio", "audio")
return signal_distortion_ratio(
preds=preds,
target=target,
use_cg_iter=use_cg_iter,
filter_length=filter_length,
zero_mean=zero_mean,
load_diag=load_diag,
)
| """Wrapper for deprecated import.
>>> import torch
>>> g = torch.manual_seed(1)
>>> preds = torch.randn(8000)
>>> target = torch.randn(8000)
>>> _signal_distortion_ratio(preds, target)
tensor(-12.0589)
>>> # use with permutation_invariant_training
>>> preds = torch.randn(4, 2, 8000)... | 11 | 1,626 | 109 | 1,735 | from typing import Any, Callable, Optional, Tuple
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.functional.audio.pit import permutation_invariant_training, pit_permutate
from torchmetrics.functional.audio.sdr import scale_invariant_signal_distortion_ratio, signal_distortion_ratio
fr... | from typing import Any, Callable, Optional, Tuple
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.functional.audio.pit import permutation_invariant_training, pit_permutate
from torchmetrics.functional.audio.sdr import scale_invariant_signal_distortion_ratio, signal_distortion_ratio
fr... | |
29,593 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/audio/snr.py | 22,23 | 1,133 | signal_noise_ratio | 23,64 | 23,64 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | r"""Calculate `Signal-to-noise ratio`_ (SNR_) meric for evaluating quality of audio.
.. math::
\text{SNR} = \frac{P_{signal}}{P_{noise}}
where :math:`P` denotes the power of each signal. The SNR metric compares the level of the desired signal to
the level of background noise. Therefore, a hig... | r"""Calculate `Signal-to-noise ratio`_ (SNR_) meric for evaluating quality of audio.
.. math::
\text{SNR} = \frac{P_{signal}}{P_{noise}}
where :math:`P` denotes the power of each signal. The SNR metric compares the level of the desired signal to
the level of background noise. Therefore, a hig... | 163 | 1,161 | 532 | 1,693 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,611 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/adjusted_rand_score.py | 39,40 | 1,76 | _adjusted_rand_score_compute | 49,55 | 40,55 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | (tn, fp), (fn, tp) = calculate_pair_cluster_confusion_matrix(contingency=contingency)
if fn == 0 and fp == 0:
return torch.ones_like(tn, dtype=torch.float32)
return 2.0 * (tp * tn - fn * fp) / ((tp + fn) * (fn + tn) + (tp + fp) * (fp + tn))
| """Compute the rand score based on the contingency matrix.
Args:
contingency: contingency matrix
Returns:
rand_score: rand score
"""
(tn, fp), (fn, tp) = calculate_pair_cluster_confusion_matrix(contingency=contingency)
if fn == 0 and fp == 0:
return torch.ones_like(tn,... | 43 | 666 | 122 | 788 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,612 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/calinski_harabasz_score.py | 23,24 | 1,63 | calinski_harabasz_score | 43,63 | 24,63 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | _validate_intrinsic_cluster_data(data, labels)
# convert to zero indexed labels
unique_labels, labels = torch.unique(labels, return_inverse=True)
num_labels = len(unique_labels)
num_samples = data.shape[0]
_validate_intrinsic_labels_to_samples(num_labels, num_samples)
mean = data.mean(dim=... | """Compute the Calinski Harabasz Score (also known as variance ratio criterion) for clustering algorithms.
Args:
data: float tensor with shape ``(N,d)`` with the embedded data.
labels: single integer tensor with shape ``(N,)`` with cluster labels
Returns:
Scalar tensor with the Cal... | 81 | 466 | 363 | 829 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,613 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/davies_bouldin_score.py | 23,24 | 1,68 | davies_bouldin_score | 43,68 | 24,68 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | _validate_intrinsic_cluster_data(data, labels)
# convert to zero indexed labels
unique_labels, labels = torch.unique(labels, return_inverse=True)
num_labels = len(unique_labels)
num_samples, dim = data.shape
_validate_intrinsic_labels_to_samples(num_labels, num_samples)
intra_dists = torch... | """Compute the Davies bouldin score for clustering algorithms.
Args:
data: float tensor with shape ``(N,d)`` with the embedded data.
labels: single integer tensor with shape ``(N,)`` with cluster labels
Returns:
Scalar tensor with the Davies bouldin score
Example:
>>> ... | 86 | 449 | 470 | 919 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,614 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/homogeneity_completeness_v_measure.py | 23,24 | 1,116 | _homogeneity_score_compute | 25,39 | 24,39 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | check_cluster_labels(preds, target)
if len(target) == 0: # special case where no clustering is defined
zero = torch.tensor(0.0, dtype=torch.float32, device=preds.device)
return zero.clone(), zero.clone(), zero.clone(), zero.clone()
entropy_target = calculate_entropy(target)
entropy_pr... | """Computes the homogeneity score of a clustering given the predicted and target cluster labels."""
check_cluster_labels(preds, target)
if len(target) == 0: # special case where no clustering is defined
zero = torch.tensor(0.0, dtype=torch.float32, device=preds.device)
return zero.clone(),... | 48 | 1,209 | 194 | 1,403 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,615 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/normalized_mutual_info_score.py | 28,31 | 1,60 | normalized_mutual_info_score | 49,60 | 31,60 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | check_cluster_labels(preds, target)
_validate_average_method_arg(average_method)
mutual_info = mutual_info_score(preds, target)
if torch.allclose(mutual_info, torch.tensor(0.0), atol=torch.finfo().eps):
return mutual_info
normalizer = calculate_generalized_mean(
torch.stack([calcula... | """Compute normalized mutual information between two clusterings.
Args:
preds: predicted cluster labels
target: ground truth cluster labels
average_method: normalizer computation method
Returns:
Scalar tensor with normalized mutual info score between 0.0 and 1.0
Exampl... | 24 | 503 | 151 | 654 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,616 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/clustering/rand_score.py | 39,40 | 1,83 | _rand_score_compute | 49,62 | 40,62 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | pair_matrix = calculate_pair_cluster_confusion_matrix(contingency=contingency)
numerator = pair_matrix.diagonal().sum()
denominator = pair_matrix.sum()
if numerator == denominator or denominator == 0:
# Special limit cases: no clustering since the data is not split;
# or trivial cluster... | """Compute the rand score based on the contingency matrix.
Args:
contingency: contingency matrix
Returns:
rand_score: rand score
"""
pair_matrix = calculate_pair_cluster_confusion_matrix(contingency=contingency)
numerator = pair_matrix.diagonal().sum()
denominator = pair_... | 56 | 642 | 157 | 799 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,617 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/detection/_deprecated.py | 39,46 | 1,71 | _panoptic_quality | 63,71 | 46,71 | from typing import Collection
from torch import Tensor
from torchmetrics.functional.detection.panoptic_qualities import modified_panoptic_quality, panoptic_quality
from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_1_12
from torchmetrics.utilities.prints import _deprecated_root_import_func
if not _TORCH... | from typing import Collection
from torch import Tensor
from torchmetrics.functional.detection.panoptic_qualities import modified_panoptic_quality, panoptic_quality
from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_1_12
from torchmetrics.utilities.prints import _deprecated_root_import_func
if not _TORCH... | _deprecated_root_import_func("panoptic_quality", "detection")
return panoptic_quality(
preds=preds,
target=target,
things=things,
stuffs=stuffs,
allow_unknown_preds_category=allow_unknown_preds_category,
)
| """Wrapper for deprecated import.
>>> from torch import tensor
>>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
... [[0, 0], [0, 0], [6, 0], [0, 1]],
... [[0, 0], [0, 0], [6, 0], [0, 1]],
... [[0, 0], [7, 0], [6, 0], [1, 0]],
... ... | 10 | 925 | 90 | 1,015 | from typing import Collection
from torch import Tensor
from torchmetrics.functional.detection.panoptic_qualities import modified_panoptic_quality, panoptic_quality
from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_1_12
from torchmetrics.utilities.prints import _deprecated_root_import_func
if not _TORCH... | from typing import Collection
from torch import Tensor
from torchmetrics.functional.detection.panoptic_qualities import modified_panoptic_quality, panoptic_quality
from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_1_12
from torchmetrics.utilities.prints import _deprecated_root_import_func
if not _TORCH... | |
29,620 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/d_lambda.py | 49,55 | 1,154 | _spectral_distortion_index_compute | 76,110 | 55,110 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | length = preds.shape[1]
m1 = torch.zeros((length, length), device=preds.device)
m2 = torch.zeros((length, length), device=preds.device)
for k in range(length):
num = length - (k + 1)
if num == 0:
continue
stack1 = target[:, k : k + 1, :, :].repeat(num, 1, 1, 1)
... | """Compute Spectral Distortion Index (SpectralDistortionIndex_).
Args:
preds: Low resolution multispectral image
target: High resolution fused image
p: a parameter to emphasize large spectral difference
reduction: a method to reduce metric score over labels.
- ``'el... | 198 | 1,336 | 560 | 1,896 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,621 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/ergas.py | 86,92 | 1,124 | error_relative_global_dimensionless_synthesis | 122,124 | 92,124 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | preds, target = _ergas_update(preds, target)
return _ergas_compute(preds, target, ratio, reduction)
| """Calculates `Error relative global dimensionless synthesis`_ (ERGAS) metric.
Args:
preds: estimated image
target: ground truth image
ratio: ratio of high resolution to low resolution
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``:... | 10 | 1,332 | 38 | 1,370 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,622 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/gradients.py | 46,47 | 1,81 | image_gradients | 78,81 | 47,81 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | _image_gradients_validate(img)
return _compute_image_gradients(img)
| """Compute `Gradient Computation of Image`_ of a given image using finite difference.
Args:
img: An ``(N, C, H, W)`` input tensor where ``C`` is the number of image channels
Return:
Tuple of ``(dy, dx)`` with each gradient of shape ``[N, C, H, W]``
Raises:
TypeError:
... | 3 | 993 | 29 | 1,022 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,624 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/perceptual_path_length.py | 40,41 | 27,50 | sample | GeneratorType | 47,50 | 41,50 | class GeneratorType(nn.Module):
"""Basic interface for a generator model.
Users can inherit from this class and implement their own generator model. The requirements are that the ``sample``
method is implemented and that the ``num_classes`` attribute is present when ``conditional=True`` metric.
"""
... | class GeneratorType(nn.Module):
"""Basic interface for a generator model.
Users can inherit from this class and implement their own generator model. The requirements are that the ``sample``
method is implemented and that the ``num_classes`` attribute is present when ``conditional=True`` metric.
"""
... | raise NotImplementedError
| """Sample from the generator.
Args:
num_samples: Number of samples to generate.
"""
raise NotImplementedError
| 2 | 172 | 13 | 185 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
29,625 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/qnr.py | 28,39 | 1,83 | quality_with_no_reference | 76,83 | 39,83 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | if not isinstance(alpha, (int, float)) or alpha < 0:
raise ValueError(f"Expected `alpha` to be a non-negative real number. Got alpha: {alpha}.")
if not isinstance(beta, (int, float)) or beta < 0:
raise ValueError(f"Expected `beta` to be a non-negative real number. Got beta: {beta}.")
d_lambd... | """Calculate `Quality with No Reference`_ (QualityWithNoReference_) also known as QNR.
Metric is used to compare the joint spectral and spatial distortion between two images.
Args:
preds: High resolution multispectral image.
ms: Low resolution multispectral image.
pan: High resolut... | 69 | 828 | 182 | 1,010 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,626 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/rase.py | 71,72 | 1,104 | relative_average_spectral_error | 94,104 | 72,104 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | if not isinstance(window_size, int) or isinstance(window_size, int) and window_size < 1:
raise ValueError("Argument `window_size` is expected to be a positive integer.")
img_shape = target.shape[1:] # [num_channels, width, height]
rmse_map = torch.zeros(img_shape, dtype=target.dtype, device=target... | """Compute Relative Average Spectral Error (RASE) (RelativeAverageSpectralError_).
Args:
preds: Deformed image
target: Ground truth image
window_size: Sliding window used for rmse calculation
Return:
Relative Average Spectral Error (RASE)
Example:
>>> from torc... | 57 | 1,082 | 235 | 1,317 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | |
29,627 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/rmse_sw.py | 111,114 | 1,149 | root_mean_squared_error_using_sliding_window | 138,149 | 114,149 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | if not isinstance(window_size, int) or isinstance(window_size, int) and window_size < 1:
raise ValueError("Argument `window_size` is expected to be a positive integer.")
rmse_val_sum, rmse_map, total_images = _rmse_sw_update(
preds, target, window_size, rmse_val_sum=None, rmse_map=None, total_i... | """Compute Root Mean Squared Error (RMSE) using sliding window.
Args:
preds: Deformed image
target: Ground truth image
window_size: Sliding window used for rmse calculation
return_rmse_map: An indication whether the full rmse reduced image should be returned.
Return:
... | 46 | 1,639 | 183 | 1,822 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | |
29,628 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/sam.py | 83,88 | 1,124 | spectral_angle_mapper | 122,124 | 88,124 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | preds, target = _sam_update(preds, target)
return _sam_compute(preds, target, reduction)
| """Universal Spectral Angle Mapper.
Args:
preds: estimated image
target: ground truth image
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'`` or ``None``... | 9 | 1,366 | 34 | 1,400 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,629 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/tv.py | 20,21 | 1,79 | _total_variation_update | 22,33 | 21,33 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | if img.ndim != 4:
raise RuntimeError(f"Expected input `img` to be an 4D tensor, but got {img.shape}")
diff1 = img[..., 1:, :] - img[..., :-1, :]
diff2 = img[..., :, 1:] - img[..., :, :-1]
res1 = diff1.abs().sum([1, 2, 3])
res2 = diff2.abs().sum([1, 2, 3])
score = res1 + res2
return ... | """Compute total variation statistics on current batch."""
if img.ndim != 4:
raise RuntimeError(f"Expected input `img` to be an 4D tensor, but got {img.shape}")
diff1 = img[..., 1:, :] - img[..., :-1, :]
diff2 = img[..., :, 1:] - img[..., :, :-1]
res1 = diff1.abs().sum([1, 2, 3])
res2 =... | 52 | 738 | 165 | 903 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,632 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/image/vif.py | 33,34 | 1,116 | _vif_per_channel | 34,86 | 34,86 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | dtype = preds.dtype
device = preds.device
preds = preds.unsqueeze(1) # Add channel dimension
target = target.unsqueeze(1)
# Constant for numerical stability
eps = torch.tensor(1e-10, dtype=dtype, device=device)
sigma_n_sq = torch.tensor(sigma_n_sq, dtype=dtype, device=device)
preds_v... | dtype = preds.dtype
device = preds.device
preds = preds.unsqueeze(1) # Add channel dimension
target = target.unsqueeze(1)
# Constant for numerical stability
eps = torch.tensor(1e-10, dtype=dtype, device=device)
sigma_n_sq = torch.tensor(sigma_n_sq, dtype=dtype, device=device)
preds_v... | 211 | 1,118 | 872 | 1,990 | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | # Copyright The PyTorch Lightning 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 applicable law or agreed to i... | |
29,634 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/nominal/fleiss_kappa.py | 61,62 | 1,102 | fleiss_kappa | 62,102 | 62,102 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
.. math::
\kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
agreement probability over all... | r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
.. math::
\kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
agreement probability over all... | 241 | 753 | 669 | 1,422 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,638 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/nominal/utils.py | 23,24 | 1,147 | _nominal_input_validation | 24,35 | 24,35 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | if nan_strategy not in ["replace", "drop"]:
raise ValueError(
f"Argument `nan_strategy` is expected to be one of `['replace', 'drop']`, but got {nan_strategy}"
)
if nan_strategy == "replace" and not isinstance(nan_replace_value, (float, int)):
raise ValueError(
"A... | if nan_strategy not in ["replace", "drop"]:
raise ValueError(
f"Argument `nan_strategy` is expected to be one of `['replace', 'drop']`, but got {nan_strategy}"
)
if nan_strategy == "replace" and not isinstance(nan_replace_value, (float, int)):
raise ValueError(
"A... | 54 | 1,840 | 157 | 1,997 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | |
29,639 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/cosine.py | 48,54 | 1,92 | pairwise_cosine_similarity | 54,92 | 54,92 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... | r"""Calculate pairwise cosine similarity.
.. math::
s_{cos}(x,y) = \frac{<x,y>}{||x|| \cdot ||y||}
= \frac{\sum_{d=1}^D x_d \cdot y_d }{\sqrt{\sum_{d=1}^D x_i^2} \cdot \sqrt{\sum_{d=1}^D y_i^2}}
If both :math:`x` and :math:`y` are passed in, the calculation will be performed p... | r"""Calculate pairwise cosine similarity.
.. math::
s_{cos}(x,y) = \frac{<x,y>}{||x|| \cdot ||y||}
= \frac{\sum_{d=1}^D x_d \cdot y_d }{\sqrt{\sum_{d=1}^D x_i^2} \cdot \sqrt{\sum_{d=1}^D y_i^2}}
If both :math:`x` and :math:`y` are passed in, the calculation will be performed p... | 197 | 561 | 718 | 1,279 | # Copyright The Lightning 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 applicable law or agreed to in writin... | # Copyright The Lightning 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 applicable law or agreed to in writin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.