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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36,702 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py | 190,191 | 145,232 | forward | PiecewiseContEmbeddings | 191,222 | 191,222 | class PiecewiseContEmbeddings(nn.Module):
def __init__(
self,
column_idx: Dict[str, int],
quantization_setup: Dict[str, List[float]],
embed_dim: int,
embed_dropout: float,
full_embed_dropout: bool,
activation_fn: Optional[str] = None,
) -> None:
su... | class PiecewiseContEmbeddings(nn.Module):
def __init__(
self,
column_idx: Dict[str, int],
quantization_setup: Dict[str, List[float]],
embed_dim: int,
embed_dropout: float,
full_embed_dropout: bool,
activation_fn: Optional[str] = None,
) -> None:
su... | # b: batch size
# n: n_cont_cols
# k: max_num_buckets
# e: embed_dim
encoded_values = []
for col, index in self.column_idx.items():
feat = X[:, index].contiguous()
col_boundaries = getattr(self, "boundaries_" + col)
bucket_indices = to... | # b: batch size
# n: n_cont_cols
# k: max_num_buckets
# e: embed_dim
encoded_values = []
for col, index in self.column_idx.items():
feat = X[:, index].contiguous()
col_boundaries = getattr(self, "boundaries_" + col)
bucket_indices = to... | 104 | 709 | 408 | 1,117 | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... |
36,703 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py | 468,469 | 395,499 | forward | SameSizeCatEmbeddings | 469,499 | 469,499 | class SameSizeCatEmbeddings(nn.Module):
def __init__(
self,
embed_dim: int,
column_idx: Dict[str, int],
embed_input: List[Tuple[str, int]],
embed_dropout: float,
full_embed_dropout: bool,
use_bias: bool,
shared_embed: bool,
add_shared_embed: bo... | class SameSizeCatEmbeddings(nn.Module):
def __init__(
self,
embed_dim: int,
column_idx: Dict[str, int],
embed_input: List[Tuple[str, int]],
embed_dropout: float,
full_embed_dropout: bool,
use_bias: bool,
shared_embed: bool,
add_shared_embed: bo... | if self.shared_embed:
cat_embed = [
self.embed["emb_layer_" + self.embed_layers_names[col]]( # type: ignore[index]
X[:, self.column_idx[col]].long()
).unsqueeze(
1
)
for col, _ in self.embed_inpu... | if self.shared_embed:
cat_embed = [
self.embed["emb_layer_" + self.embed_layers_names[col]]( # type: ignore[index]
X[:, self.column_idx[col]].long()
).unsqueeze(
1
)
for col, _ in self.embed_inpu... | 89 | 811 | 347 | 1,158 | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... |
36,704 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py | 318,319 | 298,328 | forward | SharedEmbeddings | 319,328 | 319,328 | class SharedEmbeddings(nn.Module):
def __init__(
self,
n_embed: int,
embed_dim: int,
add_shared_embed: bool = False,
frac_shared_embed=0.25,
):
super(SharedEmbeddings, self).__init__()
assert frac_shared_embed < 1, "'frac_shared_embed' must be less than 1... | class SharedEmbeddings(nn.Module):
def __init__(
self,
n_embed: int,
embed_dim: int,
add_shared_embed: bool = False,
frac_shared_embed=0.25,
):
super(SharedEmbeddings, self).__init__()
assert frac_shared_embed < 1, "'frac_shared_embed' must be less than 1... | out = self.embed(X)
shared_embed = self.shared_embed.expand(out.shape[0], -1)
if self.add_shared_embed:
out += shared_embed
else:
out[:, : shared_embed.shape[1]] = shared_embed
return out
| out = self.embed(X)
shared_embed = self.shared_embed.expand(out.shape[0], -1)
if self.add_shared_embed:
out += shared_embed
else:
out[:, : shared_embed.shape[1]] = shared_embed
return out
| 20 | 280 | 88 | 368 | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... | """
SharedEmbeddings is inspired by the TabTransformer available in AutoGluon:
https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer
PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper:
'On Embeddings for Numerical Features in Tabular Deep Learn... |
36,705 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/linear/wide.py | 65,66 | 10,70 | forward | Wide | 66,70 | 66,70 | class Wide(nn.Module):
r"""Defines a `Wide` (linear) model where the non-linearities are
captured via the so-called crossed-columns. This can be used as the
`wide` component of a Wide & Deep model.
Parameters
-----------
input_dim: int
size of the Linear layer (implemented via an Embedd... | class Wide(nn.Module):
r"""Defines a `Wide` (linear) model where the non-linearities are
captured via the so-called crossed-columns. This can be used as the
`wide` component of a Wide & Deep model.
Parameters
-----------
input_dim: int
size of the Linear layer (implemented via an Embedd... | r"""Forward pass. Simply connecting the Embedding layer with the ouput
neuron(s)"""
out = self.wide_linear(X.long()).sum(dim=1) + self.bias
return out
| r"""Forward pass. Simply connecting the Embedding layer with the ouput
neuron(s)"""
out = self.wide_linear(X.long()).sum(dim=1) + self.bias
return out
| 18 | 733 | 59 | 792 | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.utils.general_utils import alias
class Wide(nn.Module):
r"""Defines a `Wide` (linear) model where the non-linearities are
captured via the so-called crossed-columns. This can be used as the
`w... | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.utils.general_utils import alias
class Wide(nn.Module):
r"""Defines a `Wide` (linear) model where the non-linearities are
captured via the so-called crossed-columns. This can be used as the
`w... |
36,706 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_attention_layers.py | 24,25 | 10,33 | forward | ContextAttention | 25,33 | 25,33 | class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf>`_
"""
def __init__(self, input_dim: int, dropout: float, sum_along_seq: bool = False)... | class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf>`_
"""
def __init__(self, input_dim: int, dropout: float, sum_along_seq: bool = False)... | scores = torch.tanh_(self.inp_proj(X))
attn_weights = self.context(scores).softmax(dim=1)
self.attn_weights = attn_weights.squeeze(2)
attn_weights = self.dropout(attn_weights)
output = (attn_weights * X).sum(1) if self.sum_along_seq else (attn_weights * X)
return output
... | scores = torch.tanh_(self.inp_proj(X))
attn_weights = self.context(scores).softmax(dim=1)
self.attn_weights = attn_weights.squeeze(2)
attn_weights = self.dropout(attn_weights)
output = (attn_weights * X).sum(1) if self.sum_along_seq else (attn_weights * X)
return output
... | 25 | 223 | 131 | 354 | import math
import torch
import einops
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tensor
class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-at... | import math
import torch
import einops
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tensor
class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-at... |
36,707 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_attention_layers.py | 62,63 | 33,81 | forward | QueryKeySelfAttention | 63,81 | 63,81 | class QueryKeySelfAttention(nn.Module):
r"""Attention mechanism inspired by the well known multi-head attention. Here,
rather than learning a value projection matrix that will be multiplied by
the attention weights, we multiply such weights directly by the input
tensor.
The rationale behind this im... | class QueryKeySelfAttention(nn.Module):
r"""Attention mechanism inspired by the well known multi-head attention. Here,
rather than learning a value projection matrix that will be multiplied by
the attention weights, we multiply such weights directly by the input
tensor.
The rationale behind this im... | # b: batch size
# s: seq length
# l: target sequence length. Here l = s
# m: used to refer indistinctively to s or l
# h: number of attention heads,
# d: head_dim
q, k = self.qk_proj(X).chunk(2, dim=-1)
q, k, x_rearr = map(
lambda t: einops.rea... | # b: batch size
# s: seq length
# l: target sequence length. Here l = s
# m: used to refer indistinctively to s or l
# h: number of attention heads,
# d: head_dim
q, k = self.qk_proj(X).chunk(2, dim=-1)
q, k, x_rearr = map(
lambda t: einops.rea... | 123 | 336 | 341 | 677 | import math
import torch
import einops
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tensor
class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-at... | import math
import torch
import einops
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tensor
class ContextAttention(nn.Module):
r"""Attention mechanism inspired by `Hierarchical Attention Networks for
Document Classification
<https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-at... |
36,708 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_encoders.py | 37,38 | 14,46 | forward | ContextAttentionEncoder | 38,46 | 38,46 | class ContextAttentionEncoder(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
with_addnorm: bool,
activation: str,
):
super(ContextAttentionEncoder, self).__init__()
self.with_addnorm = with_addnorm
self.attn = ContextAttention(inp... | class ContextAttentionEncoder(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
with_addnorm: bool,
activation: str,
):
super(ContextAttentionEncoder, self).__init__()
self.with_addnorm = with_addnorm
self.attn = ContextAttention(inp... | if self.with_addnorm:
x = self.attn_addnorm(X, self.attn)
out = self.slp_addnorm(x, self.slp)
else:
out = self.slp(self.attn(X))
return out
| if self.with_addnorm:
x = self.attn_addnorm(X, self.attn)
out = self.slp_addnorm(x, self.slp)
else:
out = self.slp(self.attn(X))
return out
| 16 | 217 | 82 | 299 | from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.models.tabular.mlp._layers import SLP
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
QueryKeySelfAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import ... | from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.models.tabular.mlp._layers import SLP
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
QueryKeySelfAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import ... |
36,709 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_encoders.py | 71,72 | 46,78 | forward | SelfAttentionEncoder | 72,78 | 72,78 | class SelfAttentionEncoder(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
use_bias: bool,
n_heads: int,
with_addnorm: bool,
activation: str,
):
super(SelfAttentionEncoder, self).__init__()
self.with_addnorm = with_addnorm
... | class SelfAttentionEncoder(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
use_bias: bool,
n_heads: int,
with_addnorm: bool,
activation: str,
):
super(SelfAttentionEncoder, self).__init__()
self.with_addnorm = with_addnorm
... | if self.with_addnorm:
x = self.attn_addnorm(X, self.attn)
out = self.slp_addnorm(x, self.slp)
else:
out = self.slp(self.attn(X))
return out
| if self.with_addnorm:
x = self.attn_addnorm(X, self.attn)
out = self.slp_addnorm(x, self.slp)
else:
out = self.slp(self.attn(X))
return out
| 16 | 247 | 78 | 325 | from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.models.tabular.mlp._layers import SLP
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
QueryKeySelfAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import ... | from torch import nn
from pytorch_widedeep.wdtypes import Tensor
from pytorch_widedeep.models.tabular.mlp._layers import SLP
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
QueryKeySelfAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import ... |
36,710 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_layers.py | 7,15 | 1,90 | dense_layer | 15,26 | 15,26 | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
FILL_FUNC_BODYclass SLP(nn.Module):... | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
FILL_FUNC_BODYclass SLP(nn.Module):... | # This is basically the LinBnDrop class at the fastai library
act_fn = get_activation_fn(activation)
layers = [nn.BatchNorm1d(out if linear_first else inp)] if bn else []
if p != 0:
layers.append(nn.Dropout(p)) # type: ignore[arg-type]
lin = [nn.Linear(inp, out, bias=not bn), act_fn]
la... | # This is basically the LinBnDrop class at the fastai library
act_fn = get_activation_fn(activation)
layers = [nn.BatchNorm1d(out if linear_first else inp)] if bn else []
if p != 0:
layers.append(nn.Dropout(p)) # type: ignore[arg-type]
lin = [nn.Linear(inp, out, bias=not bn), act_fn]
la... | 68 | 713 | 178 | 891 | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
FILL_FUNC_BODYclass SLP(nn.Module):... | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
FILL_FUNC_BODYclass SLP(nn.Module):... | |
36,711 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_layers.py | 88,89 | 52,90 | forward | MLP | 89,90 | 89,90 | class MLP(nn.Module):
def __init__(
self,
d_hidden: List[int],
activation: str,
dropout: Optional[Union[float, List[float]]],
batchnorm: bool,
batchnorm_last: bool,
linear_first: bool,
):
super(MLP, self).__init__()
if dropout is None:
... | class MLP(nn.Module):
def __init__(
self,
d_hidden: List[int],
activation: str,
dropout: Optional[Union[float, List[float]]],
batchnorm: bool,
batchnorm_last: bool,
linear_first: bool,
):
super(MLP, self).__init__()
if dropout is None:
... | return self.mlp(X)
| return self.mlp(X)
| 2 | 361 | 11 | 372 | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
# This is basically the LinBnDr... | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
# This is basically the LinBnDr... |
36,712 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/_layers.py | 48,49 | 26,52 | forward | SLP | 49,52 | 49,52 | class SLP(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
activation: str,
normalise: bool,
):
super(SLP, self).__init__()
self.lin = nn.Linear(
input_dim,
input_dim * 2 if activation.endswith("glu") else input_dim,... | class SLP(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
activation: str,
normalise: bool,
):
super(SLP, self).__init__()
self.lin = nn.Linear(
input_dim,
input_dim * 2 if activation.endswith("glu") else input_dim,... | return self.dropout(self.norm(self.activation(self.lin(X))))
| return self.dropout(self.norm(self.activation(self.lin(X))))
| 2 | 220 | 29 | 249 | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
# This is basically the LinBnDr... | from torch import nn
from pytorch_widedeep.wdtypes import List, Union, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_activation_fn
def dense_layer(
inp: int,
out: int,
activation: str,
p: float,
bn: bool,
linear_first: bool,
):
# This is basically the LinBnDr... |
36,716 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/mlp/tab_mlp.py | 309,310 | 231,311 | forward | TabMlpDecoder | 310,311 | 310,311 | class TabMlpDecoder(nn.Module):
r"""Companion decoder model for the `TabMlp` model (which can be considered
an encoder itself).
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). The `TabMlpDecoder`... | class TabMlpDecoder(nn.Module):
r"""Companion decoder model for the `TabMlp` model (which can be considered
an encoder itself).
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). The `TabMlpDecoder`... | return self.decoder(X)
| return self.decoder(X)
| 2 | 939 | 11 | 950 | from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Union,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widedeep.models.tabular._base_tabular_model import (
BaseTabularModelWithoutAttention,
)
class Ta... | from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Union,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widedeep.models.tabular._base_tabular_model import (
BaseTabularModelWithoutAttention,
)
class Ta... |
36,717 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/resnet/_layers.py | 36,37 | 8,58 | forward | BasicBlock | 37,58 | 37,58 | class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
dropout: float = 0.0,
simplify: bool = False,
resize: Optional[nn.Module] = None,
):
super... | class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
dropout: float = 0.0,
simplify: bool = False,
resize: Optional[nn.Module] = None,
):
super... | identity = X
out = self.lin1(X)
out = self.bn1(out)
out = self.leaky_relu(out)
if self.dropout:
out = self.dp(out)
if not self.simplify:
out = self.lin2(out)
out = self.bn2(out)
if self.resize is not None:
identit... | identity = X
out = self.lin1(X)
out = self.bn1(out)
out = self.leaky_relu(out)
if self.dropout:
out = self.dp(out)
if not self.simplify:
out = self.lin2(out)
out = self.bn2(out)
if self.resize is not None:
identit... | 42 | 317 | 162 | 479 | from collections import OrderedDict
from torch import nn
from pytorch_widedeep.wdtypes import List, Tensor, Optional
class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
... | from collections import OrderedDict
from torch import nn
from pytorch_widedeep.wdtypes import List, Tensor, Optional
class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
... |
36,718 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/resnet/_layers.py | 89,90 | 58,91 | forward | DenseResnet | 90,91 | 90,91 | class DenseResnet(nn.Module):
def __init__(
self, input_dim: int, blocks_dims: List[int], dropout: float, simplify: bool
):
super(DenseResnet, self).__init__()
if input_dim != blocks_dims[0]:
self.dense_resnet = nn.Sequential(
OrderedDict(
... | class DenseResnet(nn.Module):
def __init__(
self, input_dim: int, blocks_dims: List[int], dropout: float, simplify: bool
):
super(DenseResnet, self).__init__()
if input_dim != blocks_dims[0]:
self.dense_resnet = nn.Sequential(
OrderedDict(
... | return self.dense_resnet(X)
| return self.dense_resnet(X)
| 2 | 384 | 14 | 398 | from collections import OrderedDict
from torch import nn
from pytorch_widedeep.wdtypes import List, Tensor, Optional
class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
... | from collections import OrderedDict
from torch import nn
from pytorch_widedeep.wdtypes import List, Tensor, Optional
class BasicBlock(nn.Module):
# inspired by https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L37
def __init__(
self,
inp: int,
out: int,
... |
36,720 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/resnet/tab_resnet.py | 432,433 | 291,435 | forward | TabResnetDecoder | 433,435 | 433,435 | class TabResnetDecoder(nn.Module):
r"""Companion decoder model for the `TabResnet` model (which can be
considered an encoder itself)
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). This class wil... | class TabResnetDecoder(nn.Module):
r"""Companion decoder model for the `TabResnet` model (which can be
considered an encoder itself)
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). This class wil... | x = self.mlp(X) if self.mlp is not None else X
return self.reconstruction_layer(self.decoder(x))
| x = self.mlp(X) if self.mlp is not None else X
return self.reconstruction_layer(self.decoder(x))
| 12 | 1,887 | 41 | 1,928 | from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widedeep.models.tabular.resnet._layers import DenseResnet
from pytorch_widedeep.models.tabular._base_tabular_model... | from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widedeep.models.tabular.resnet._layers import DenseResnet
from pytorch_widedeep.models.tabular._base_tabular_model... |
36,721 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_augmentations.py | 15,16 | 1,39 | cut_mix | 16,31 | 16,31 | """
The following two functions are based on those in the SAINT repo
(https://github.com/somepago/saint) and code here:
- CutMix: https://github.com/clovaai/CutMix-PyTorch
- MixUp: https://github.com/facebookresearch/mixup-cifar10
"""
import numpy as np
import torch
from pytorch_widedeep.wdtypes import Tensor
def ... | """
The following two functions are based on those in the SAINT repo
(https://github.com/somepago/saint) and code here:
- CutMix: https://github.com/clovaai/CutMix-PyTorch
- MixUp: https://github.com/facebookresearch/mixup-cifar10
"""
import numpy as np
import torch
from pytorch_widedeep.wdtypes import Tensor
def ... | batch_size = x.size()[0]
mask = torch.from_numpy(np.random.choice(2, (x.shape), p=[lam, 1 - lam])).to(
x.device
)
rand_idx = torch.randperm(batch_size).to(x.device)
x_ = x[rand_idx].clone()
x_[mask == 0] = x[mask == 0]
return x_
| batch_size = x.size()[0]
mask = torch.from_numpy(np.random.choice(2, (x.shape), p=[lam, 1 - lam])).to(
x.device
)
rand_idx = torch.randperm(batch_size).to(x.device)
x_ = x[rand_idx].clone()
x_[mask == 0] = x[mask == 0]
return x_
| 28 | 242 | 141 | 383 | """
The following two functions are based on those in the SAINT repo
(https://github.com/somepago/saint) and code here:
- CutMix: https://github.com/clovaai/CutMix-PyTorch
- MixUp: https://github.com/facebookresearch/mixup-cifar10
"""
import numpy as np
import torch
from pytorch_widedeep.wdtypes import Tensor
def ... | """
The following two functions are based on those in the SAINT repo
(https://github.com/somepago/saint) and code here:
- CutMix: https://github.com/clovaai/CutMix-PyTorch
- MixUp: https://github.com/facebookresearch/mixup-cifar10
"""
import numpy as np
import torch
from pytorch_widedeep.wdtypes import Tensor
def ... | |
36,722 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_denoise_mlps.py | 95,96 | 58,111 | forward | CatMlpPerFeature | 96,111 | 96,111 | class CatMlpPerFeature(nn.Module):
r"""Dedicated MLP per categorical feature"""
def __init__(
self,
input_dim: int,
cat_embed_input: List[Tuple[str, int]],
column_idx: Dict[str, int],
activation: str,
):
super(CatMlpPerFeature, self).__init__()
self.... | class CatMlpPerFeature(nn.Module):
r"""Dedicated MLP per categorical feature"""
def __init__(
self,
input_dim: int,
cat_embed_input: List[Tuple[str, int]],
column_idx: Dict[str, int],
activation: str,
):
super(CatMlpPerFeature, self).__init__()
self.... | x = [
X[:, self.column_idx[col]].long()
for col, _ in self.cat_embed_input
if col != "cls_token"
]
x_ = [
self.mlp["mlp_" + col](r_[:, self.column_idx[col], :])
for col, _ in self.cat_embed_input
if col != "cls_token"
... | x = [
X[:, self.column_idx[col]].long()
for col, _ in self.cat_embed_input
if col != "cls_token"
]
x_ = [
self.mlp["mlp_" + col](r_[:, self.column_idx[col], :])
for col, _ in self.cat_embed_input
if col != "cls_token"
... | 36 | 323 | 141 | 464 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... |
36,723 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_denoise_mlps.py | 36,37 | 8,58 | forward | CatSingleMlp | 37,58 | 37,58 | class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
cat_embed_input: List[Tuple[str, int]],
column_idx: Dict[str, int],
activation: str,
):
super(CatSingleMlp, self).__init__()
... | class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
cat_embed_input: List[Tuple[str, int]],
column_idx: Dict[str, int],
activation: str,
):
super(CatSingleMlp, self).__init__()
... | x = torch.cat(
[
X[:, self.column_idx[col]].long()
for col, _ in self.cat_embed_input
if col != "cls_token"
]
)
cat_r_ = torch.cat(
[
r_[:, self.column_idx[col], :]
for col, _ in ... | x = torch.cat(
[
X[:, self.column_idx[col]].long()
for col, _ in self.cat_embed_input
if col != "cls_token"
]
)
cat_r_ = torch.cat(
[
r_[:, self.column_idx[col], :]
for col, _ in ... | 41 | 305 | 168 | 473 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... |
36,724 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_denoise_mlps.py | 187,188 | 151,199 | forward | ContMlpPerFeature | 188,199 | 188,199 | class ContMlpPerFeature(nn.Module):
r"""Dedicated MLP per continuous feature"""
def __init__(
self,
input_dim: int,
continuous_cols: List[str],
column_idx: Dict[str, int],
activation: str,
):
super(ContMlpPerFeature, self).__init__()
self.input_dim =... | class ContMlpPerFeature(nn.Module):
r"""Dedicated MLP per continuous feature"""
def __init__(
self,
input_dim: int,
continuous_cols: List[str],
column_idx: Dict[str, int],
activation: str,
):
super(ContMlpPerFeature, self).__init__()
self.input_dim =... | x = [
X[:, self.column_idx[col]].unsqueeze(1).float()
for col in self.continuous_cols
]
x_ = [
self.mlp["mlp_" + col](r_[:, self.column_idx[col]])
for col in self.continuous_cols
]
return list(zip(x, x_))
| x = [
X[:, self.column_idx[col]].unsqueeze(1).float()
for col in self.continuous_cols
]
x_ = [
self.mlp["mlp_" + col](r_[:, self.column_idx[col]])
for col in self.continuous_cols
]
return list(zip(x, x_))
| 25 | 303 | 115 | 418 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... |
36,725 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_denoise_mlps.py | 137,138 | 111,151 | forward | ContSingleMlp | 138,151 | 138,151 | class ContSingleMlp(nn.Module):
r"""Single MLP will be applied to all continuous features"""
def __init__(
self,
input_dim: int,
continuous_cols: List[str],
column_idx: Dict[str, int],
activation: str,
):
super(ContSingleMlp, self).__init__()
self.in... | class ContSingleMlp(nn.Module):
r"""Single MLP will be applied to all continuous features"""
def __init__(
self,
input_dim: int,
continuous_cols: List[str],
column_idx: Dict[str, int],
activation: str,
):
super(ContSingleMlp, self).__init__()
self.in... | x = torch.cat(
[X[:, self.column_idx[col]].float() for col in self.continuous_cols]
).unsqueeze(1)
cont_r_ = torch.cat(
[r_[:, self.column_idx[col], :] for col in self.continuous_cols]
)
x_ = self.mlp(cont_r_)
return x, x_
| x = torch.cat(
[X[:, self.column_idx[col]].float() for col in self.continuous_cols]
).unsqueeze(1)
cont_r_ = torch.cat(
[r_[:, self.column_idx[col], :] for col in self.continuous_cols]
)
x_ = self.mlp(cont_r_)
return x, x_
| 27 | 253 | 129 | 382 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Dict, List, Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._layers import MLP
class CatSingleMlp(nn.Module):
r"""Single MLP will be applied to all categorical features"""
def __init__(
self,
input_dim: int,
... |
36,726 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/self_supervised/_random_obfuscator.py | 30,31 | 14,34 | forward | RandomObfuscator | 31,34 | 31,34 | class RandomObfuscator(nn.Module):
r"""Creates and applies an obfuscation masks
Note that the class will return a mask tensor with 1s IF the feature value
is considered for reconstruction
Parameters:
----------
p: float
Ratio of features that will be discarded for reconstruction
""... | class RandomObfuscator(nn.Module):
r"""Creates and applies an obfuscation masks
Note that the class will return a mask tensor with 1s IF the feature value
is considered for reconstruction
Parameters:
----------
p: float
Ratio of features that will be discarded for reconstruction
""... | mask = torch.bernoulli(self.p * torch.ones(x.shape)).to(x.device)
masked_input = torch.mul(1 - mask, x)
return masked_input, mask
| mask = torch.bernoulli(self.p * torch.ones(x.shape)).to(x.device)
masked_input = torch.mul(1 - mask, x)
return masked_input, mask
| 14 | 163 | 62 | 225 | """
This class is (almost) directly copied from the dreamquark-ai's repo:
https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT to the dreamquark-ai's team
"""
from typing import Tuple
import torch
from torch import nn
class RandomObfuscator(nn.Module):
r"""Creates and applies an obfuscation masks
... | """
This class is (almost) directly copied from the dreamquark-ai's repo:
https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT to the dreamquark-ai's team
"""
from typing import Tuple
import torch
from torch import nn
class RandomObfuscator(nn.Module):
r"""Creates and applies an obfuscation masks
... |
36,728 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 219,220 | 188,225 | forward | AttentiveTransformer | 220,225 | 220,225 | class AttentiveTransformer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
mask_type: str = "sparsemax",
ghost_bn=True,
virtual_batch_size=128,
momentum=0.02,
):
super(AttentiveTransformer, self).__init__()
self.fc = nn.Lin... | class AttentiveTransformer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
mask_type: str = "sparsemax",
ghost_bn=True,
virtual_batch_size=128,
momentum=0.02,
):
super(AttentiveTransformer, self).__init__()
self.fc = nn.Lin... | x = self.bn(self.fc(processed_feat))
x = torch.mul(x, priors)
return self.mask(x)
| x = self.bn(self.fc(processed_feat))
x = torch.mul(x, priors)
return self.mask(x)
| 9 | 385 | 49 | 434 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,729 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 184,185 | 145,188 | forward | FeatTransformer | 185,188 | 185,188 | class FeatTransformer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
shared_layers: nn.ModuleList,
n_glu_step_dependent: int,
ghost_bn=True,
virtual_batch_size=128,
momentum=0.02,
):
super(FeatTrans... | class FeatTransformer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
shared_layers: nn.ModuleList,
n_glu_step_dependent: int,
ghost_bn=True,
virtual_batch_size=128,
momentum=0.02,
):
super(FeatTrans... | return self.step_dependent(self.shared(X))
| return self.step_dependent(self.shared(X))
| 2 | 314 | 20 | 334 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,730 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 47,48 | 34,53 | forward | GBN | 48,53 | 48,53 | class GBN(torch.nn.Module):
"""
Ghost Batch Normalization
https://arxiv.org/abs/1705.08741
"""
def __init__(
self, input_dim: int, virtual_batch_size: int = 128, momentum: float = 0.01
):
super(GBN, self).__init__()
self.virtual_batch_size = virtual_batch_size
se... | class GBN(torch.nn.Module):
"""
Ghost Batch Normalization
https://arxiv.org/abs/1705.08741
"""
def __init__(
self, input_dim: int, virtual_batch_size: int = 128, momentum: float = 0.01
):
super(GBN, self).__init__()
self.virtual_batch_size = virtual_batch_size
se... | chunks = X.chunk(int(np.ceil(X.shape[0] / self.virtual_batch_size)), 0)
res = [self.bn(x_) for x_ in chunks]
return torch.cat(res, dim=0)
| chunks = X.chunk(int(np.ceil(X.shape[0] / self.virtual_batch_size)), 0)
res = [self.bn(x_) for x_ in chunks]
return torch.cat(res, dim=0)
| 16 | 167 | 73 | 240 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,731 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 129,130 | 85,145 | forward | GLU_Block | 130,145 | 130,145 | class GLU_Block(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
n_glu: int = 2,
first: bool = False,
shared_layers: nn.ModuleList = None,
ghost_bn: bool = True,
virtual_batch_size: int = 128,
momentum: f... | class GLU_Block(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
n_glu: int = 2,
first: bool = False,
shared_layers: nn.ModuleList = None,
ghost_bn: bool = True,
virtual_batch_size: int = 128,
momentum: f... | scale = torch.sqrt(torch.FloatTensor([0.5]).to(X.device))
if self.first: # the first layer of the block has no scale multiplication
x = self.glu_layers[0](X)
layers_left = range(1, self.n_glu)
else:
x = nn.Identity()(X)
layers_left = range(self.n... | scale = torch.sqrt(torch.FloatTensor([0.5]).to(X.device))
if self.first: # the first layer of the block has no scale multiplication
x = self.glu_layers[0](X)
layers_left = range(1, self.n_glu)
else:
x = nn.Identity()(X)
layers_left = range(self.n... | 42 | 484 | 172 | 656 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,732 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 81,82 | 53,85 | forward | GLU_Layer | 82,85 | 82,85 | class GLU_Layer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
fc: nn.Module = None,
ghost_bn: bool = True,
virtual_batch_size: int = 128,
momentum: float = 0.02,
):
super(GLU_Layer, self).__init__()
... | class GLU_Layer(nn.Module):
def __init__(
self,
input_dim: int,
output_dim: int,
dropout: float,
fc: nn.Module = None,
ghost_bn: bool = True,
virtual_batch_size: int = 128,
momentum: float = 0.02,
):
super(GLU_Layer, self).__init__()
... | return self.dp(F.glu(self.bn(self.fc(X))))
| return self.dp(F.glu(self.bn(self.fc(X))))
| 2 | 308 | 28 | 336 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,733 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_layers.py | 298,301 | 225,363 | forward | TabNetEncoder | 301,338 | 301,338 | class TabNetEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_steps: int = 3,
step_dim: int = 8,
attn_dim: int = 8,
dropout: float = 0.0,
n_glu_step_dependent: int = 2,
n_glu_shared: int = 2,
ghost_bn: bool = True,
virtual_batch... | class TabNetEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_steps: int = 3,
step_dim: int = 8,
attn_dim: int = 8,
dropout: float = 0.0,
n_glu_step_dependent: int = 2,
n_glu_shared: int = 2,
ghost_bn: bool = True,
virtual_batch... | x = self.initial_bn(X)
if prior is None:
# P[n_step = 0] is initialized as all ones, 1^(B×D)
prior = torch.ones(x.shape).to(x.device)
# sparsity regularization
M_loss = torch.FloatTensor([0.0]).to(x.device)
# split block
attn = self.initial_spli... | x = self.initial_bn(X)
if prior is None:
# P[n_step = 0] is initialized as all ones, 1^(B×D)
prior = torch.ones(x.shape).to(x.device)
# sparsity regularization
M_loss = torch.FloatTensor([0.0]).to(x.device)
# split block
attn = self.initial_spli... | 123 | 1,068 | 481 | 1,549 | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... | """
Most of the code here is a direct copy and paste from the fantastic tabnet
implementation here: https://github.com/dreamquark-ai/tabnet
Therefore, ALL CREDIT TO THE DREAMQUARK-AI TEAM
-----------------------------------------------
Here I simply adapted what I needed the TabNet to work within pytorch-widedeep
"""... |
36,734 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/_utils.py | 89,90 | 1,114 | extract_cat_setup | 90,97 | 90,97 | import numpy as np
from torch import nn
from scipy.sparse import csc_matrix
from pytorch_widedeep.wdtypes import Dict, List, WideDeep
def create_explain_matrix(model: WideDeep) -> csc_matrix:
"""
Returns a sparse matrix used to compute the feature importances after
training
Parameters
----------... | import numpy as np
from torch import nn
from scipy.sparse import csc_matrix
from pytorch_widedeep.wdtypes import Dict, List, WideDeep
def create_explain_matrix(model: WideDeep) -> csc_matrix:
"""
Returns a sparse matrix used to compute the feature importances after
training
Parameters
----------... | cat_cols: List = backbone.cat_embed_input # type: ignore[assignment]
if cat_cols is not None:
return cat_cols
else:
return []
| cat_cols: List = backbone.cat_embed_input # type: ignore[assignment]
if cat_cols is not None:
return cat_cols
else:
return []
| 17 | 1,248 | 61 | 1,309 | import numpy as np
from torch import nn
from scipy.sparse import csc_matrix
from pytorch_widedeep.wdtypes import Dict, List, WideDeep
def create_explain_matrix(model: WideDeep) -> csc_matrix:
"""
Returns a sparse matrix used to compute the feature importances after
training
Parameters
----------... | import numpy as np
from torch import nn
from scipy.sparse import csc_matrix
from pytorch_widedeep.wdtypes import Dict, List, WideDeep
def create_explain_matrix(model: WideDeep) -> csc_matrix:
"""
Returns a sparse matrix used to compute the feature importances after
training
Parameters
----------... | |
36,735 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/sparsemax.py | 28,29 | 1,184 | _make_ix_like | 29,36 | 29,36 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | d = input.size(dim)
rho = torch.arange(1, d + 1, device=input.device, dtype=input.dtype)
view = [1] * input.dim()
view[0] = -1
return rho.view(view).transpose(0, dim)
| d = input.size(dim)
rho = torch.arange(1, d + 1, device=input.device, dtype=input.dtype)
view = [1] * input.dim()
view[0] = -1
return rho.view(view).transpose(0, dim)
| 22 | 1,822 | 88 | 1,910 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | |
36,736 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/sparsemax.py | 182,183 | 177,184 | forward | Entmax15 | 183,184 | 183,184 | class Entmax15(nn.Module):
def __init__(self, dim=-1):
self.dim = dim
super(Entmax15, self).__init__()
def forward(self, input):
FILL_FUNC_BODY | class Entmax15(nn.Module):
def __init__(self, dim=-1):
self.dim = dim
super(Entmax15, self).__init__()
def forward(self, input):
FILL_FUNC_BODY | return entmax15(input, self.dim)
| return entmax15(input, self.dim)
| 3 | 66 | 15 | 81 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... |
36,737 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/sparsemax.py | 130,132 | 123,174 | forward | Entmax15Function | 132,143 | 132,143 | class Entmax15Function(Function):
"""
An implementation of exact Entmax with alpha=1.5 (B. Peters, V. Niculae, A. Martins). See
:cite:`https://arxiv.org/abs/1905.05702 for detailed description.
Source: https://github.com/deep-spin/entmax
"""
@staticmethod
def forward(ctx, input, dim=-1):
FI... | class Entmax15Function(Function):
"""
An implementation of exact Entmax with alpha=1.5 (B. Peters, V. Niculae, A. Martins). See
:cite:`https://arxiv.org/abs/1905.05702 for detailed description.
Source: https://github.com/deep-spin/entmax
"""
@staticmethod
def forward(ctx, input, dim=-1):
FI... | ctx.dim = dim
max_val, _ = input.max(dim=dim, keepdim=True)
input = input - max_val # same numerical stability trick as for softmax
input = input / 2 # divide by 2 to solve actual Entmax
tau_star, _ = Entmax15Function._threshold_and_support(input, dim)
output = torch.... | ctx.dim = dim
max_val, _ = input.max(dim=dim, keepdim=True)
input = input - max_val # same numerical stability trick as for softmax
input = input / 2 # divide by 2 to solve actual Entmax
tau_star, _ = Entmax15Function._threshold_and_support(input, dim)
output = torch.... | 50 | 515 | 147 | 662 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... |
36,738 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/sparsemax.py | 119,120 | 114,123 | forward | Sparsemax | 120,123 | 120,123 | class Sparsemax(nn.Module):
def __init__(self, dim=-1):
self.dim = dim
super(Sparsemax, self).__init__()
def forward(self, input):
FILL_FUNC_BODY | class Sparsemax(nn.Module):
def __init__(self, dim=-1):
self.dim = dim
super(Sparsemax, self).__init__()
def forward(self, input):
FILL_FUNC_BODY | return sparsemax(input, self.dim)
| return sparsemax(input, self.dim)
| 3 | 64 | 17 | 81 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... |
36,739 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/sparsemax.py | 43,45 | 36,111 | forward | SparsemaxFunction | 61,69 | 45,69 | class SparsemaxFunction(Function):
"""
An implementation of sparsemax (Martins & Astudillo, 2016). See
:cite:`DBLP:journals/corr/MartinsA16` for detailed description.
By Ben Peters and Vlad Niculae
"""
@staticmethod
def forward(ctx, input, dim=-1):
FILL_FUNC_BODY @staticmethod
def ba... | class SparsemaxFunction(Function):
"""
An implementation of sparsemax (Martins & Astudillo, 2016). See
:cite:`DBLP:journals/corr/MartinsA16` for detailed description.
By Ben Peters and Vlad Niculae
"""
@staticmethod
def forward(ctx, input, dim=-1):
"""sparsemax: normalizing sparse t... | ctx.dim = dim
max_val, _ = input.max(dim=dim, keepdim=True)
input -= max_val # same numerical stability trick as for softmax
tau, supp_size = SparsemaxFunction._threshold_and_support(input, dim=dim)
output = torch.clamp(input - tau, min=0)
ctx.save_for_backward(supp_size... | """sparsemax: normalizing sparse transform (a la softmax)
Parameters
----------
ctx : torch.autograd.function._ContextMethodMixin
input : torch.Tensor
any shape
dim : int
dimension along which to apply sparsemax
Returns
-------
... | 34 | 615 | 124 | 739 | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... | """
The code in this module is taken directly from the fantastic tabnet implementation
here: https://github.com/dreamquark-ai/tabnet
which is in itself taken directly from the also fantastic NODE implementation
here: https://github.com/Qwicen/node
In particular: https://github.com/Qwicen/node/blob/master/lib/nn_utils... |
36,741 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/tab_net.py | 389,390 | 287,396 | forward | TabNetDecoder | 390,396 | 390,396 | class TabNetDecoder(nn.Module):
r"""Companion decoder model for the `TabNet` model (which can be
considered an encoder itself)
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). This class will rece... | class TabNetDecoder(nn.Module):
r"""Companion decoder model for the `TabNet` model (which can be
considered an encoder itself)
This class is designed to be used with the `EncoderDecoderTrainer` when
using self-supervised pre-training (see the corresponding section in the
docs). This class will rece... | out = torch.tensor(0.0)
for i, x in enumerate(X):
x = self.decoder[i](x)
out = torch.add(out, x)
out = self.reconstruction_layer(out)
return out
| out = torch.tensor(0.0)
for i, x in enumerate(X):
x = self.decoder[i](x)
out = torch.add(out, x)
out = self.reconstruction_layer(out)
return out
| 20 | 1,200 | 75 | 1,275 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.tabnet._layers import (
TabNetEncoder,
FeatTransformer,
initialize_non_glu,
)
from pytorch_widedeep.models.tabular._base_tabu... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.tabnet._layers import (
TabNetEncoder,
FeatTransformer,
initialize_non_glu,
)
from pytorch_widedeep.models.tabular._base_tabu... |
36,742 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/tabnet/tab_net.py | 282,283 | 266,287 | forward | TabNetPredLayer | 283,287 | 283,287 | class TabNetPredLayer(nn.Module):
def __init__(self, inp, out):
r"""This class is a 'hack' required because TabNet is a very particular
model within `WideDeep`.
TabNet's forward method within `WideDeep` outputs two tensors, one
with the last layer's activations and the sparse regula... | class TabNetPredLayer(nn.Module):
def __init__(self, inp, out):
r"""This class is a 'hack' required because TabNet is a very particular
model within `WideDeep`.
TabNet's forward method within `WideDeep` outputs two tensors, one
with the last layer's activations and the sparse regula... | res, M_loss = tabnet_tuple[0], tabnet_tuple[1]
return self.pred_layer(res), M_loss
| res, M_loss = tabnet_tuple[0], tabnet_tuple[1]
return self.pred_layer(res), M_loss
| 8 | 268 | 44 | 312 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.tabnet._layers import (
TabNetEncoder,
FeatTransformer,
initialize_non_glu,
)
from pytorch_widedeep.models.tabular._base_tabu... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Tensor,
Literal,
Optional,
)
from pytorch_widedeep.models.tabular.tabnet._layers import (
TabNetEncoder,
FeatTransformer,
initialize_non_glu,
)
from pytorch_widedeep.models.tabular._base_tabu... |
36,743 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 63,64 | 55,67 | forward | AddNorm | 64,67 | 64,67 | class AddNorm(nn.Module):
"""aka PosNorm"""
def __init__(self, input_dim: int, dropout: float):
super(AddNorm, self).__init__()
self.dropout = nn.Dropout(dropout)
self.ln = nn.LayerNorm(input_dim)
def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor:
FILL_FUNC_BODY | class AddNorm(nn.Module):
"""aka PosNorm"""
def __init__(self, input_dim: int, dropout: float):
super(AddNorm, self).__init__()
self.dropout = nn.Dropout(dropout)
self.ln = nn.LayerNorm(input_dim)
def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor:
FILL_FUNC_BODY | return self.ln(X + self.dropout(sublayer(X)))
| return self.ln(X + self.dropout(sublayer(X)))
| 4 | 117 | 24 | 141 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,744 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 294,295 | 257,327 | forward | AdditiveAttention | 295,327 | 295,327 | class AdditiveAttention(nn.Module):
"""Additive Attention Implementation from [FastFormer]
(https://arxiv.org/abs/2108.09084)
"""
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
dropout: float,
share_qv_weights: bool,
):
supe... | class AdditiveAttention(nn.Module):
"""Additive Attention Implementation from [FastFormer]
(https://arxiv.org/abs/2108.09084)
"""
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
dropout: float,
share_qv_weights: bool,
):
supe... | # b: batch size
# s: seq length
# h: number of attention heads,
# d: head_dim
q = self.qv_proj(X) if self.share_qv_weights else self.q_proj(X)
v = self.qv_proj(X) if self.share_qv_weights else self.v_proj(X)
k = self.k_proj(X)
alphas = (self.W_q(q) / math... | # b: batch size
# s: seq length
# h: number of attention heads,
# d: head_dim
q = self.qv_proj(X) if self.share_qv_weights else self.q_proj(X)
v = self.qv_proj(X) if self.share_qv_weights else self.v_proj(X)
k = self.k_proj(X)
alphas = (self.W_q(q) / math... | 173 | 478 | 542 | 1,020 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,745 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 39,40 | 17,43 | forward | FeedForward | 40,43 | 40,43 | class FeedForward(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
mult: float,
activation: str,
*,
ff_hidden_dim: Optional[int] = None,
):
super(FeedForward, self).__init__()
ff_hid_dim = (
ff_hidden_dim if ff_hi... | class FeedForward(nn.Module):
def __init__(
self,
input_dim: int,
dropout: float,
mult: float,
activation: str,
*,
ff_hidden_dim: Optional[int] = None,
):
super(FeedForward, self).__init__()
ff_hid_dim = (
ff_hidden_dim if ff_hi... | return self.w_2(self.dropout(self.activation(self.w_1(X))))
| return self.w_2(self.dropout(self.activation(self.w_1(X))))
| 2 | 254 | 33 | 287 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,746 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 229,230 | 190,257 | forward | LinearAttentionLinformer | 230,257 | 230,257 | class LinearAttentionLinformer(nn.Module):
"""Linear Attention implementation from [Linformer: Self-Attention with
Linear Complexity](https://arxiv.org/abs/2006.04768)
"""
def __init__(
self,
input_dim: int,
n_feats: int,
n_heads: int,
use_bias: bool,
dro... | class LinearAttentionLinformer(nn.Module):
"""Linear Attention implementation from [Linformer: Self-Attention with
Linear Complexity](https://arxiv.org/abs/2006.04768)
"""
def __init__(
self,
input_dim: int,
n_feats: int,
n_heads: int,
use_bias: bool,
dro... | # b: batch size
# s: seq length
# h: number of attention heads,
# i: input dim
# k: k dim
# d: head dim
q, k, v = self.qkv_proj(X).chunk(3, dim=-1)
q = einops.rearrange(q, "b s (h d) -> b h s d", h=self.n_heads)
k = einsum("b s i, s k -> b k i", k... | # b: batch size
# s: seq length
# h: number of attention heads,
# i: input dim
# k: k dim
# d: head dim
q, k, v = self.qkv_proj(X).chunk(3, dim=-1)
q = einops.rearrange(q, "b s (h d) -> b h s d", h=self.n_heads)
k = einsum("b s i, s k -> b k i", k... | 161 | 505 | 434 | 939 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,747 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 161,163 | 67,190 | _linear_attention | MultiHeadedAttention | 167,190 | 163,190 | class MultiHeadedAttention(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
dropout: float,
query_dim: Optional[int] = None,
use_linear_attention: bool = False,
use_flash_attention: bool = False,
):
super(MultiH... | class MultiHeadedAttention(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
dropout: float,
query_dim: Optional[int] = None,
use_linear_attention: bool = False,
use_flash_attention: bool = False,
):
super(MultiH... | # b: batch size
# s: seq length
# l: target sequence length
# m: used to refer indistinctively to s or l
# h: number of attention heads,
# d and e: head_dim
q, k = (
nn.functional.elu(q) + 1,
nn.functional.elu(k) + 1,
)
# T... | """Liner attention implemenation from [Transformers are RNNs: Fast
Autoregressive Transformers with Linear Attention]
(https://arxiv.org/abs/2006.16236)
"""
# b: batch size
# s: seq length
# l: target sequence length
# m: used to refer indistinctively to s... | 127 | 1,239 | 284 | 1,523 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,748 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_attention_layers.py | 51,52 | 43,55 | forward | NormAdd | 52,55 | 52,55 | class NormAdd(nn.Module):
"""aka PreNorm"""
def __init__(self, input_dim: int, dropout: float):
super(NormAdd, self).__init__()
self.dropout = nn.Dropout(dropout)
self.ln = nn.LayerNorm(input_dim)
def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor:
FILL_FUNC_BODY | class NormAdd(nn.Module):
"""aka PreNorm"""
def __init__(self, input_dim: int, dropout: float):
super(NormAdd, self).__init__()
self.dropout = nn.Dropout(dropout)
self.ln = nn.LayerNorm(input_dim)
def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor:
FILL_FUNC_BODY | return X + self.dropout(sublayer(self.ln(X)))
| return X + self.dropout(sublayer(self.ln(X)))
| 4 | 117 | 24 | 141 | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... | """
MultiHeadedAttention is inspired by the implementation at
https://github.com/lucidrains
"""
import math
import torch
import einops
import torch.nn.functional as F
from torch import nn, einsum
from pytorch_widedeep.wdtypes import Tuple, Tensor, Optional
from pytorch_widedeep.models._get_activation_fn import get_a... |
36,749 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_encoders.py | 133,134 | 100,141 | forward | FTTransformerEncoder | 134,141 | 134,141 | class FTTransformerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_feats: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: float,
kv_compression_factor: float,
kv_sharing: bool,
act... | class FTTransformerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_feats: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: float,
kv_compression_factor: float,
kv_sharing: bool,
act... | if self.first_block:
x = X + self.attn(X)
else:
x = self.attn_normadd(X, self.attn)
return self.ff_normadd(x, self.ff)
| if self.first_block:
x = X + self.attn(X)
else:
x = self.attn_normadd(X, self.attn)
return self.ff_normadd(x, self.ff)
| 15 | 322 | 70 | 392 | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... |
36,750 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_encoders.py | 205,206 | 179,208 | forward | FastFormerEncoder | 206,208 | 206,208 | class FastFormerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
share_qv_weights: bool,
activation: str,
):
super(FastFormerEncoder, self)... | class FastFormerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
share_qv_weights: bool,
activation: str,
):
super(FastFormerEncoder, self)... | x = self.attn_addnorm(X, self.attn)
return self.ff_addnorm(x, self.ff)
| x = self.attn_addnorm(X, self.attn)
return self.ff_addnorm(x, self.ff)
| 7 | 265 | 37 | 302 | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... |
36,751 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_encoders.py | 172,173 | 141,179 | forward | PerceiverEncoder | 173,179 | 173,179 | class PerceiverEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
query_dim: Optional[int] = None,
):
super(PerceiverEncoder... | class PerceiverEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
query_dim: Optional[int] = None,
):
super(PerceiverEncoder... | x = self.ln_q(X_Q)
y = None if X_KV is None else self.ln_kv(X_KV)
x = x + self.norm_attn_dropout(self.attn(x, y))
return x + self.norm_ff_dropout(self.ff(self.ff_norm(x)))
| x = self.ln_q(X_Q)
y = None if X_KV is None else self.ln_kv(X_KV)
x = x + self.norm_attn_dropout(self.attn(x, y))
return x + self.norm_ff_dropout(self.ff(self.ff_norm(x)))
| 22 | 366 | 98 | 464 | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... |
36,752 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_encoders.py | 90,91 | 49,100 | forward | SaintEncoder | 91,100 | 91,100 | class SaintEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
n_feat: int,
):
super(SaintEncoder, self).__init__()
... | class SaintEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
n_feat: int,
):
super(SaintEncoder, self).__init__()
... | x = self.col_attn_addnorm(X, self.col_attn)
x = self.col_attn_ff_addnorm(x, self.col_attn_ff)
x = einops.rearrange(x, "b n d -> 1 b (n d)")
x = self.row_attn_addnorm(x, self.row_attn)
x = self.row_attn_ff_addnorm(x, self.row_attn_ff)
x = einops.rearrange(x, "1 b (n d) -> ... | x = self.col_attn_addnorm(X, self.col_attn)
x = self.col_attn_ff_addnorm(x, self.col_attn_ff)
x = einops.rearrange(x, "b n d -> 1 b (n d)")
x = self.row_attn_addnorm(x, self.row_attn)
x = self.row_attn_ff_addnorm(x, self.row_attn_ff)
x = einops.rearrange(x, "1 b (n d) -> ... | 41 | 436 | 178 | 614 | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... |
36,753 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/transformers/_encoders.py | 44,45 | 15,49 | forward | TransformerEncoder | 45,49 | 45,49 | class TransformerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
use_linear_attention: bool,
use_flash_attention: bool,
)... | class TransformerEncoder(nn.Module):
def __init__(
self,
input_dim: int,
n_heads: int,
use_bias: bool,
attn_dropout: float,
ff_dropout: float,
ff_factor: int,
activation: str,
use_linear_attention: bool,
use_flash_attention: bool,
)... | x = self.attn_addnorm(X, self.attn)
return self.ff_addnorm(x, self.ff)
| x = self.attn_addnorm(X, self.attn)
return self.ff_addnorm(x, self.ff)
| 7 | 287 | 41 | 328 | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... | import einops
from torch import nn
from pytorch_widedeep.wdtypes import Tensor, Optional
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
NormAdd,
FeedForward,
AdditiveAttention,
MultiHeadedAttention,
LinearAttentionLinformer,
)
class TransformerEncoder(nn... |
36,759 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/text/huggingface_transformers/hf_model.py | 172,174 | 17,188 | attention_weight | HFModel | 174,188 | 174,188 | class HFModel(BaseWDModelComponent):
"""This class is a wrapper around the Hugging Face transformers library. It
can be used as the text component of a Wide & Deep model or independently
by itself.
At the moment only models from the families BERT, RoBERTa, DistilBERT,
ALBERT and ELECTRA are support... | class HFModel(BaseWDModelComponent):
"""This class is a wrapper around the Hugging Face transformers library. It
can be used as the text component of a Wide & Deep model or independently
by itself.
At the moment only models from the families BERT, RoBERTa, DistilBERT,
ALBERT and ELECTRA are support... | r"""Returns the attention weights if the model was created with the
output_attention_weights=True argument. If not, it will raise an
AttributeError.
The shape of the attention weights is $(N, H, F, F)$, where $N$ is the
batch size, $H$ is the number of attention heads and $F$ is... | r"""Returns the attention weights if the model was created with the
output_attention_weights=True argument. If not, it will raise an
AttributeError.
The shape of the attention weights is $(N, H, F, F)$, where $N$ is the
batch size, $H$ is the number of attention heads and $F$ is... | 83 | 1,797 | 188 | 1,985 | import warnings
import torch
from pytorch_widedeep.wdtypes import List, Tensor, Optional
from pytorch_widedeep.utils.hf_utils import (
get_model_class,
get_config_and_model,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widede... | import warnings
import torch
from pytorch_widedeep.wdtypes import List, Tensor, Optional
from pytorch_widedeep.utils.hf_utils import (
get_model_class,
get_config_and_model,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widede... |
36,760 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/text/miscellaneous/basic_transformer.py | 210,211 | 176,212 | forward | PositionalEncoding | 211,212 | 211,212 | class PositionalEncoding(nn.Module):
"""Positional Encoding copied and pasted directly from [The Beginners'
Tutorial]
(https://pytorch.org/tutorials/beginner/transformer_tutorial.html) at the
Pytorch site. Here is simply adapated so that the input sequence length
must be specified and in our impleme... | class PositionalEncoding(nn.Module):
"""Positional Encoding copied and pasted directly from [The Beginners'
Tutorial]
(https://pytorch.org/tutorials/beginner/transformer_tutorial.html) at the
Pytorch site. Here is simply adapated so that the input sequence length
must be specified and in our impleme... | return self.dropout(X + self.pe)
| return self.dropout(X + self.pe)
| 4 | 434 | 15 | 449 | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Union, Tensor, Optional
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.transformers._encoders import (
TransformerEncoder,
)
class Transformer(nn.Module):
r"""Basic Encoder-Only Tr... | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Union, Tensor, Optional
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.transformers._encoders import (
TransformerEncoder,
)
class Transformer(nn.Module):
r"""Basic Encoder-Only Tr... |
36,761 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/text/miscellaneous/basic_transformer.py | 157,158 | 13,176 | forward | Transformer | 158,167 | 158,167 | class Transformer(nn.Module):
r"""Basic Encoder-Only Transformer Model for text classification/regression.
As all other models in the library this model can be used as the
`deeptext` component of a Wide & Deep model or independently by itself.
:information_source: **NOTE**:
This model is introduced... | class Transformer(nn.Module):
r"""Basic Encoder-Only Transformer Model for text classification/regression.
As all other models in the library this model can be used as the
`deeptext` component of a Wide & Deep model or independently by itself.
:information_source: **NOTE**:
This model is introduced... | x = self.embedding(X.long())
x = self.pos_encoder(x)
x = self.encoder(x)
if self.with_cls_token:
x = x[:, 0, :]
else:
x = x.flatten(1)
return x
| x = self.embedding(X.long())
x = self.pos_encoder(x)
x = self.encoder(x)
if self.with_cls_token:
x = x[:, 0, :]
else:
x = x.flatten(1)
return x
| 22 | 1,680 | 89 | 1,769 | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Union, Tensor, Optional
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.transformers._encoders import (
TransformerEncoder,
)
class Transformer(nn.Module):
r"""Basic Encoder-Only Tr... | import math
import torch
from torch import nn
from pytorch_widedeep.wdtypes import Union, Tensor, Optional
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.models.tabular.transformers._encoders import (
TransformerEncoder,
)
class Transformer(nn.Module):
r"""Basic Encoder-Only Tr... |
36,762 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/text/rnns/_encoders.py | 35,36 | 13,69 | forward | ContextAttentionEncoder | 36,54 | 36,54 | class ContextAttentionEncoder(nn.Module):
def __init__(
self,
rnn: nn.Module,
input_dim: int,
attn_dropout: float,
attn_concatenate: bool,
with_addnorm: bool,
sum_along_seq: bool,
):
super(ContextAttentionEncoder, self).__init__()
self.rnn... | class ContextAttentionEncoder(nn.Module):
def __init__(
self,
rnn: nn.Module,
input_dim: int,
attn_dropout: float,
attn_concatenate: bool,
with_addnorm: bool,
sum_along_seq: bool,
):
super(ContextAttentionEncoder, self).__init__()
self.rnn... | if isinstance(self.rnn, nn.LSTM):
o, (h, c) = self.rnn(X, (h, c))
elif isinstance(self.rnn, nn.GRU):
o, h = self.rnn(X, h)
else:
raise ValueError(
"rnn should be either nn.LSTM or nn.GRU. Got {}".format(type(self.rnn))
)
at... | if isinstance(self.rnn, nn.LSTM):
o, (h, c) = self.rnn(X, (h, c))
elif isinstance(self.rnn, nn.GRU):
o, h = self.rnn(X, h)
else:
raise ValueError(
"rnn should be either nn.LSTM or nn.GRU. Got {}".format(type(self.rnn))
)
at... | 49 | 447 | 220 | 667 | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
)
class ContextAttentionEncoder(nn.Module):
de... | import torch
from torch import nn
from pytorch_widedeep.wdtypes import Tuple, Tensor
from pytorch_widedeep.models.tabular.mlp._attention_layers import (
ContextAttention,
)
from pytorch_widedeep.models.tabular.transformers._attention_layers import (
AddNorm,
)
class ContextAttentionEncoder(nn.Module):
de... |
36,766 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/preprocessing/base_preprocessor.py | 26,32 | 1,60 | check_is_fitted | 32,60 | 32,60 | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... | r"""Checks if an estimator is fitted
Parameters
----------
estimator: ``BasePreprocessor``,
An object of type ``BasePreprocessor``
attributes: List, default = None
List of strings with the attributes to check for
all_or_any: str, default = "all"
whether all or any of the... | r"""Checks if an estimator is fitted
Parameters
----------
estimator: ``BasePreprocessor``,
An object of type ``BasePreprocessor``
attributes: List, default = None
List of strings with the attributes to check for
all_or_any: str, default = "all"
whether all or any of the... | 141 | 277 | 334 | 611 | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... | |
36,767 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/preprocessing/base_preprocessor.py | 16,17 | 10,26 | fit | BasePreprocessor | 17,19 | 17,19 | class BasePreprocessor:
"""Base Class of All Preprocessors."""
def __init__(self, *args):
pass
def fit(self, df: pd.DataFrame):
FILL_FUNC_BODY def transform(self, df: pd.DataFrame):
raise NotImplementedError("Preprocessor must implement this method")
def fit_transform(self, df: pd.... | class BasePreprocessor:
"""Base Class of All Preprocessors."""
def __init__(self, *args):
pass
def fit(self, df: pd.DataFrame):
FILL_FUNC_BODY def transform(self, df: pd.DataFrame):
raise NotImplementedError("Preprocessor must implement this method")
def fit_transform(self, df: pd.... | raise NotImplementedError("Preprocessor must implement this method")
| raise NotImplementedError("Preprocessor must implement this method")
| 6 | 125 | 19 | 144 | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... | from typing import Any, List, Union, Optional
import pandas as pd
from sklearn.exceptions import NotFittedError
# This class does not represent any sctructural advantage, but I keep it to
# keep things tidy, as guidance for contribution and because is useful for the
# check_is_fitted function
class BasePreprocessor:... |
36,772 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/preprocessing/tab_preprocessor.py | 96,97 | 46,117 | transform | Quantizer | 97,110 | 97,110 | class Quantizer:
"""Helper class to perform the quantization of continuous columns. It is
included in this docs for completion, since depending on the value of the
parameter `'quantization_setup'` of the `TabPreprocessor` class, that
class might have an attribute of type `Quantizer`. However, this class... | class Quantizer:
"""Helper class to perform the quantization of continuous columns. It is
included in this docs for completion, since depending on the value of the
parameter `'quantization_setup'` of the `TabPreprocessor` class, that
class might have an attribute of type `Quantizer`. However, this class... | check_is_fitted(self, condition=self.is_fitted)
dfc = df.copy()
for col, bins in self.bins.items():
dfc[col] = pd.cut(dfc[col], bins, labels=False, **self.quant_args)
# 0 will be left for numbers outside the bins, i.e. smaller than
# the smaller boundary or l... | check_is_fitted(self, condition=self.is_fitted)
dfc = df.copy()
for col, bins in self.bins.items():
dfc[col] = pd.cut(dfc[col], bins, labels=False, **self.quant_args)
# 0 will be left for numbers outside the bins, i.e. smaller than
# the smaller boundary or l... | 52 | 610 | 178 | 788 | import warnings
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Union,
Literal,
Optional,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.utils.deeptabular_utils imp... | import warnings
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from pytorch_widedeep.wdtypes import (
Dict,
List,
Tuple,
Union,
Literal,
Optional,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.utils.deeptabular_utils imp... |
36,774 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/preprocessing/text_preprocessor.py | 345,346 | 261,397 | partial_fit | ChunkTextPreprocessor | 346,375 | 346,375 | class ChunkTextPreprocessor(TextPreprocessor):
r"""Preprocessor to prepare the ``deeptext`` input dataset
Parameters
----------
text_col: str
column in the input dataframe containing either the texts or the
filenames where the text documents are stored
n_chunks: int
Number o... | class ChunkTextPreprocessor(TextPreprocessor):
r"""Preprocessor to prepare the ``deeptext`` input dataset
Parameters
----------
text_col: str
column in the input dataframe containing either the texts or the
filenames where the text documents are stored
n_chunks: int
Number o... | # df is a chunk of the original dataframe
self.chunk_counter += 1
texts = self._read_texts(df, self.root_dir)
tokens = get_texts(texts, self.already_processed, self.n_cpus)
if not hasattr(self, "vocab"):
self.vocab = ChunkVocab(
max_vocab=self.max_v... | # df is a chunk of the original dataframe
self.chunk_counter += 1
texts = self._read_texts(df, self.root_dir)
tokens = get_texts(texts, self.already_processed, self.n_cpus)
if not hasattr(self, "vocab"):
self.vocab = ChunkVocab(
max_vocab=self.max_v... | 62 | 1,360 | 325 | 1,685 | import os
from typing import List, Union, Optional
import numpy as np
import pandas as pd
from pytorch_widedeep.utils.text_utils import (
get_texts,
pad_sequences,
build_embeddings_matrix,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.utils.fastai_transforms import Vocab, ... | import os
from typing import List, Union, Optional
import numpy as np
import pandas as pd
from pytorch_widedeep.utils.text_utils import (
get_texts,
pad_sequences,
build_embeddings_matrix,
)
from pytorch_widedeep.utils.general_utils import alias
from pytorch_widedeep.utils.fastai_transforms import Vocab, ... |
36,776 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/preprocessing/wide_preprocessor.py | 305,306 | 210,319 | fit | ChunkWidePreprocessor | 310,312 | 306,312 | class ChunkWidePreprocessor(WidePreprocessor):
r"""Preprocessor to prepare the wide input dataset
This Preprocessor prepares the data for the wide, linear component.
This linear model is implemented via an Embedding layer that is
connected to the output neuron. `ChunkWidePreprocessor` numerically
e... | class ChunkWidePreprocessor(WidePreprocessor):
r"""Preprocessor to prepare the wide input dataset
This Preprocessor prepares the data for the wide, linear component.
This linear model is implemented via an Embedding layer that is
connected to the output neuron. `ChunkWidePreprocessor` numerically
e... | return self.partial_fit(df)
| """
Runs `partial_fit`. This is just to override the fit method in the base
class. This class is not designed or thought to run fit
"""
return self.partial_fit(df)
| 2 | 1,238 | 14 | 1,252 | import sys
from typing import List, Tuple, Optional
import numpy as np
import pandas as pd
from pytorch_widedeep.preprocessing.base_preprocessor import (
BasePreprocessor,
check_is_fitted,
)
class WidePreprocessor(BasePreprocessor):
r"""Preprocessor to prepare the wide input dataset
This Preprocess... | import sys
from typing import List, Tuple, Optional
import numpy as np
import pandas as pd
from pytorch_widedeep.preprocessing.base_preprocessor import (
BasePreprocessor,
check_is_fitted,
)
class WidePreprocessor(BasePreprocessor):
r"""Preprocessor to prepare the wide input dataset
This Preprocess... |
36,783 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/training/_multiple_lr_scheduler.py | 8,9 | 4,11 | step | MultipleLRScheduler | 9,11 | 9,11 | class MultipleLRScheduler(object):
def __init__(self, scheds: Dict[str, LRScheduler]):
self._schedulers = scheds
def step(self):
FILL_FUNC_BODY | class MultipleLRScheduler(object):
def __init__(self, scheds: Dict[str, LRScheduler]):
self._schedulers = scheds
def step(self):
FILL_FUNC_BODY | for _, sc in self._schedulers.items():
sc.step()
| for _, sc in self._schedulers.items():
sc.step()
| 6 | 61 | 22 | 83 | from pytorch_widedeep.wdtypes import Dict, LRScheduler
class MultipleLRScheduler(object):
def __init__(self, scheds: Dict[str, LRScheduler]):
self._schedulers = scheds
def step(self):
FILL_FUNC_BODY | from pytorch_widedeep.wdtypes import Dict, LRScheduler
class MultipleLRScheduler(object):
def __init__(self, scheds: Dict[str, LRScheduler]):
self._schedulers = scheds
def step(self):
FILL_FUNC_BODY |
36,784 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/training/_multiple_optimizer.py | 8,9 | 4,15 | zero_grad | MultipleOptimizer | 9,12 | 9,12 | class MultipleOptimizer(object):
def __init__(self, opts: Dict[str, Optimizer]):
self._optimizers = opts
def zero_grad(self):
FILL_FUNC_BODY def step(self):
for _, op in self._optimizers.items():
op.step()
| class MultipleOptimizer(object):
def __init__(self, opts: Dict[str, Optimizer]):
self._optimizers = opts
def zero_grad(self):
FILL_FUNC_BODY def step(self):
for _, op in self._optimizers.items():
op.step()
| for _, op in self._optimizers.items():
op.zero_grad()
| for _, op in self._optimizers.items():
op.zero_grad()
| 6 | 83 | 25 | 108 | from pytorch_widedeep.wdtypes import Dict, Optimizer
class MultipleOptimizer(object):
def __init__(self, opts: Dict[str, Optimizer]):
self._optimizers = opts
def zero_grad(self):
FILL_FUNC_BODY def step(self):
for _, op in self._optimizers.items():
op.step()
| from pytorch_widedeep.wdtypes import Dict, Optimizer
class MultipleOptimizer(object):
def __init__(self, opts: Dict[str, Optimizer]):
self._optimizers = opts
def zero_grad(self):
FILL_FUNC_BODY def step(self):
for _, op in self._optimizers.items():
op.step()
|
36,789 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/utils/general_utils.py | 4,5 | 1,17 | alias | 5,17 | 5,17 | from functools import wraps
def alias(original_name: str, alternative_names: list):
FILL_FUNC_BODY | from functools import wraps
def alias(original_name: str, alternative_names: list):
FILL_FUNC_BODY | def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for alt_name in alternative_names:
if alt_name in kwargs:
kwargs[original_name] = kwargs.pop(alt_name)
break
return func(*args, **kwargs)
return wr... | def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for alt_name in alternative_names:
if alt_name in kwargs:
kwargs[original_name] = kwargs.pop(alt_name)
break
return func(*args, **kwargs)
return wr... | 25 | 36 | 105 | 141 | from functools import wraps
def alias(original_name: str, alternative_names: list):
FILL_FUNC_BODY | from functools import wraps
def alias(original_name: str, alternative_names: list):
FILL_FUNC_BODY | |
36,790 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/utils/hf_utils.py | 54,55 | 1,93 | get_model_class | 55,72 | 55,72 | from typing import Tuple
from collections import namedtuple
from transformers import (
BertModel,
BertConfig,
AlbertModel,
AlbertConfig,
ElectraModel,
RobertaModel,
BertTokenizer,
ElectraConfig,
RobertaConfig,
AlbertTokenizer,
DistilBertModel,
PreTrainedModel,
Distil... | from typing import Tuple
from collections import namedtuple
from transformers import (
BertModel,
BertConfig,
AlbertModel,
AlbertConfig,
ElectraModel,
RobertaModel,
BertTokenizer,
ElectraConfig,
RobertaConfig,
AlbertTokenizer,
DistilBertModel,
PreTrainedModel,
Distil... | if "distilbert" in model_name:
return "distilbert"
elif "roberta" in model_name:
return "roberta"
elif "albert" in model_name:
return "albert"
elif "electra" in model_name:
return "electra"
elif "bert" in model_name:
return "bert"
else:
raise Value... | if "distilbert" in model_name:
return "distilbert"
elif "roberta" in model_name:
return "roberta"
elif "albert" in model_name:
return "albert"
elif "electra" in model_name:
return "electra"
elif "bert" in model_name:
return "bert"
else:
raise Value... | 52 | 664 | 176 | 840 | from typing import Tuple
from collections import namedtuple
from transformers import (
BertModel,
BertConfig,
AlbertModel,
AlbertConfig,
ElectraModel,
RobertaModel,
BertTokenizer,
ElectraConfig,
RobertaConfig,
AlbertTokenizer,
DistilBertModel,
PreTrainedModel,
Distil... | from typing import Tuple
from collections import namedtuple
from transformers import (
BertModel,
BertConfig,
AlbertModel,
AlbertConfig,
ElectraModel,
RobertaModel,
BertTokenizer,
ElectraConfig,
RobertaConfig,
AlbertTokenizer,
DistilBertModel,
PreTrainedModel,
Distil... | |
36,791 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/utils/image_utils.py | 37,38 | 17,83 | preprocess | AspectAwarePreprocessor | 38,83 | 38,83 | class AspectAwarePreprocessor:
r"""Class to resize an image to a certain width and height taking into account
the image aspect ratio
Parameters
----------
width: int
output width
height: int
output height
inter: interpolation method, default = ``cv2.INTER_AREA``
``o... | class AspectAwarePreprocessor:
r"""Class to resize an image to a certain width and height taking into account
the image aspect ratio
Parameters
----------
width: int
output width
height: int
output height
inter: interpolation method, default = ``cv2.INTER_AREA``
``o... | r"""Returns the resized input image taking into account the image aspect ratio
Parameters
----------
image: np.ndarray
Input image to be resized
Examples
--------
>>> import cv2
>>> from pytorch_widedeep.utils import AspectAwarePreprocessor
... | r"""Returns the resized input image taking into account the image aspect ratio
Parameters
----------
image: np.ndarray
Input image to be resized
Examples
--------
>>> import cv2
>>> from pytorch_widedeep.utils import AspectAwarePreprocessor
... | 132 | 190 | 479 | 669 | """
AspectAwarePreprocessor and SimplePreprocessor are directly taked from the
great series of Books "Deep Learning for Computer Vision" by Adrian
(https://www.pyimagesearch.com/author/adrian/). Check here
https://www.pyimagesearch.com/
Credit for the code here to ADRIAN ROSEBROCK
"""
import cv2
import numpy as np
im... | """
AspectAwarePreprocessor and SimplePreprocessor are directly taked from the
great series of Books "Deep Learning for Computer Vision" by Adrian
(https://www.pyimagesearch.com/author/adrian/). Check here
https://www.pyimagesearch.com/
Credit for the code here to ADRIAN ROSEBROCK
"""
import cv2
import numpy as np
im... |
36,792 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/utils/image_utils.py | 102,103 | 83,121 | preprocess | SimplePreprocessor | 103,121 | 103,121 | class SimplePreprocessor:
r"""Class to resize an image to a certain width and height
Parameters
----------
width: int
output width
height: int
output height
inter: interpolation method, default = ``cv2.INTER_AREA``
``opencv`` interpolation method. See ``opencv``
... | class SimplePreprocessor:
r"""Class to resize an image to a certain width and height
Parameters
----------
width: int
output width
height: int
output height
inter: interpolation method, default = ``cv2.INTER_AREA``
``opencv`` interpolation method. See ``opencv``
... | r"""Returns the resized input image
Parameters
----------
image: np.ndarray
Input image to be resized
Returns
-------
np.ndarray
Resized image
"""
resized_image = cv2.resize(
image, (self.width, self.height), ... | r"""Returns the resized input image
Parameters
----------
image: np.ndarray
Input image to be resized
Returns
-------
np.ndarray
Resized image
"""
resized_image = cv2.resize(
image, (self.width, self.height), ... | 30 | 177 | 119 | 296 | """
AspectAwarePreprocessor and SimplePreprocessor are directly taked from the
great series of Books "Deep Learning for Computer Vision" by Adrian
(https://www.pyimagesearch.com/author/adrian/). Check here
https://www.pyimagesearch.com/
Credit for the code here to ADRIAN ROSEBROCK
"""
import cv2
import numpy as np
im... | """
AspectAwarePreprocessor and SimplePreprocessor are directly taked from the
great series of Books "Deep Learning for Computer Vision" by Adrian
(https://www.pyimagesearch.com/author/adrian/). Check here
https://www.pyimagesearch.com/
Credit for the code here to ADRIAN ROSEBROCK
"""
import cv2
import numpy as np
im... |
36,794 | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep | /home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/setup.py | 8,9 | 1,89 | requirements | 9,14 | 9,14 | #!/usr/bin/env python3
# flake8: noqa
import os
import setuptools
def requirements(fname):
FILL_FUNC_BODYpwd = os.path.dirname(__file__)
dev_status = {
"0.1": "Development Status :: 1 - Planning", # v0.1 - skeleton
"0.2": "Development Status :: 2 - Pre-Alpha", # v0.2 - some basic functionality
"0.3": ... | #!/usr/bin/env python3
# flake8: noqa
import os
import setuptools
def requirements(fname):
FILL_FUNC_BODYpwd = os.path.dirname(__file__)
dev_status = {
"0.1": "Development Status :: 1 - Planning", # v0.1 - skeleton
"0.2": "Development Status :: 2 - Pre-Alpha", # v0.2 - some basic functionality
"0.3": ... | return [
line.strip() for line in open(os.path.join(os.path.dirname(__file__), fname))
]
| return [
line.strip() for line in open(os.path.join(os.path.dirname(__file__), fname))
]
| 9 | 1,081 | 44 | 1,125 | #!/usr/bin/env python3
# flake8: noqa
import os
import setuptools
def requirements(fname):
FILL_FUNC_BODYpwd = os.path.dirname(__file__)
dev_status = {
"0.1": "Development Status :: 1 - Planning", # v0.1 - skeleton
"0.2": "Development Status :: 2 - Pre-Alpha", # v0.2 - some basic functionality
"0.3": ... | #!/usr/bin/env python3
# flake8: noqa
import os
import setuptools
def requirements(fname):
FILL_FUNC_BODYpwd = os.path.dirname(__file__)
dev_status = {
"0.1": "Development Status :: 1 - Planning", # v0.1 - skeleton
"0.2": "Development Status :: 2 - Pre-Alpha", # v0.2 - some basic functionality
"0.3": ... | |
36,827 | /home/hieuvd/dung_repo/raw/stars_02/justinpinkney_awesome-pretrained-stylegan2/awesome-pretrained-stylegan2 | /home/hieuvd/dung_repo/raw/stars_02/justinpinkney_awesome-pretrained-stylegan2/awesome-pretrained-stylegan2/make_readme.py | 6,7 | 1,31 | make_thumbnail | 7,15 | 7,15 | import json
import jinja2
from PIL import Image
import os
def make_thumbnail(filename):
FILL_FUNC_BODYmodel_file = "models.json"
output_file = "README.md"
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('template.md')
with open(model_file) as jsonfile:
reader = json.load(... | import json
import jinja2
from PIL import Image
import os
def make_thumbnail(filename):
FILL_FUNC_BODYmodel_file = "models.json"
output_file = "README.md"
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('template.md')
with open(model_file) as jsonfile:
reader = json.load(... | image_name = f"content/{filename}/samples.jpg"
if not os.path.exists(image_name):
return
im = Image.open(image_name)
thumb = im.crop((0,0,256,256))
thumb = thumb.resize((128,128))
thumb.save(f"content/{filename}/thumbnail.jpg")
| image_name = f"content/{filename}/samples.jpg"
if not os.path.exists(image_name):
return
im = Image.open(image_name)
thumb = im.crop((0,0,256,256))
thumb = thumb.resize((128,128))
thumb.save(f"content/{filename}/thumbnail.jpg")
| 17 | 183 | 109 | 292 | import json
import jinja2
from PIL import Image
import os
def make_thumbnail(filename):
FILL_FUNC_BODYmodel_file = "models.json"
output_file = "README.md"
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('template.md')
with open(model_file) as jsonfile:
reader = json.load(... | import json
import jinja2
from PIL import Image
import os
def make_thumbnail(filename):
FILL_FUNC_BODYmodel_file = "models.json"
output_file = "README.md"
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('template.md')
with open(model_file) as jsonfile:
reader = json.load(... | |
36,828 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/bangumi.py | 13,17 | 1,87 | calendar | 20,26 | 17,26 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.bangumi import BangumiChain
from app.core.context import MediaInfo
from app.core.security import verify_token
router = APIRouter()
@router.get("/calendar", summary="Bangumi每日放送", response_model=List[schemas.M... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.bangumi import BangumiChain
from app.core.context import MediaInfo
from app.core.security import verify_token
router = APIRouter()
@router.get("/calendar", summary="Bangumi每日放送", response_model=List[schemas.M... | medias = BangumiChain().calendar()
if medias:
return [media.to_dict() for media in medias[(page - 1) * count: page * count]]
return []
| """
浏览Bangumi每日放送
"""
medias = BangumiChain().calendar()
if medias:
return [media.to_dict() for media in medias[(page - 1) * count: page * count]]
return []
| 20 | 940 | 58 | 998 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.bangumi import BangumiChain
from app.core.context import MediaInfo
from app.core.security import verify_token
router = APIRouter()
@router.get("/calendar", summary="Bangumi每日放送", response_model=List[schemas.M... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.bangumi import BangumiChain
from app.core.context import MediaInfo
from app.core.security import verify_token
router = APIRouter()
@router.get("/calendar", summary="Bangumi每日放送", response_model=List[schemas.M... | |
36,829 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/dashboard.py | 73,75 | 1,154 | downloader | 78,90 | 75,90 | from typing import Any, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.dashboard import DashboardChain
from app.core.config import settings
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.d... | from typing import Any, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.dashboard import DashboardChain
from app.core.config import settings
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.d... | downloader_info = schemas.DownloaderInfo()
transfer_infos = DashboardChain().downloader_info()
if transfer_infos:
for transfer_info in transfer_infos:
downloader_info.download_speed += transfer_info.download_speed
downloader_info.upload_speed += transfer_info.upload_speed
... | """
查询下载器信息
"""
downloader_info = schemas.DownloaderInfo()
transfer_infos = DashboardChain().downloader_info()
if transfer_infos:
for transfer_info in transfer_infos:
downloader_info.download_speed += transfer_info.download_speed
downloader_info.upload_speed += tr... | 29 | 1,542 | 168 | 1,710 | from typing import Any, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.dashboard import DashboardChain
from app.core.config import settings
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.d... | from typing import Any, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.dashboard import DashboardChain
from app.core.config import settings
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.d... | |
36,831 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/download.py | 26,31 | 1,113 | download | 34,54 | 31,54 | from typing import Any, List
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.download import DownloadChain
from app.chain.media import MediaChain
from app.core.context import MediaInfo, Context, TorrentInfo
from app.core.metainfo import MetaInfo
from app.core.security import verify_token... | from typing import Any, List
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.download import DownloadChain
from app.chain.media import MediaChain
from app.core.context import MediaInfo, Context, TorrentInfo
from app.core.metainfo import MetaInfo
from app.core.security import verify_token... | # 元数据
metainfo = MetaInfo(title=torrent_in.title, subtitle=torrent_in.description)
# 媒体信息
mediainfo = MediaInfo()
mediainfo.from_dict(media_in.dict())
# 种子信息
torrentinfo = TorrentInfo()
torrentinfo.from_dict(torrent_in.dict())
# 上下文
context = Context(
meta_info=metainfo,
... | """
添加下载任务(含媒体信息)
"""
# 元数据
metainfo = MetaInfo(title=torrent_in.title, subtitle=torrent_in.description)
# 媒体信息
mediainfo = MediaInfo()
mediainfo.from_dict(media_in.dict())
# 种子信息
torrentinfo = TorrentInfo()
torrentinfo.from_dict(torrent_in.dict())
# 上下文
context = Con... | 41 | 948 | 217 | 1,165 | from typing import Any, List
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.download import DownloadChain
from app.chain.media import MediaChain
from app.core.context import MediaInfo, Context, TorrentInfo
from app.core.metainfo import MetaInfo
from app.core.security import verify_token... | from typing import Any, List
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.download import DownloadChain
from app.chain.media import MediaChain
from app.core.context import MediaInfo, Context, TorrentInfo
from app.core.metainfo import MetaInfo
from app.core.security import verify_token... | |
36,832 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/filebrowser.py | 19,23 | 1,190 | list_path | 30,101 | 23,101 | import shutil
from pathlib import Path
from typing import Any, List
from fastapi import APIRouter, Depends
from starlette.responses import FileResponse, Response
from app import schemas
from app.core.config import settings
from app.core.security import verify_token
from app.log import logger
from app.utils.system imp... | import shutil
from pathlib import Path
from typing import Any, List
from fastapi import APIRouter, Depends
from starlette.responses import FileResponse, Response
from app import schemas
from app.core.config import settings
from app.core.security import verify_token
from app.log import logger
from app.utils.system imp... | # 返回结果
ret_items = []
if not path or path == "/":
if SystemUtils.is_windows():
partitions = SystemUtils.get_windows_drives() or ["C:/"]
for partition in partitions:
ret_items.append(schemas.FileItem(
type="dir",
path=par... | """
查询当前目录下所有目录和文件
:param path: 目录路径
:param sort: 排序方式,name:按名称排序,time:按修改时间排序
:param _: token
:return: 所有目录和文件
"""
# 返回结果
ret_items = []
if not path or path == "/":
if SystemUtils.is_windows():
partitions = SystemUtils.get_windows_drives() or ["C:/"]
... | 132 | 1,202 | 749 | 1,951 | import shutil
from pathlib import Path
from typing import Any, List
from fastapi import APIRouter, Depends
from starlette.responses import FileResponse, Response
from app import schemas
from app.core.config import settings
from app.core.security import verify_token
from app.log import logger
from app.utils.system imp... | import shutil
from pathlib import Path
from typing import Any, List
from fastapi import APIRouter, Depends
from starlette.responses import FileResponse, Response
from app import schemas
from app.core.config import settings
from app.core.security import verify_token
from app.log import logger
from app.utils.system imp... | |
36,833 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/login.py | 22,28 | 1,113 | login_access_token | 31,75 | 28,75 | from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import schemas
from app.chain.tmdb import TmdbChain
from app.chain.user import UserChain
from app.core im... | from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import schemas
from app.chain.tmdb import TmdbChain
from app.chain.user import UserChain
from app.core im... | # 检查数据库
success, user = User.authenticate(
db=db,
name=form_data.username,
password=form_data.password,
otp_password=otp_password
)
if not success:
# 认证不成功
if not user:
# 未找到用户,请求协助认证
logger.warn(f"登录用户 {form_data.username} 本地不存在,尝试... | """
获取认证Token
"""
# 检查数据库
success, user = User.authenticate(
db=db,
name=form_data.username,
password=form_data.password,
otp_password=otp_password
)
if not success:
# 认证不成功
if not user:
# 未找到用户,请求协助认证
logger.warn(f"登录用户... | 87 | 596 | 615 | 1,211 | from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import schemas
from app.chain.tmdb import TmdbChain
from app.chain.user import UserChain
from app.core im... | from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import schemas
from app.chain.tmdb import TmdbChain
from app.chain.user import UserChain
from app.core im... | |
36,834 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/media.py | 17,21 | 1,144 | recognize | 24,32 | 21,32 | from pathlib import Path
from typing import List, Any, Union
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.core.config import settings
from app.core.context import Context
from app.core.metainfo import MetaInfo, MetaInfoPath
from app.core.security impor... | from pathlib import Path
from typing import List, Any, Union
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.core.config import settings
from app.core.context import Context
from app.core.metainfo import MetaInfo, MetaInfoPath
from app.core.security impor... | # 识别媒体信息
metainfo = MetaInfo(title, subtitle)
mediainfo = MediaChain().recognize_by_meta(metainfo)
if mediainfo:
return Context(meta_info=metainfo, media_info=mediainfo).to_dict()
return schemas.Context()
| """
根据标题、副标题识别媒体信息
"""
# 识别媒体信息
metainfo = MetaInfo(title, subtitle)
mediainfo = MediaChain().recognize_by_meta(metainfo)
if mediainfo:
return Context(meta_info=metainfo, media_info=mediainfo).to_dict()
return schemas.Context()
| 16 | 1,577 | 92 | 1,669 | from pathlib import Path
from typing import List, Any, Union
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.core.config import settings
from app.core.context import Context
from app.core.metainfo import MetaInfo, MetaInfoPath
from app.core.security impor... | from pathlib import Path
from typing import List, Any, Union
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.core.config import settings
from app.core.context import Context
from app.core.metainfo import MetaInfo, MetaInfoPath
from app.core.security impor... | |
36,835 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/mediaserver.py | 88,91 | 1,142 | not_exists | 94,118 | 91,118 | from typing import Any, List, Dict
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.download import DownloadChain
from app.chain.mediaserver import MediaServerChain
from app.core.config import settings
from app.core.context import MediaInfo
from app.core... | from typing import Any, List, Dict
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.download import DownloadChain
from app.chain.mediaserver import MediaServerChain
from app.core.config import settings
from app.core.context import MediaInfo
from app.core... | # 媒体信息
meta = MetaInfo(title=media_in.title)
mtype = MediaType(media_in.type) if media_in.type else None
if mtype:
meta.type = mtype
if media_in.season:
meta.begin_season = media_in.season
meta.type = MediaType.TV
if media_in.year:
meta.year = media_in.year
# ... | """
根据媒体信息查询缺失电影/剧集
"""
# 媒体信息
meta = MetaInfo(title=media_in.title)
mtype = MediaType(media_in.type) if media_in.type else None
if mtype:
meta.type = mtype
if media_in.season:
meta.begin_season = media_in.season
meta.type = MediaType.TV
if media_in.year:
... | 68 | 1,313 | 331 | 1,644 | from typing import Any, List, Dict
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.download import DownloadChain
from app.chain.mediaserver import MediaServerChain
from app.core.config import settings
from app.core.context import MediaInfo
from app.core... | from typing import Any, List, Dict
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.download import DownloadChain
from app.chain.mediaserver import MediaServerChain
from app.core.config import settings
from app.core.context import MediaInfo
from app.core... | |
36,836 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/message.py | 99,100 | 1,153 | vocechat_verify | 103,108 | 100,108 | from typing import Union, Any, List
from fastapi import APIRouter, BackgroundTasks, Depends
from fastapi import Request
from sqlalchemy.orm import Session
from starlette.responses import PlainTextResponse
from app import schemas
from app.chain.message import MessageChain
from app.core.config import settings
from app.... | from typing import Union, Any, List
from fastapi import APIRouter, BackgroundTasks, Depends
from fastapi import Request
from sqlalchemy.orm import Session
from starlette.responses import PlainTextResponse
from app import schemas
from app.chain.message import MessageChain
from app.core.config import settings
from app.... | if token == settings.API_TOKEN:
return {"status": "OK"}
return {"status": "ERROR"}
| """
VoceChat验证响应
"""
if token == settings.API_TOKEN:
return {"status": "OK"}
return {"status": "ERROR"}
| 10 | 1,578 | 38 | 1,616 | from typing import Union, Any, List
from fastapi import APIRouter, BackgroundTasks, Depends
from fastapi import Request
from sqlalchemy.orm import Session
from starlette.responses import PlainTextResponse
from app import schemas
from app.chain.message import MessageChain
from app.core.config import settings
from app.... | from typing import Union, Any, List
from fastapi import APIRouter, BackgroundTasks, Depends
from fastapi import Request
from sqlalchemy.orm import Session
from starlette.responses import PlainTextResponse
from app import schemas
from app.chain.message import MessageChain
from app.core.config import settings
from app.... | |
36,838 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/search.py | 24,30 | 1,98 | search_by_id | 33,88 | 30,88 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.chain.search import SearchChain
from app.core.config import settings
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@r... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.chain.search import SearchChain
from app.core.config import settings
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@r... | if mtype:
mtype = MediaType(mtype)
if season:
season = int(season)
if mediaid.startswith("tmdb:"):
tmdbid = int(mediaid.replace("tmdb:", ""))
if settings.RECOGNIZE_SOURCE == "douban":
# 通过TMDBID识别豆瓣ID
doubaninfo = MediaChain().get_doubaninfo_by_tmdbid(... | """
根据TMDBID/豆瓣ID精确搜索站点资源 tmdb:/douban:/bangumi:
"""
if mtype:
mtype = MediaType(mtype)
if season:
season = int(season)
if mediaid.startswith("tmdb:"):
tmdbid = int(mediaid.replace("tmdb:", ""))
if settings.RECOGNIZE_SOURCE == "douban":
# 通过TMDBID识别豆瓣I... | 143 | 476 | 946 | 1,422 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.chain.search import SearchChain
from app.core.config import settings
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@r... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.media import MediaChain
from app.chain.search import SearchChain
from app.core.config import settings
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@r... | |
36,839 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/tmdb.py | 121,127 | 1,159 | tmdb_tvs | 130,140 | 127,140 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.tmdb import TmdbChain
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@router.get("/seasons/{tmdbid}", summary="TMDB所有季", response_model=List[schemas.Tm... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.tmdb import TmdbChain
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@router.get("/seasons/{tmdbid}", summary="TMDB所有季", response_model=List[schemas.Tm... | tvs = TmdbChain().tmdb_discover(mtype=MediaType.TV,
sort_by=sort_by,
with_genres=with_genres,
with_original_language=with_original_language,
page=page)
if not tvs:
... | """
浏览TMDB剧集信息
"""
tvs = TmdbChain().tmdb_discover(mtype=MediaType.TV,
sort_by=sort_by,
with_genres=with_genres,
with_original_language=with_original_language,
... | 18 | 1,759 | 105 | 1,864 | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.tmdb import TmdbChain
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@router.get("/seasons/{tmdbid}", summary="TMDB所有季", response_model=List[schemas.Tm... | from typing import List, Any
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.tmdb import TmdbChain
from app.core.security import verify_token
from app.schemas.types import MediaType
router = APIRouter()
@router.get("/seasons/{tmdbid}", summary="TMDB所有季", response_model=List[schemas.Tm... | |
36,840 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/endpoints/transfer.py | 17,33 | 1,120 | manual_transfer | 51,113 | 33,113 | from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.transfer import TransferChain
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.db.models.transferhistory impor... | from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.transfer import TransferChain
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.db.models.transferhistory impor... | force = False
target = Path(target) if target else None
transfer = TransferChain()
if logid:
# 查询历史记录
history: TransferHistory = TransferHistory.get(db, logid)
if not history:
return schemas.Response(success=False, message=f"历史记录不存在,ID:{logid}")
# 强制转移
... | """
手动转移,文件或历史记录,支持自定义剧集识别格式
:param path: 转移路径或文件
:param logid: 转移历史记录ID
:param target: 目标路径
:param type_name: 媒体类型、电影/电视剧
:param tmdbid: tmdbid
:param doubanid: 豆瓣ID
:param season: 剧集季号
:param transfer_type: 转移类型,move/copy 等
:param episode_format: 剧集识别格式
:param episode_d... | 147 | 626 | 678 | 1,304 | from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.transfer import TransferChain
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.db.models.transferhistory impor... | from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import schemas
from app.chain.transfer import TransferChain
from app.core.security import verify_token, verify_uri_token
from app.db import get_db
from app.db.models.transferhistory impor... | |
36,842 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/servcookie.py | 54,56 | 1,138 | get_root | 56,59 | 56,59 | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | return "Hello MoviePilot! COOKIECLOUD API ROOT = /cookiecloud"
| return "Hello MoviePilot! COOKIECLOUD API ROOT = /cookiecloud"
| 8 | 1,313 | 30 | 1,343 | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | |
36,843 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/servcookie.py | 19,20 | 17,28 | body | GzipRequest | 20,28 | 20,28 | class GzipRequest(Request):
async def body(self) -> bytes:
FILL_FUNC_BODY | class GzipRequest(Request):
async def body(self) -> bytes:
FILL_FUNC_BODY | if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("Content-Encoding"):
body = gzip.decompress(body)
self._body = body
return self._body
| if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("Content-Encoding"):
body = gzip.decompress(body)
self._body = body
return self._body
| 20 | 31 | 78 | 109 | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... |
36,844 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/api/servcookie.py | 30,31 | 28,40 | get_route_handler | GzipRoute | 31,40 | 31,40 | class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
FILL_FUNC_BODY | class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
FILL_FUNC_BODY | original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
request = GzipRequest(request.scope, request.receive)
return await original_route_handler(request)
return custom_route_handler
| original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
request = GzipRequest(request.scope, request.receive)
return await original_route_handler(request)
return custom_route_handler
| 18 | 37 | 84 | 121 | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... | import gzip
import json
from hashlib import md5
from typing import Annotated, Callable
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Path, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.routing import APIRoute
from app import schemas
from... |
36,845 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/bangumi.py | 14,15 | 9,55 | calendar | BangumiChain | 18,20 | 15,20 | class BangumiChain(ChainBase, metaclass=Singleton):
"""
Bangumi处理链,单例运行
"""
def calendar(self) -> Optional[List[MediaInfo]]:
FILL_FUNC_BODY def bangumi_info(self, bangumiid: int) -> Optional[dict]:
"""
获取Bangumi信息
:param bangumiid: BangumiID
:return: Bangumi信息
... | class BangumiChain(ChainBase, metaclass=Singleton):
"""
Bangumi处理链,单例运行
"""
def calendar(self) -> Optional[List[MediaInfo]]:
"""
获取Bangumi每日放送
"""
FILL_FUNC_BODY def bangumi_info(self, bangumiid: int) -> Optional[dict]:
"""
获取Bangumi信息
:param bangumiid... | return self.run_module("bangumi_calendar")
| """
获取Bangumi每日放送
"""
return self.run_module("bangumi_calendar")
| 2 | 533 | 19 | 552 | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.core.context import MediaInfo
from app.utils.singleton import Singleton
class BangumiChain(ChainBase, metaclass=Singleton):
"""
Bangumi处理链,单例运行
"""
def calendar(self) -> Optional[List[MediaInfo]]:
FILL... | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.core.context import MediaInfo
from app.utils.singleton import Singleton
class BangumiChain(ChainBase, metaclass=Singleton):
"""
Bangumi处理链,单例运行
"""
def calendar(self) -> Optional[List[MediaInfo]]:
... |
36,846 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/dashboard.py | 18,19 | 8,23 | downloader_info | DashboardChain | 22,23 | 19,23 | class DashboardChain(ChainBase, metaclass=Singleton):
"""
各类仪表板统计处理链
"""
def media_statistic(self) -> Optional[List[schemas.Statistic]]:
"""
媒体数量统计
"""
return self.run_module("media_statistic")
def downloader_info(self) -> Optional[List[schemas.DownloaderInfo]]:
FILL... | class DashboardChain(ChainBase, metaclass=Singleton):
"""
各类仪表板统计处理链
"""
def media_statistic(self) -> Optional[List[schemas.Statistic]]:
"""
媒体数量统计
"""
return self.run_module("media_statistic")
def downloader_info(self) -> Optional[List[schemas.DownloaderInfo]]:
... | return self.run_module("downloader_info")
| """
下载器信息
"""
return self.run_module("downloader_info")
| 2 | 127 | 15 | 142 | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.utils.singleton import Singleton
class DashboardChain(ChainBase, metaclass=Singleton):
"""
各类仪表板统计处理链
"""
def media_statistic(self) -> Optional[List[schemas.Statistic]]:
"""
媒体数量统计
... | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.utils.singleton import Singleton
class DashboardChain(ChainBase, metaclass=Singleton):
"""
各类仪表板统计处理链
"""
def media_statistic(self) -> Optional[List[schemas.Statistic]]:
"""
媒体数量统计
... |
36,847 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/douban.py | 30,31 | 10,115 | movie_top250 | DoubanChain | 36,38 | 31,38 | class DoubanChain(ChainBase, metaclass=Singleton):
"""
豆瓣处理链,单例运行
"""
def person_detail(self, person_id: int) -> Optional[schemas.MediaPerson]:
"""
根据人物ID查询豆瓣人物详情
:param person_id: 人物ID
"""
return self.run_module("douban_person_detail", person_id=person_id)
... | class DoubanChain(ChainBase, metaclass=Singleton):
"""
豆瓣处理链,单例运行
"""
def person_detail(self, person_id: int) -> Optional[schemas.MediaPerson]:
"""
根据人物ID查询豆瓣人物详情
:param person_id: 人物ID
"""
return self.run_module("douban_person_detail", person_id=person_id)
... | return self.run_module("movie_top250", page=page, count=count)
| """
获取豆瓣电影TOP250
:param page: 页码
:param count: 每页数量
"""
return self.run_module("movie_top250", page=page, count=count)
| 4 | 1,250 | 28 | 1,278 | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.core.context import MediaInfo
from app.schemas import MediaType
from app.utils.singleton import Singleton
class DoubanChain(ChainBase, metaclass=Singleton):
"""
豆瓣处理链,单例运行
"""
def person_detail(self, p... | from typing import Optional, List
from app import schemas
from app.chain import ChainBase
from app.core.context import MediaInfo
from app.schemas import MediaType
from app.utils.singleton import Singleton
class DoubanChain(ChainBase, metaclass=Singleton):
"""
豆瓣处理链,单例运行
"""
def person_detail(self, p... |
36,850 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/mediaserver.py | 65,66 | 14,115 | sync | MediaServerChain | 69,115 | 66,115 | class MediaServerChain(ChainBase):
"""
媒体服务器处理链
"""
def __init__(self):
super().__init__()
self.dboper = MediaServerOper()
def librarys(self, server: str = None, username: str = None) -> List[schemas.MediaServerLibrary]:
"""
获取媒体服务器所有媒体库
"""
return s... | class MediaServerChain(ChainBase):
"""
媒体服务器处理链
"""
def __init__(self):
super().__init__()
self.dboper = MediaServerOper()
def librarys(self, server: str = None, username: str = None) -> List[schemas.MediaServerLibrary]:
"""
获取媒体服务器所有媒体库
"""
return s... | # 设置的媒体服务器
if not settings.MEDIASERVER:
return
# 同步黑名单
sync_blacklist = settings.MEDIASERVER_SYNC_BLACKLIST.split(
",") if settings.MEDIASERVER_SYNC_BLACKLIST else []
mediaservers = settings.MEDIASERVER.split(",")
with lock:
# 汇总统计
... | """
同步媒体库所有数据到本地数据库
"""
# 设置的媒体服务器
if not settings.MEDIASERVER:
return
# 同步黑名单
sync_blacklist = settings.MEDIASERVER_SYNC_BLACKLIST.split(
",") if settings.MEDIASERVER_SYNC_BLACKLIST else []
mediaservers = settings.MEDIASERVER.split... | 138 | 630 | 626 | 1,256 | import json
import threading
from typing import List, Union, Optional
from app import schemas
from app.chain import ChainBase
from app.core.config import settings
from app.db.mediaserver_oper import MediaServerOper
from app.log import logger
lock = threading.Lock()
class MediaServerChain(ChainBase):
"""
媒体服... | import json
import threading
from typing import List, Union, Optional
from app import schemas
from app.chain import ChainBase
from app.core.config import settings
from app.db.mediaserver_oper import MediaServerOper
from app.log import logger
lock = threading.Lock()
class MediaServerChain(ChainBase):
"""
媒体服... |
36,853 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/system.py | 129,131 | 15,167 | get_server_local_version | SystemChain | 134,151 | 131,151 | class SystemChain(ChainBase, metaclass=Singleton):
"""
系统级处理链
"""
_restart_file = "__system_restart__"
def remote_clear_cache(self, channel: MessageChannel, userid: Union[int, str]):
"""
清理系统缓存
"""
self.clear_cache()
self.post_message(Notification(channel=ch... | class SystemChain(ChainBase, metaclass=Singleton):
"""
系统级处理链
"""
_restart_file = "__system_restart__"
def remote_clear_cache(self, channel: MessageChannel, userid: Union[int, str]):
"""
清理系统缓存
"""
self.clear_cache()
self.post_message(Notification(channel=ch... | version_file = settings.ROOT_PATH / "version.py"
if version_file.exists():
try:
with open(version_file, 'rb') as f:
version = f.read()
pattern = r"'([^']*)'"
match = re.search(pattern, str(version))
if match... | """
查看当前版本
"""
version_file = settings.ROOT_PATH / "version.py"
if version_file.exists():
try:
with open(version_file, 'rb') as f:
version = f.read()
pattern = r"'([^']*)'"
match = re.search(pattern, ... | 41 | 1,397 | 171 | 1,568 | import json
import re
from pathlib import Path
from typing import Union
from app.chain import ChainBase
from app.core.config import settings
from app.log import logger
from app.schemas import Notification, MessageChannel
from app.utils.http import RequestUtils
from app.utils.singleton import Singleton
from app.utils.s... | import json
import re
from pathlib import Path
from typing import Union
from app.chain import ChainBase
from app.core.config import settings
from app.log import logger
from app.schemas import Notification, MessageChannel
from app.utils.http import RequestUtils
from app.utils.singleton import Singleton
from app.utils.s... |
36,854 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/tmdb.py | 108,109 | 14,129 | person_credits | TmdbChain | 114,116 | 109,116 | class TmdbChain(ChainBase, metaclass=Singleton):
"""
TheMovieDB处理链,单例运行
"""
def tmdb_discover(self, mtype: MediaType, sort_by: str, with_genres: str,
with_original_language: str, page: int = 1) -> Optional[List[MediaInfo]]:
"""
:param mtype: 媒体类型
:param so... | class TmdbChain(ChainBase, metaclass=Singleton):
"""
TheMovieDB处理链,单例运行
"""
def tmdb_discover(self, mtype: MediaType, sort_by: str, with_genres: str,
with_original_language: str, page: int = 1) -> Optional[List[MediaInfo]]:
"""
:param mtype: 媒体类型
:param so... | return self.run_module("tmdb_person_credits", person_id=person_id, page=page)
| """
根据人物ID查询人物参演作品
:param person_id: 人物ID
:param page: 页码
"""
return self.run_module("tmdb_person_credits", person_id=person_id, page=page)
| 4 | 1,396 | 32 | 1,428 | import random
from typing import Optional, List
from cachetools import cached, TTLCache
from app import schemas
from app.chain import ChainBase
from app.core.config import settings
from app.core.context import MediaInfo
from app.schemas import MediaType
from app.utils.singleton import Singleton
class TmdbChain(Chai... | import random
from typing import Optional, List
from cachetools import cached, TTLCache
from app import schemas
from app.chain import ChainBase
from app.core.config import settings
from app.core.context import MediaInfo
from app.schemas import MediaType
from app.utils.singleton import Singleton
class TmdbChain(Chai... |
36,856 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/user.py | 8,9 | 6,16 | user_authenticate | UserChain | 15,16 | 9,16 | class UserChain(ChainBase):
def user_authenticate(self, name, password) -> Optional[str]:
FILL_FUNC_BODY | class UserChain(ChainBase):
def user_authenticate(self, name, password) -> Optional[str]:
"""
辅助完成用户认证
:param name: 用户名
:param password: 密码
:return: token
"""
FILL_FUNC_BODY | return self.run_module("user_authenticate", name=name, password=password)
| """
辅助完成用户认证
:param name: 用户名
:param password: 密码
:return: token
"""
return self.run_module("user_authenticate", name=name, password=password)
| 4 | 77 | 24 | 101 | from typing import Optional
from app.chain import ChainBase
class UserChain(ChainBase):
def user_authenticate(self, name, password) -> Optional[str]:
FILL_FUNC_BODY | from typing import Optional
from app.chain import ChainBase
class UserChain(ChainBase):
def user_authenticate(self, name, password) -> Optional[str]:
"""
辅助完成用户认证
:param name: 用户名
:param password: 密码
:return: token
"""
FILL_FUNC_BODY |
36,857 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/chain/webhook.py | 13,14 | 8,23 | message | WebhookChain | 17,23 | 14,23 | class WebhookChain(ChainBase, metaclass=Singleton):
"""
Webhook处理链
"""
def message(self, body: Any, form: Any, args: Any) -> None:
FILL_FUNC_BODY | class WebhookChain(ChainBase, metaclass=Singleton):
"""
Webhook处理链
"""
def message(self, body: Any, form: Any, args: Any) -> None:
"""
处理Webhook报文并发送事件
"""
FILL_FUNC_BODY | # 获取主体内容
event_info = self.webhook_parser(body=body, form=form, args=args)
if not event_info:
return
# 广播事件
self.eventmanager.send_event(EventType.WebhookMessage, event_info)
| """
处理Webhook报文并发送事件
"""
# 获取主体内容
event_info = self.webhook_parser(body=body, form=form, args=args)
if not event_info:
return
# 广播事件
self.eventmanager.send_event(EventType.WebhookMessage, event_info)
| 15 | 80 | 78 | 158 | from typing import Any
from app.chain import ChainBase
from app.schemas.types import EventType
from app.utils.singleton import Singleton
class WebhookChain(ChainBase, metaclass=Singleton):
"""
Webhook处理链
"""
def message(self, body: Any, form: Any, args: Any) -> None:
FILL_FUNC_BODY | from typing import Any
from app.chain import ChainBase
from app.schemas.types import EventType
from app.utils.singleton import Singleton
class WebhookChain(ChainBase, metaclass=Singleton):
"""
Webhook处理链
"""
def message(self, body: Any, form: Any, args: Any) -> None:
"""
处理Webhook报文并... |
36,859 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/context.py | 760,761 | 747,769 | to_dict | Context | 764,769 | 761,769 | @dataclass
class Context:
"""
上下文对象
"""
# 识别信息
meta_info: MetaBase = None
# 媒体信息
media_info: MediaInfo = None
# 种子信息
torrent_info: TorrentInfo = None
def to_dict(self):
FILL_FUNC_BODY | @dataclass
class Context:
"""
上下文对象
"""
# 识别信息
meta_info: MetaBase = None
# 媒体信息
media_info: MediaInfo = None
# 种子信息
torrent_info: TorrentInfo = None
def to_dict(self):
"""
转换为字典
"""
FILL_FUNC_BODY | return {
"meta_info": self.meta_info.to_dict() if self.meta_info else None,
"torrent_info": self.torrent_info.to_dict() if self.torrent_info else None,
"media_info": self.media_info.to_dict() if self.media_info else None
}
| """
转换为字典
"""
return {
"meta_info": self.meta_info.to_dict() if self.meta_info else None,
"torrent_info": self.torrent_info.to_dict() if self.torrent_info else None,
"media_info": self.media_info.to_dict() if self.media_info else None
}
| 21 | 107 | 92 | 199 | import re
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any, Tuple
from app.core.config import settings
from app.core.meta import MetaBase
from app.core.metainfo import MetaInfo
from app.schemas.types import MediaType
from app.utils.string import StringUtils
@dataclass
class Torrent... | import re
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any, Tuple
from app.core.config import settings
from app.core.meta import MetaBase
from app.core.metainfo import MetaInfo
from app.schemas.types import MediaType
from app.utils.string import StringUtils
@dataclass
class Torrent... |
36,861 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/context.py | 77,78 | 12,134 | from_dict | TorrentInfo | 81,87 | 78,87 | @dataclass
class TorrentInfo:
# 站点ID
site: int = None
# 站点名称
site_name: str = None
# 站点Cookie
site_cookie: str = None
# 站点UA
site_ua: str = None
# 站点是否使用代理
site_proxy: bool = False
# 站点优先级
site_order: int = 0
# 种子名称
title: str = None
# 种子副标题
description: s... | @dataclass
class TorrentInfo:
# 站点ID
site: int = None
# 站点名称
site_name: str = None
# 站点Cookie
site_cookie: str = None
# 站点UA
site_ua: str = None
# 站点是否使用代理
site_proxy: bool = False
# 站点优先级
site_order: int = 0
# 种子名称
title: str = None
# 种子副标题
description: s... | properties = self.__get_properties()
for key, value in data.items():
if key in properties:
continue
setattr(self, key, value)
| """
从字典中初始化
"""
properties = self.__get_properties()
for key, value in data.items():
if key in properties:
continue
setattr(self, key, value)
| 16 | 1,030 | 49 | 1,079 | import re
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any, Tuple
from app.core.config import settings
from app.core.meta import MetaBase
from app.core.metainfo import MetaInfo
from app.schemas.types import MediaType
from app.utils.string import StringUtils
@dataclass
class Torrent... | import re
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any, Tuple
from app.core.config import settings
from app.core.meta import MetaBase
from app.core.metainfo import MetaInfo
from app.schemas.types import MediaType
from app.utils.string import StringUtils
@dataclass
class Torrent... |
36,862 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/event.py | 22,23 | 9,110 | get_event | EventManager | 26,38 | 23,38 | class EventManager(metaclass=Singleton):
"""
事件管理器
"""
def __init__(self):
# 事件队列
self._eventQueue = Queue()
# 事件响应函数字典
self._handlers: Dict[str, Dict[str, Any]] = {}
# 已禁用的事件响应
self._disabled_handlers = []
def get_event(self):
FILL_FUNC_BODY def ... | class EventManager(metaclass=Singleton):
"""
事件管理器
"""
def __init__(self):
# 事件队列
self._eventQueue = Queue()
# 事件响应函数字典
self._handlers: Dict[str, Dict[str, Any]] = {}
# 已禁用的事件响应
self._disabled_handlers = []
def get_event(self):
"""
获取... | try:
event = self._eventQueue.get(block=True, timeout=1)
handlers = self._handlers.get(event.event_type) or {}
if handlers:
# 去除掉被禁用的事件响应
handlerList = [handler for handler in handlers.values()
if handler.__qualna... | """
获取事件
"""
try:
event = self._eventQueue.get(block=True, timeout=1)
handlers = self._handlers.get(event.event_type) or {}
if handlers:
# 去除掉被禁用的事件响应
handlerList = [handler for handler in handlers.values()
... | 37 | 833 | 140 | 973 | from queue import Queue, Empty
from typing import Dict, Any
from app.log import logger
from app.utils.singleton import Singleton
from app.schemas.types import EventType
class EventManager(metaclass=Singleton):
"""
事件管理器
"""
def __init__(self):
# 事件队列
self._eventQueue = Queue()
... | from queue import Queue, Empty
from typing import Dict, Any
from app.log import logger
from app.utils.singleton import Singleton
from app.schemas.types import EventType
class EventManager(metaclass=Singleton):
"""
事件管理器
"""
def __init__(self):
# 事件队列
self._eventQueue = Queue()
... |
36,863 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/meta/customization.py | 20,21 | 8,48 | match | CustomizationMatcher | 25,48 | 21,48 | class CustomizationMatcher(metaclass=Singleton):
"""
识别自定义占位符
"""
customization = None
custom_separator = None
def __init__(self):
self.systemconfig = SystemConfigOper()
self.customization = None
self.custom_separator = None
def match(self, title=None):
FILL_FUNC_BO... | class CustomizationMatcher(metaclass=Singleton):
"""
识别自定义占位符
"""
customization = None
custom_separator = None
def __init__(self):
self.systemconfig = SystemConfigOper()
self.customization = None
self.custom_separator = None
def match(self, title=None):
"""
... | if not title:
return ""
if not self.customization:
# 自定义占位符
customization = self.systemconfig.get(SystemConfigKey.Customization)
if not customization:
return ""
if isinstance(customization, str):
customization = ... | """
:param title: 资源标题或文件名
:return: 匹配结果
"""
if not title:
return ""
if not self.customization:
# 自定义占位符
customization = self.systemconfig.get(SystemConfigKey.Customization)
if not customization:
return ""
... | 81 | 132 | 348 | 480 | import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class CustomizationMatcher(metaclass=Singleton):
"""
识别自定义占位符
"""
customization = None
custom_separator = None
def __init__(self):
... | import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class CustomizationMatcher(metaclass=Singleton):
"""
识别自定义占位符
"""
customization = None
custom_separator = None
def __init__(self):
... |
36,866 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/meta/releasegroup.py | 85,86 | 8,109 | match | ReleaseGroupsMatcher | 91,109 | 86,109 | class ReleaseGroupsMatcher(metaclass=Singleton):
"""
识别制作组、字幕组
"""
__release_groups: str = None
# 内置组
RELEASE_GROUPS: dict = {
"0ff": ['FF(?:(?:A|WE)B|CD|E(?:DU|B)|TV)'],
"1pt": [],
"52pt": [],
"audiences": ['Audies', 'AD(?:Audio|E(?:|book)|Music|Web)'],
"... | class ReleaseGroupsMatcher(metaclass=Singleton):
"""
识别制作组、字幕组
"""
__release_groups: str = None
# 内置组
RELEASE_GROUPS: dict = {
"0ff": ['FF(?:(?:A|WE)B|CD|E(?:DU|B)|TV)'],
"1pt": [],
"52pt": [],
"audiences": ['Audies', 'AD(?:Audio|E(?:|book)|Music|Web)'],
"... | if not title:
return ""
if not groups:
# 自定义组
custom_release_groups = self.systemconfig.get(SystemConfigKey.CustomReleaseGroups)
if custom_release_groups:
custom_release_groups_str = '|'.join(custom_release_groups)
groups = ... | """
:param title: 资源标题或文件名
:param groups: 制作组/字幕组
:return: 匹配结果
"""
if not title:
return ""
if not groups:
# 自定义组
custom_release_groups = self.systemconfig.get(SystemConfigKey.CustomReleaseGroups)
if custom_release_g... | 53 | 1,396 | 258 | 1,654 | import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class ReleaseGroupsMatcher(metaclass=Singleton):
"""
识别制作组、字幕组
"""
__release_groups: str = None
# 内置组
RELEASE_GROUPS: dict = {
... | import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class ReleaseGroupsMatcher(metaclass=Singleton):
"""
识别制作组、字幕组
"""
__release_groups: str = None
# 内置组
RELEASE_GROUPS: dict = {
... |
36,867 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/meta/words.py | 17,18 | 12,136 | prepare | WordsMatcher | 24,71 | 18,71 | class WordsMatcher(metaclass=Singleton):
def __init__(self):
self.systemconfig = SystemConfigOper()
def prepare(self, title: str) -> Tuple[str, List[str]]:
FILL_FUNC_BODY @staticmethod
def __replace_regex(title: str, replaced: str, replace: str) -> Tuple[str, str, bool]:
"""
正则替... | class WordsMatcher(metaclass=Singleton):
def __init__(self):
self.systemconfig = SystemConfigOper()
def prepare(self, title: str) -> Tuple[str, List[str]]:
"""
预处理标题,支持三种格式
1:屏蔽词
2:被替换词 => 替换词
3:前定位词 <> 后定位词 >> 偏移量(EP)
"""
FILL_FUNC_BODY @staticmethod... | appley_words = []
# 读取自定义识别词
words: List[str] = self.systemconfig.get(SystemConfigKey.CustomIdentifiers) or []
for word in words:
if not word or word.startswith("#"):
continue
try:
if word.count(" => ") and word.count(" && ") and wo... | """
预处理标题,支持三种格式
1:屏蔽词
2:被替换词 => 替换词
3:前定位词 <> 后定位词 >> 偏移量(EP)
"""
appley_words = []
# 读取自定义识别词
words: List[str] = self.systemconfig.get(SystemConfigKey.CustomIdentifiers) or []
for word in words:
if not word or word.startswith(... | 167 | 1,201 | 679 | 1,880 | from typing import List, Tuple
import cn2an
import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.log import logger
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class WordsMatcher(metaclass=Singleton):
def __init__(self):
self.syste... | from typing import List, Tuple
import cn2an
import regex as re
from app.db.systemconfig_oper import SystemConfigOper
from app.log import logger
from app.schemas.types import SystemConfigKey
from app.utils.singleton import Singleton
class WordsMatcher(metaclass=Singleton):
def __init__(self):
self.syste... |
36,868 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/module.py | 61,62 | 10,100 | test | ModuleManager | 65,73 | 62,73 | class ModuleManager(metaclass=Singleton):
"""
模块管理器
"""
# 模块列表
_modules: dict = {}
# 运行态模块列表
_running_modules: dict = {}
def __init__(self):
self.load_modules()
def load_modules(self):
"""
加载所有模块
"""
# 扫描模块目录
modules = ModuleHelper.l... | class ModuleManager(metaclass=Singleton):
"""
模块管理器
"""
# 模块列表
_modules: dict = {}
# 运行态模块列表
_running_modules: dict = {}
def __init__(self):
self.load_modules()
def load_modules(self):
"""
加载所有模块
"""
# 扫描模块目录
modules = ModuleHelper.l... | if modleid not in self._running_modules:
return False, "模块未加载,请检查参数设置"
module = self._running_modules[modleid]
if hasattr(module, "test") \
and ObjectUtils.check_method(getattr(module, "test")):
return module.test()
return True, "模块不支持测试"
| """
测试模块
"""
if modleid not in self._running_modules:
return False, "模块未加载,请检查参数设置"
module = self._running_modules[modleid]
if hasattr(module, "test") \
and ObjectUtils.check_method(getattr(module, "test")):
return module.test()
... | 23 | 659 | 104 | 763 | from typing import Generator, Optional, Tuple
from app.core.config import settings
from app.helper.module import ModuleHelper
from app.log import logger
from app.utils.object import ObjectUtils
from app.utils.singleton import Singleton
class ModuleManager(metaclass=Singleton):
"""
模块管理器
"""
# 模块列表
... | from typing import Generator, Optional, Tuple
from app.core.config import settings
from app.helper.module import ModuleHelper
from app.log import logger
from app.utils.object import ObjectUtils
from app.utils.singleton import Singleton
class ModuleManager(metaclass=Singleton):
"""
模块管理器
"""
# 模块列表
... |
36,869 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/core/security.py | 106,107 | 1,198 | get_password_hash | 107,110 | 107,110 | import base64
import hashlib
import hmac
import json
import os
import traceback
from datetime import datetime, timedelta
from typing import Any, Union, Optional, Annotated
import jwt
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from fastapi import HTTPException, status, Depends, Header
from fastapi... | import base64
import hashlib
import hmac
import json
import os
import traceback
from datetime import datetime, timedelta
from typing import Any, Union, Optional, Annotated
import jwt
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from fastapi import HTTPException, status, Depends, Header
from fastapi... | return pwd_context.hash(password)
| return pwd_context.hash(password)
| 2 | 1,880 | 17 | 1,897 | import base64
import hashlib
import hmac
import json
import os
import traceback
from datetime import datetime, timedelta
from typing import Any, Union, Optional, Annotated
import jwt
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from fastapi import HTTPException, status, Depends, Header
from fastapi... | import base64
import hashlib
import hmac
import json
import os
import traceback
from datetime import datetime, timedelta
from typing import Any, Union, Optional, Annotated
import jwt
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from fastapi import HTTPException, status, Depends, Header
from fastapi... | |
36,870 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/downloadhistory_oper.py | 104,106 | 7,142 | get_last_by | DownloadHistoryOper | 109,117 | 106,117 | class DownloadHistoryOper(DbOper):
"""
下载历史管理
"""
def get_by_path(self, path: str) -> DownloadHistory:
"""
按路径查询下载记录
:param path: 数据key
"""
return DownloadHistory.get_by_path(self._db, path)
def get_by_hash(self, download_hash: str) -> DownloadHistory:
... | class DownloadHistoryOper(DbOper):
"""
下载历史管理
"""
def get_by_path(self, path: str) -> DownloadHistory:
"""
按路径查询下载记录
:param path: 数据key
"""
return DownloadHistory.get_by_path(self._db, path)
def get_by_hash(self, download_hash: str) -> DownloadHistory:
... | return DownloadHistory.get_last_by(db=self._db,
mtype=mtype,
title=title,
year=year,
season=season,
... | """
按类型、标题、年份、季集查询下载记录
"""
return DownloadHistory.get_last_by(db=self._db,
mtype=mtype,
title=title,
year=year,
seas... | 8 | 1,275 | 77 | 1,352 | from typing import List
from app.db import DbOper
from app.db.models.downloadhistory import DownloadHistory, DownloadFiles
class DownloadHistoryOper(DbOper):
"""
下载历史管理
"""
def get_by_path(self, path: str) -> DownloadHistory:
"""
按路径查询下载记录
:param path: 数据key
"""
... | from typing import List
from app.db import DbOper
from app.db.models.downloadhistory import DownloadHistory, DownloadFiles
class DownloadHistoryOper(DbOper):
"""
下载历史管理
"""
def get_by_path(self, path: str) -> DownloadHistory:
"""
按路径查询下载记录
:param path: 数据key
"""
... |
36,871 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/mediaserver_oper.py | 60,61 | 10,68 | get_item_id | MediaServerOper | 64,68 | 61,68 | class MediaServerOper(DbOper):
"""
媒体服务器数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self, **kwargs) -> bool:
"""
新增媒体服务器数据
"""
item = MediaServerItem(**kwargs)
if not item.get_by_itemid(self._db, kwargs.get("item_id"... | class MediaServerOper(DbOper):
"""
媒体服务器数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self, **kwargs) -> bool:
"""
新增媒体服务器数据
"""
item = MediaServerItem(**kwargs)
if not item.get_by_itemid(self._db, kwargs.get("item_id"... | item = self.exists(**kwargs)
if not item:
return None
return str(item.item_id)
| """
获取媒体服务器数据ID
"""
item = self.exists(**kwargs)
if not item:
return None
return str(item.item_id)
| 10 | 497 | 36 | 533 | import json
from typing import Optional
from sqlalchemy.orm import Session
from app.db import DbOper
from app.db.models.mediaserver import MediaServerItem
class MediaServerOper(DbOper):
"""
媒体服务器数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self, **kwarg... | import json
from typing import Optional
from sqlalchemy.orm import Session
from app.db import DbOper
from app.db.models.mediaserver import MediaServerItem
class MediaServerOper(DbOper):
"""
媒体服务器数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self, **kwarg... |
36,872 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/message_oper.py | 20,31 | 12,62 | add | MessageOper | 43,57 | 31,57 | class MessageOper(DbOper):
"""
消息数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self,
channel: MessageChannel = None,
mtype: NotificationType = None,
title: str = None,
text: str = None,
image: str =... | class MessageOper(DbOper):
"""
消息数据管理
"""
def __init__(self, db: Session = None):
super().__init__(db)
def add(self,
channel: MessageChannel = None,
mtype: NotificationType = None,
title: str = None,
text: str = None,
image: str =... | kwargs.update({
"channel": channel.value if channel else '',
"mtype": mtype.value if mtype else '',
"title": title,
"text": text,
"image": image,
"link": link,
"userid": userid,
"action": action,
"reg_tim... | """
新增媒体服务器数据
:param channel: 消息渠道
:param mtype: 消息类型
:param title: 标题
:param text: 文本内容
:param image: 图片
:param link: 链接
:param userid: 用户ID
:param action: 消息方向:0-接收息,1-发送消息
:param note: 附件json
"""
kwargs.update({
... | 37 | 324 | 161 | 485 | import json
import time
from typing import Optional, Union
from sqlalchemy.orm import Session
from app.db import DbOper
from app.db.models.message import Message
from app.schemas import MessageChannel, NotificationType
class MessageOper(DbOper):
"""
消息数据管理
"""
def __init__(self, db: Session = None)... | import json
import time
from typing import Optional, Union
from sqlalchemy.orm import Session
from app.db import DbOper
from app.db.models.message import Message
from app.schemas import MessageChannel, NotificationType
class MessageOper(DbOper):
"""
消息数据管理
"""
def __init__(self, db: Session = None)... |
36,873 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/models/downloadhistory.py | 176,179 | 156,212 | get_by_hash | DownloadFiles | 179,187 | 179,187 | class DownloadFiles(Base):
"""
下载文件记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 下载任务Hash
download_hash = Column(String, index=True)
# 下载器
downloader = Column(String)
# 完整路径
fullpath = Column(String, index=True)
# 保存路径
savepath = Column(Strin... | class DownloadFiles(Base):
"""
下载文件记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 下载任务Hash
download_hash = Column(String, index=True)
# 下载器
downloader = Column(String)
# 完整路径
fullpath = Column(String, index=True)
# 保存路径
savepath = Column(Strin... | if state:
result = db.query(DownloadFiles).filter(DownloadFiles.download_hash == download_hash,
DownloadFiles.state == state).all()
else:
result = db.query(DownloadFiles).filter(DownloadFiles.download_hash == download_hash).all(... | if state:
result = db.query(DownloadFiles).filter(DownloadFiles.download_hash == download_hash,
DownloadFiles.state == state).all()
else:
result = db.query(DownloadFiles).filter(DownloadFiles.download_hash == download_hash).all(... | 18 | 500 | 88 | 588 | import time
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nul... | import time
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nul... |
36,874 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/models/downloadhistory.py | 67,71 | 9,156 | get_last_by | DownloadHistory | 74,112 | 71,112 | class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nullable=False, index=True)
# 类型 电影/电视剧
type = Column(String, nullable=False)
# 标题
title = Column(String, nullable=False)
# 年份
year ... | class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nullable=False, index=True)
# 类型 电影/电视剧
type = Column(String, nullable=False)
# 标题
title = Column(String, nullable=False)
# 年份
year ... | result = None
if tmdbid and not season and not episode:
result = db.query(DownloadHistory).filter(DownloadHistory.tmdbid == tmdbid).order_by(
DownloadHistory.id.desc()).all()
if tmdbid and season and not episode:
result = db.query(DownloadHistory).filter(D... | """
据tmdbid、season、season_episode查询转移记录
"""
result = None
if tmdbid and not season and not episode:
result = db.query(DownloadHistory).filter(DownloadHistory.tmdbid == tmdbid).order_by(
DownloadHistory.id.desc()).all()
if tmdbid and season and ... | 121 | 1,124 | 504 | 1,628 | import time
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nul... | import time
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class DownloadHistory(Base):
"""
下载历史记录
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 保存路径
path = Column(String, nul... |
36,875 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/models/mediaserver.py | 63,66 | 10,69 | exists_by_title | MediaServerItem | 66,69 | 66,69 | class MediaServerItem(Base):
"""
媒体服务器媒体条目表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 服务器类型
server = Column(String)
# 媒体库ID
library = Column(String)
# ID
item_id = Column(String, index=True)
# 类型
item_type = Column(String)
# 标题
title... | class MediaServerItem(Base):
"""
媒体服务器媒体条目表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 服务器类型
server = Column(String)
# 媒体库ID
library = Column(String)
# ID
item_id = Column(String, index=True)
# 类型
item_type = Column(String)
# 标题
title... | return db.query(MediaServerItem).filter(MediaServerItem.title == title,
MediaServerItem.item_type == mtype,
MediaServerItem.year == str(year)).first()
| return db.query(MediaServerItem).filter(MediaServerItem.title == title,
MediaServerItem.item_type == mtype,
MediaServerItem.year == str(year)).first()
| 10 | 572 | 51 | 623 | from datetime import datetime
from typing import Optional
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class MediaServerItem(Base):
"""
媒体服务器媒体条目表
"""
id = Column(Integer, Sequence('id'), primary_key=True, in... | from datetime import datetime
from typing import Optional
from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, db_update, Base
class MediaServerItem(Base):
"""
媒体服务器媒体条目表
"""
id = Column(Integer, Sequence('id'), primary_key=True, in... |
36,876 | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot | /home/hieuvd/dung_repo/raw/stars_02/jxxghp_MoviePilot/MoviePilot/app/db/models/message.py | 33,36 | 7,40 | list_by_page | Message | 36,40 | 36,40 | class Message(Base):
"""
消息表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 消息渠道
channel = Column(String)
# 消息类型
mtype = Column(String)
# 标题
title = Column(String)
# 文本内容
text = Column(String)
# 图片
image = Column(String)
# 链接
link... | class Message(Base):
"""
消息表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 消息渠道
channel = Column(String)
# 消息类型
mtype = Column(String)
# 标题
title = Column(String)
# 文本内容
text = Column(String)
# 图片
image = Column(String)
# 链接
link... | result = db.query(Message).order_by(Message.reg_time.desc()).offset((page - 1) * count).limit(
count).all()
result.sort(key=lambda x: x.reg_time, reverse=False)
return list(result)
| result = db.query(Message).order_by(Message.reg_time.desc()).offset((page - 1) * count).limit(
count).all()
result.sort(key=lambda x: x.reg_time, reverse=False)
return list(result)
| 14 | 250 | 72 | 322 | from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, Base
class Message(Base):
"""
消息表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 消息渠道
channel = Column(String)
# 消息类型
mtype = Column(Strin... | from sqlalchemy import Column, Integer, String, Sequence
from sqlalchemy.orm import Session
from app.db import db_query, Base
class Message(Base):
"""
消息表
"""
id = Column(Integer, Sequence('id'), primary_key=True, index=True)
# 消息渠道
channel = Column(String)
# 消息类型
mtype = Column(Strin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.