code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def forward(
self,
input_features: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optiona... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`confi... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def NonMaxSuppression(boxes, scores, threshold):
r"""Non-Maximum Suppression
The algorithm begins by storing the highest-scoring bounding
box, and eliminating any box whose intersection-over-union (IoU)
with it is too great. The procedure repeats on the surviving
boxes, and so on until there are no ... | Non-Maximum Suppression
The algorithm begins by storing the highest-scoring bounding
box, and eliminating any box whose intersection-over-union (IoU)
with it is too great. The procedure repeats on the surviving
boxes, and so on until there are no boxes left.
The stored boxes are returned.
NB: T... | NonMaxSuppression | python | junfu1115/DANet | encoding/functions/customize.py | https://github.com/junfu1115/DANet/blob/master/encoding/functions/customize.py | MIT |
def pairwise_cosine(X, C, normalize=False):
r"""Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of feat... | Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of features,
:math:`K` is number is codewords, :m... | pairwise_cosine | python | junfu1115/DANet | encoding/functions/encoding.py | https://github.com/junfu1115/DANet/blob/master/encoding/functions/encoding.py | MIT |
def get_deepten(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""DeepTen model from the paper `"Deep TEN: Texture Encoding Network"
<https://arxiv.org/pdf/1612.02844v1.pdf>`_
Parameters
----------
dataset : str, default pascal_voc... | DeepTen model from the paper `"Deep TEN: Texture Encoding Network"
<https://arxiv.org/pdf/1612.02844v1.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, default False
Whether to load the pretra... | get_deepten | python | junfu1115/DANet | encoding/models/deepten.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/deepten.py | MIT |
def get_model_file(name, root=os.path.join('~', '.encoding', 'models')):
r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
---... | Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : str
Name of the model.
root : str, default '~/.enc... | get_model_file | python | junfu1115/DANet | encoding/models/model_store.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_store.py | MIT |
def purge(root=os.path.join('~', '.encoding', 'models')):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
... | Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
| purge | python | junfu1115/DANet | encoding/models/model_store.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_store.py | MIT |
def get_model(name, **kwargs):
"""Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameter... | Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
Returns
-------
Module... | get_model | python | junfu1115/DANet | encoding/models/model_zoo.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_zoo.py | MIT |
def resnet50(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(
... | Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet50 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet101(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
pretrained=False
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_st... | Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet101 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet152(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(
... | Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet152 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet50s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-50 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:... | Constructs a ResNetS-50 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet50s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def resnet101s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-101 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrain... | Constructs a ResNetS-101 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet101s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def resnet152s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-152 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrain... | Constructs a ResNetS-152 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet152s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def wideresnet38(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a WideResNet-38 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = WideResNet([3, 3, 6, 3, 1, 1], **kwargs)
if pretrained:
model.load_state_dict(torch.loa... | Constructs a WideResNet-38 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| wideresnet38 | python | junfu1115/DANet | encoding/models/backbone/wideresnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/wideresnet.py | MIT |
def wideresnet50(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a WideResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = WideResNet([3, 3, 6, 6, 3, 1], **kwargs)
if pretrained:
model.load_state_dict(torch.loa... | Constructs a WideResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| wideresnet50 | python | junfu1115/DANet | encoding/models/backbone/wideresnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/wideresnet.py | MIT |
def xception65(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = Xception65(**kwargs)
if pretrained:
model.load_state_dict(torch.load(get_model_file('xception65', root=root)))
retur... | Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| xception65 | python | junfu1115/DANet | encoding/models/backbone/xception.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/xception.py | MIT |
def get_atten(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""ATTEN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_atten.pdf>`_
Parameters
------... | ATTEN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_atten.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, def... | get_atten | python | junfu1115/DANet | encoding/models/sseg/atten.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/atten.py | MIT |
def parallel_forward(self, inputs, **kwargs):
"""Multi-GPU Mult-size Evaluation
Args:
inputs: list of Tensors
"""
inputs = [(input.unsqueeze(0).cuda(device),)
for input, device in zip(inputs, self.device_ids)]
replicas = self.replicate(self, self.de... | Multi-GPU Mult-size Evaluation
Args:
inputs: list of Tensors
| parallel_forward | python | junfu1115/DANet | encoding/models/sseg/base.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/base.py | MIT |
def get_danet(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""DANet model from the paper `"Dual Attention Network for Scene Segmentation"
<https://arxiv.org/abs/1809.02983.pdf>`
"""
acronyms = {
'pascal_voc': 'voc',
'pasca... | DANet model from the paper `"Dual Attention Network for Scene Segmentation"
<https://arxiv.org/abs/1809.02983.pdf>`
| get_danet | python | junfu1115/DANet | encoding/models/sseg/danet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/danet.py | MIT |
def get_dran(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""Scene Segmentation with Dual Relation-aware Attention Network
"""
acronyms = {
'pascal_voc': 'voc',
'pascal_aug': 'voc',
'pcontext': 'pcontext',
'a... | Scene Segmentation with Dual Relation-aware Attention Network
| get_dran | python | junfu1115/DANet | encoding/models/sseg/dran.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/dran.py | MIT |
def get_encnet(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
dataset : str, default pasca... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
backbone : str, default resnet50s
The backbone networ... | get_encnet | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrain... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet50_pcontext | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet101_coco(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained ... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet101_coco | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet101_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrai... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet101_pcontext | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained we... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet50_ade | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_fcfpn(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""FCFPN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcfpn.pdf>`_
Parameters
---------... | FCFPN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcfpn.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, def... | get_fcfpn | python | junfu1115/DANet | encoding/models/sseg/fcfpn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcfpn.py | MIT |
def get_fcn(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""FCN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf>`_
Parameters
----------
... | FCN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, default... | get_fcn | python | junfu1115/DANet | encoding/models/sseg/fcn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcn.py | MIT |
def get_fcn_resnest50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained ... | EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keepi... | get_fcn_resnest50_ade | python | junfu1115/DANet | encoding/models/sseg/fcn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcn.py | MIT |
def get_upernet(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""UperNet model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_upernet.pdf>`_
Parameters
--... | UperNet model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_upernet.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool,... | get_upernet | python | junfu1115/DANet | encoding/models/sseg/upernet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/upernet.py | MIT |
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
"""
m_batchsize, C, height, width = x.size()
proj_query = self.qu... |
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
| forward | python | junfu1115/DANet | encoding/nn/da_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/da_att.py | MIT |
def forward(self,x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X C X C
"""
m_batchsize, C, height, width = x.size()
proj_query = x.view(m_batchsi... |
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X C X C
| forward | python | junfu1115/DANet | encoding/nn/da_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/da_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,M)
returns :
out : compact position attention feature
attention map: (H*W)*M
"""
m_batchsize,C,width ,height = x.size()
m_batchs... |
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,M)
returns :
out : compact position attention feature
attention map: (H*W)*M
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,H,W)
returns :
out : compact channel attention feature
attention map: K*C
"""
m_batchsize,C,width ,height = x.size()
x_reshape =... |
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,H,W)
returns :
out : compact channel attention feature
attention map: K*C
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : low level feature(N,C,H,W) y:high level feature(N,C,H,W)
returns :
out : cross-level gating decoder feature
"""
low_lvl_feat = self.conv_low(x)
high_lvl_feat = upsample(y, low_lvl_feat.size... |
inputs :
x : low level feature(N,C,H,W) y:high level feature(N,C,H,W)
returns :
out : cross-level gating decoder feature
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def reset_dropblock(start_step, nr_steps, start_value, stop_value, m):
"""
Example:
from functools import partial
apply_drop_prob = partial(reset_dropblock, 0, epochs*iters_per_epoch, 0.0, 0.1)
net.apply(apply_drop_prob)
"""
if isinstance(m, DropBlock2D):
m.reset_steps(st... |
Example:
from functools import partial
apply_drop_prob = partial(reset_dropblock, 0, epochs*iters_per_epoch, 0.0, 0.1)
net.apply(apply_drop_prob)
| reset_dropblock | python | junfu1115/DANet | encoding/nn/dropblock.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dropblock.py | MIT |
def __init__(self, smoothing=0.1):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothing, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing |
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
| __init__ | python | junfu1115/DANet | encoding/nn/loss.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/loss.py | MIT |
def download(url, path=None, overwrite=False, sha1_hash=None):
"""Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
ove... | Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file ... | download | python | junfu1115/DANet | encoding/utils/files.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/files.py | MIT |
def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the fil... | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
| check_sha1 | python | junfu1115/DANet | encoding/utils/files.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/files.py | MIT |
def batch_pix_accuracy(output, target):
"""Batch Pixel Accuracy
Args:
predict: input 4D tensor
target: label 3D tensor
"""
_, predict = torch.max(output, 1)
predict = predict.cpu().numpy().astype('int64') + 1
target = target.cpu().numpy().astype('int64') + 1
pixel_labeled =... | Batch Pixel Accuracy
Args:
predict: input 4D tensor
target: label 3D tensor
| batch_pix_accuracy | python | junfu1115/DANet | encoding/utils/metrics.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/metrics.py | MIT |
def batch_intersection_union(output, target, nclass):
"""Batch Intersection of Union
Args:
predict: input 4D tensor
target: label 3D tensor
nclass: number of categories (int)
"""
_, predict = torch.max(output, 1)
mini = 1
maxi = nclass
nbins = nclass
predict = pre... | Batch Intersection of Union
Args:
predict: input 4D tensor
target: label 3D tensor
nclass: number of categories (int)
| batch_intersection_union | python | junfu1115/DANet | encoding/utils/metrics.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/metrics.py | MIT |
def get_mask_pallete(npimg, dataset='detail'):
"""Get image color pallete for visualizing masks"""
# recovery boundary
if dataset == 'pascal_voc':
npimg[npimg==21] = 255
# put colormap
out_img = Image.fromarray(npimg.squeeze().astype('uint8'))
if dataset == 'ade20k':
out_img.putp... | Get image color pallete for visualizing masks | get_mask_pallete | python | junfu1115/DANet | encoding/utils/pallete.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/pallete.py | MIT |
def update_bn_stats(
model: nn.Module, data_loader: Iterable[Any], num_iters: int = 200 # pyre-ignore
) -> None:
"""
Recompute and update the batch norm stats to make them more precise. During
training both BN stats and the weight are changing after every iteration, so
the running average can not p... |
Recompute and update the batch norm stats to make them more precise. During
training both BN stats and the weight are changing after every iteration, so
the running average can not precisely reflect the actual stats of the
current model.
In this function, the BN stats are recomputed with fixed weig... | update_bn_stats | python | junfu1115/DANet | encoding/utils/precise_bn.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/precise_bn.py | MIT |
def get_bn_modules(model: nn.Module) -> List[nn.Module]:
"""
Find all BatchNorm (BN) modules that are in training mode. See
fvcore.precise_bn.BN_MODULE_TYPES for a list of all modules that are
included in this search.
Args:
model (nn.Module): a model possibly containing BN modules.
Retur... |
Find all BatchNorm (BN) modules that are in training mode. See
fvcore.precise_bn.BN_MODULE_TYPES for a list of all modules that are
included in this search.
Args:
model (nn.Module): a model possibly containing BN modules.
Returns:
list[nn.Module]: all BN modules in the model.
| get_bn_modules | python | junfu1115/DANet | encoding/utils/precise_bn.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/precise_bn.py | MIT |
def get_selabel_vector(target, nclass):
r"""Get SE-Loss Label in a batch
Args:
predict: input 4D tensor
target: label 3D tensor (BxHxW)
nclass: number of categories (int)
Output:
2D tensor (BxnClass)
"""
batch = target.size(0)
tvect = torch.zeros(batch, nclass)
... | Get SE-Loss Label in a batch
Args:
predict: input 4D tensor
target: label 3D tensor (BxHxW)
nclass: number of categories (int)
Output:
2D tensor (BxnClass)
| get_selabel_vector | python | junfu1115/DANet | encoding/utils/train_helper.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/train_helper.py | MIT |
def filepath_enumerate(paths):
"""Enumerate the file paths of all subfiles of the list of paths"""
out = []
for path in paths:
if os.path.isfile(path):
out.append(path)
else:
for root, dirs, files in os.walk(path):
for name in files:
... | Enumerate the file paths of all subfiles of the list of paths | filepath_enumerate | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def _print_summary_map(strm, result_map, ftype):
"""Print summary of certain result map."""
if len(result_map) == 0:
return 0
npass = len([x for k, x in result_map.items() if len(x) == 0])
strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), ftype))... | Print summary of certain result map. | _print_summary_map | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def get_header_guard_dmlc(filename):
"""Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_I... | Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
| get_header_guard_dmlc | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def __init__(self, caption_track: Dict):
"""Construct a :class:`Caption <Caption>`.
:param dict caption_track:
Caption track data extracted from ``watch_html``.
"""
self.url = caption_track.get("baseUrl")
# Certain videos have runs instead of simpleText
# t... | Construct a :class:`Caption <Caption>`.
:param dict caption_track:
Caption track data extracted from ``watch_html``.
| __init__ | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def json_captions(self) -> dict:
"""Download and parse the json caption tracks."""
json_captions_url = self.url.replace('fmt=srv3','fmt=json3')
text = request.get(json_captions_url)
parsed = json.loads(text)
assert parsed['wireMagic'] == 'pb3', 'Unexpected captions format'
... | Download and parse the json caption tracks. | json_captions | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def float_to_srt_time_format(d: float) -> str:
"""Convert decimal durations into proper srt format.
:rtype: str
:returns:
SubRip Subtitle (str) formatted time duration.
float_to_srt_time_format(3.89) -> '00:00:03,890'
"""
fraction, whole = math.modf(d)
... | Convert decimal durations into proper srt format.
:rtype: str
:returns:
SubRip Subtitle (str) formatted time duration.
float_to_srt_time_format(3.89) -> '00:00:03,890'
| float_to_srt_time_format | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def xml_caption_to_srt(self, xml_captions: str) -> str:
"""Convert xml caption tracks to "SubRip Subtitle (srt)".
:param str xml_captions:
XML formatted caption tracks.
"""
segments = []
root = ElementTree.fromstring(xml_captions)
for i, child in enumerate(li... | Convert xml caption tracks to "SubRip Subtitle (srt)".
:param str xml_captions:
XML formatted caption tracks.
| xml_caption_to_srt | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def download(
self,
title: str,
srt: bool = True,
output_path: Optional[str] = None,
filename_prefix: Optional[str] = None,
) -> str:
"""Write the media stream to disk.
:param title:
Output filename (stem only) for writing media file.
... | Write the media stream to disk.
:param title:
Output filename (stem only) for writing media file.
If one is not specified, the default filename is used.
:type title: str
:param srt:
Set to True to download srt, false to download xml. Defaults to True.
... | download | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def calculate_n(self, initial_n: list):
"""Converts n to the correct value to prevent throttling."""
if self.calculated_n:
return self.calculated_n
# First, update all instances of 'b' with the list(initial_n)
for i in range(len(self.throttling_array)):
if self.t... | Converts n to the correct value to prevent throttling. | calculate_n | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_signature(self, ciphered_signature: str) -> str:
"""Decipher the signature.
Taking the ciphered signature, applies the transform functions.
:param str ciphered_signature:
The ciphered signature sent in the ``player_config``.
:rtype: str
:returns:
... | Decipher the signature.
Taking the ciphered signature, applies the transform functions.
:param str ciphered_signature:
The ciphered signature sent in the ``player_config``.
:rtype: str
:returns:
Decrypted signature required to download the media content.
... | get_signature | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def parse_function(self, js_func: str) -> Tuple[str, int]:
"""Parse the Javascript transform function.
Break a JavaScript transform function down into a two element ``tuple``
containing the function name and some integer-based argument.
:param str js_func:
The JavaScript ve... | Parse the Javascript transform function.
Break a JavaScript transform function down into a two element ``tuple``
containing the function name and some integer-based argument.
:param str js_func:
The JavaScript version of the transform function.
:rtype: tuple
:return... | parse_function | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_initial_function_name(js: str) -> str:
"""Extract the name of the function responsible for computing the signature.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
Function name from regex match
"""
function_patterns = [
r"\b[cs]\s*&&... | Extract the name of the function responsible for computing the signature.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
Function name from regex match
| get_initial_function_name | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_plan(js: str) -> List[str]:
"""Extract the "transform plan".
The "transform plan" is the functions that the ciphered signature is
cycled through to obtain the actual signature.
:param str js:
The contents of the base.js asset file.
**Example**:
['DE.AJ(a,15)',
'... | Extract the "transform plan".
The "transform plan" is the functions that the ciphered signature is
cycled through to obtain the actual signature.
:param str js:
The contents of the base.js asset file.
**Example**:
['DE.AJ(a,15)',
'DE.VR(a,3)',
'DE.AJ(a,51)',
'DE.VR(a,3)',
... | get_transform_plan | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_object(js: str, var: str) -> List[str]:
"""Extract the "transform object".
The "transform object" contains the function definitions referenced in the
"transform plan". The ``var`` argument is the obfuscated variable name
which contains these functions, for example, given the function ... | Extract the "transform object".
The "transform object" contains the function definitions referenced in the
"transform plan". The ``var`` argument is the obfuscated variable name
which contains these functions, for example, given the function call
``DE.AJ(a,15)`` returned by the transform plan, "DE" wou... | get_transform_object | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_map(js: str, var: str) -> Dict:
"""Build a transform function lookup.
Build a lookup table of obfuscated JavaScript function names to the
Python equivalents.
:param str js:
The contents of the base.js asset file.
:param str var:
The obfuscated variable name that s... | Build a transform function lookup.
Build a lookup table of obfuscated JavaScript function names to the
Python equivalents.
:param str js:
The contents of the base.js asset file.
:param str var:
The obfuscated variable name that stores an object with all functions
that descrambl... | get_transform_map | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_name(js: str) -> str:
"""Extract the name of the function that computes the throttling parameter.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
"""
funct... | Extract the name of the function that computes the throttling parameter.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
| get_throttling_function_name | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_code(js: str) -> str:
"""Extract the raw code for the throttling function.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
"""
# Begin by extracting the co... | Extract the raw code for the throttling function.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
| get_throttling_function_code | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_array(js: str) -> List[Any]:
"""Extract the "c" array.
:param str js:
The contents of the base.js asset file.
:returns:
The array of various integers, arrays, and functions.
"""
raw_code = get_throttling_function_code(js)
array_start = r",c=\["
a... | Extract the "c" array.
:param str js:
The contents of the base.js asset file.
:returns:
The array of various integers, arrays, and functions.
| get_throttling_function_array | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_plan(js: str):
"""Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to that functio... | Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to that function.
:param str js:
The conten... | get_throttling_plan | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def swap(arr: List, b: int):
"""Swap positions at b modulus the list length.
This function is equivalent to:
.. code-block:: javascript
function(a, b) { var c=a[0];a[0]=a[b%a.length];a[b]=c }
**Example**:
>>> swap([1, 2, 3, 4], 2)
[3, 2, 1, 4]
"""
r = b % len(arr)
return... | Swap positions at b modulus the list length.
This function is equivalent to:
.. code-block:: javascript
function(a, b) { var c=a[0];a[0]=a[b%a.length];a[b]=c }
**Example**:
>>> swap([1, 2, 3, 4], 2)
[3, 2, 1, 4]
| swap | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_reverse(arr: list):
"""Reverses the input list.
Needs to do an in-place reversal so that the passed list gets changed.
To accomplish this, we create a reversed copy, and then change each
indvidual element.
"""
reverse_copy = arr.copy()[::-1]
for i in range(len(reverse_copy)):... | Reverses the input list.
Needs to do an in-place reversal so that the passed list gets changed.
To accomplish this, we create a reversed copy, and then change each
indvidual element.
| throttling_reverse | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_unshift(d: list, e: int):
"""Rotates the elements of the list to the right.
In the javascript, the operation is as follows:
for(e=(e%d.length+d.length)%d.length;e--;)d.unshift(d.pop())
"""
e = throttling_mod_func(d, e)
new_arr = d[-e:] + d[:-e]
d.clear()
for el in new_arr... | Rotates the elements of the list to the right.
In the javascript, the operation is as follows:
for(e=(e%d.length+d.length)%d.length;e--;)d.unshift(d.pop())
| throttling_unshift | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_cipher_function(d: list, e: str):
"""This ciphers d with e to generate a new list.
In the javascript, the operation is as follows:
var h = [A-Za-z0-9-_], f = 96; // simplified from switch-case loop
d.forEach(
function(l,m,n){
this.push(
n[m]=h[
... | This ciphers d with e to generate a new list.
In the javascript, the operation is as follows:
var h = [A-Za-z0-9-_], f = 96; // simplified from switch-case loop
d.forEach(
function(l,m,n){
this.push(
n[m]=h[
(h.indexOf(l)-h.indexOf(this[m])+m-32+f--)... | throttling_cipher_function | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_nested_splice(d: list, e: int):
"""Nested splice function in throttling js.
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(
0,
1,
d.splice(
e,
1,
... | Nested splice function in throttling js.
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(
0,
1,
d.splice(
e,
1,
d[0]
)[0]
)
}
... | throttling_nested_splice | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_prepend(d: list, e: int):
"""
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(-e).reverse().forEach(
function(f){
d.unshift(f)
}
)
}
Effectively, this moves the ... |
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(-e).reverse().forEach(
function(f){
d.unshift(f)
}
)
}
Effectively, this moves the last e elements of d to the beginning.
| throttling_prepend | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_swap(d: list, e: int):
"""Swap positions of the 0'th and e'th elements in-place."""
e = throttling_mod_func(d, e)
f = d[0]
d[0] = d[e]
d[e] = f | Swap positions of the 0'th and e'th elements in-place. | throttling_swap | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def map_functions(js_func: str) -> Callable:
"""For a given JavaScript transform function, return the Python equivalent.
:param str js_func:
The JavaScript version of the transform function.
"""
mapper = (
# function(a){a.reverse()}
(r"{\w\.reverse\(\)}", reverse),
# fun... | For a given JavaScript transform function, return the Python equivalent.
:param str js_func:
The JavaScript version of the transform function.
| map_functions | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def main():
"""Command line application to download youtube videos."""
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(description=main.__doc__)
args = _parse_args(parser)
if args.verbose:
log_filename = None
if args.logfile:
log_filename = args.logfile
... | Command line application to download youtube videos. | main | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def build_playback_report(youtube: YouTube) -> None:
"""Serialize the request data to json for offline debugging.
:param YouTube youtube:
A YouTube object.
"""
ts = int(dt.datetime.utcnow().timestamp())
fp = os.path.join(os.getcwd(), f"yt-video-{youtube.video_id}-{ts}.json.gz")
js = yo... | Serialize the request data to json for offline debugging.
:param YouTube youtube:
A YouTube object.
| build_playback_report | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def _unique_name(base: str, subtype: str, media_type: str, target: str) -> str:
"""
Given a base name, the file format, and the target directory, will generate
a filename unique for that directory and file format.
:param str base:
The given base-name.
:param str subtype:
The filetype... |
Given a base name, the file format, and the target directory, will generate
a filename unique for that directory and file format.
:param str base:
The given base-name.
:param str subtype:
The filetype of the video which will be downloaded.
:param str media_type:
The media_ty... | _unique_name | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def ffmpeg_process(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""
Decides the correct video stream to download, then calls _ffmpeg_downloader.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param... |
Decides the correct video stream to download, then calls _ffmpeg_downloader.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
| ffmpeg_process | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def _ffmpeg_downloader(
audio_stream: Stream, video_stream: Stream, target: str
) -> None:
"""
Given a YouTube Stream object, finds the correct audio stream, downloads them both
giving them a unique name, them uses ffmpeg to create a new file with the audio
and video from the previously downloaded f... |
Given a YouTube Stream object, finds the correct audio stream, downloads them both
giving them a unique name, them uses ffmpeg to create a new file with the audio
and video from the previously downloaded files. Then deletes the original adaptive
streams, leaving the combination.
:param Stream audi... | _ffmpeg_downloader | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def download_by_itag(
youtube: YouTube, itag: int, target: Optional[str] = None
) -> None:
"""Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param int itag:
YouTube format identifier code.
:param str target:
Target directory for download
... | Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param int itag:
YouTube format identifier code.
:param str target:
Target directory for download
| download_by_itag | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def download_by_resolution(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory f... | Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
| download_by_resolution | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def download_highest_resolution_progressive(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""Start downloading the highest resolution progressive stream.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:p... | Start downloading the highest resolution progressive stream.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
| download_highest_resolution_progressive | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def download_caption(
youtube: YouTube, lang_code: Optional[str], target: Optional[str] = None
) -> None:
"""Download a caption for the YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str lang_code:
Language code desired for caption file.
Prints available c... | Download a caption for the YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str lang_code:
Language code desired for caption file.
Prints available codes if the value is None
or the desired code is not available.
:param str target:
Target directo... | download_caption | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def download_audio(
youtube: YouTube, filetype: str, target: Optional[str] = None
) -> None:
"""
Given a filetype, downloads the highest quality available audio stream for a
YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str filetype:
Desired file format t... |
Given a filetype, downloads the highest quality available audio stream for a
YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str filetype:
Desired file format to download.
:param str target:
Target directory for download
| download_audio | python | pytube/pytube | pytube/cli.py | https://github.com/pytube/pytube/blob/master/pytube/cli.py | Unlicense |
def __init__(self, caller: str, pattern: Union[str, Pattern]):
"""
:param str caller:
Calling function
:param str pattern:
Pattern that failed to match
"""
super().__init__(f"{caller}: could not find match for {pattern}")
self.caller = caller
... |
:param str caller:
Calling function
:param str pattern:
Pattern that failed to match
| __init__ | python | pytube/pytube | pytube/exceptions.py | https://github.com/pytube/pytube/blob/master/pytube/exceptions.py | Unlicense |
def publish_date(watch_html: str):
"""Extract publish date
:param str watch_html:
The html contents of the watch page.
:rtype: str
:returns:
Publish date of the video.
"""
try:
result = regex_search(
r"(?<=itemprop=\"datePublished\" content=\")\d{4}-\d{2}-\d{2... | Extract publish date
:param str watch_html:
The html contents of the watch page.
:rtype: str
:returns:
Publish date of the video.
| publish_date | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def recording_available(watch_html):
"""Check if live stream recording is available.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
"""
unavailable_strings = [
'This live stream recording is not a... | Check if live stream recording is available.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
| recording_available | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def is_private(watch_html):
"""Check if content is private.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
"""
private_strings = [
"This is a private video. Please sign in to verify that you may s... | Check if content is private.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
| is_private | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def is_age_restricted(watch_html: str) -> bool:
"""Check if content is age restricted.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is age restricted.
"""
try:
regex_search(r"og:restrictions:age", watch_htm... | Check if content is age restricted.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is age restricted.
| is_age_restricted | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def playability_status(watch_html: str) -> (str, str):
"""Return the playability status and status explanation of a video.
For example, a video may have a status of LOGIN_REQUIRED, and an explanation
of "This is a private video. Please sign in to verify that you may see it."
This explanation is what g... | Return the playability status and status explanation of a video.
For example, a video may have a status of LOGIN_REQUIRED, and an explanation
of "This is a private video. Please sign in to verify that you may see it."
This explanation is what gets incorporated into the media player overlay.
:param st... | playability_status | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def channel_name(url: str) -> str:
"""Extract the ``channel_name`` or ``channel_id`` from a YouTube url.
This function supports the following patterns:
- :samp:`https://youtube.com/c/{channel_name}/*`
- :samp:`https://youtube.com/channel/{channel_id}/*
- :samp:`https://youtube.com/u/{channel_name}... | Extract the ``channel_name`` or ``channel_id`` from a YouTube url.
This function supports the following patterns:
- :samp:`https://youtube.com/c/{channel_name}/*`
- :samp:`https://youtube.com/channel/{channel_id}/*
- :samp:`https://youtube.com/u/{channel_name}/*`
- :samp:`https://youtube.com/user/... | channel_name | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def video_info_url(video_id: str, watch_url: str) -> str:
"""Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str watch_url:
A YouTube watch url.
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
... | Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str watch_url:
A YouTube watch url.
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
| video_info_url | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def video_info_url_age_restricted(video_id: str, embed_html: str) -> str:
"""Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str embed_html:
The html contents of the embed page (for age restricted videos).
:rtype: str
:returns:
:samp:`ht... | Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str embed_html:
The html contents of the embed page (for age restricted videos).
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
| video_info_url_age_restricted | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def js_url(html: str) -> str:
"""Get the base JavaScript url.
Construct the base JavaScript url, which contains the decipher
"transforms".
:param str html:
The html contents of the watch page.
"""
try:
base_js = get_ytplayer_config(html)['assets']['js']
except (KeyError, Re... | Get the base JavaScript url.
Construct the base JavaScript url, which contains the decipher
"transforms".
:param str html:
The html contents of the watch page.
| js_url | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def mime_type_codec(mime_type_codec: str) -> Tuple[str, List[str]]:
"""Parse the type data.
Breaks up the data in the ``type`` key of the manifest, which contains the
mime type and codecs serialized together, and splits them into separate
elements.
**Example**:
mime_type_codec('audio/webm; co... | Parse the type data.
Breaks up the data in the ``type`` key of the manifest, which contains the
mime type and codecs serialized together, and splits them into separate
elements.
**Example**:
mime_type_codec('audio/webm; codecs="opus"') -> ('audio/webm', ['opus'])
:param str mime_type_codec:
... | mime_type_codec | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def get_ytplayer_js(html: str) -> Any:
"""Get the YouTube player base JavaScript path.
:param str html
The html contents of the watch page.
:rtype: str
:returns:
Path to YouTube's base.js file.
"""
js_url_patterns = [
r"(/s/player/[\w\d]+/[\w\d_/.]+/base\.js)"
]
... | Get the YouTube player base JavaScript path.
:param str html
The html contents of the watch page.
:rtype: str
:returns:
Path to YouTube's base.js file.
| get_ytplayer_js | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def get_ytplayer_config(html: str) -> Any:
"""Get the YouTube player configuration data from the watch html.
Extract the ``ytplayer_config``, which is json data embedded within the
watch html and serves as the primary source of obtaining the stream
manifest data.
:param str html:
The html ... | Get the YouTube player configuration data from the watch html.
Extract the ``ytplayer_config``, which is json data embedded within the
watch html and serves as the primary source of obtaining the stream
manifest data.
:param str html:
The html contents of the watch page.
:rtype: str
:r... | get_ytplayer_config | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def get_ytcfg(html: str) -> str:
"""Get the entirety of the ytcfg object.
This is built over multiple pieces, so we have to find all matches and
combine the dicts together.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html contain... | Get the entirety of the ytcfg object.
This is built over multiple pieces, so we have to find all matches and
combine the dicts together.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html containing the encoded manifest data.
| get_ytcfg | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def apply_signature(stream_manifest: Dict, vid_info: Dict, js: str) -> None:
"""Apply the decrypted signature to the stream manifest.
:param dict stream_manifest:
Details of the media streams available.
:param str js:
The contents of the base.js asset file.
"""
cipher = Cipher(js=j... | Apply the decrypted signature to the stream manifest.
:param dict stream_manifest:
Details of the media streams available.
:param str js:
The contents of the base.js asset file.
| apply_signature | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def apply_descrambler(stream_data: Dict) -> None:
"""Apply various in-place transforms to YouTube's media stream data.
Creates a ``list`` of dictionaries by string splitting on commas, then
taking each list item, parsing it as a query string, converting it to a
``dict`` and unquoting the value.
:p... | Apply various in-place transforms to YouTube's media stream data.
Creates a ``list`` of dictionaries by string splitting on commas, then
taking each list item, parsing it as a query string, converting it to a
``dict`` and unquoting the value.
:param dict stream_data:
Dictionary containing quer... | apply_descrambler | python | pytube/pytube | pytube/extract.py | https://github.com/pytube/pytube/blob/master/pytube/extract.py | Unlicense |
def __init__(self, generator):
"""Construct a :class:`DeferredGeneratorList <DeferredGeneratorList>`.
:param generator generator:
The deferrable generator to create a wrapper for.
:param func func:
(Optional) A function to call on the generator items to produce the list.... | Construct a :class:`DeferredGeneratorList <DeferredGeneratorList>`.
:param generator generator:
The deferrable generator to create a wrapper for.
:param func func:
(Optional) A function to call on the generator items to produce the list.
| __init__ | python | pytube/pytube | pytube/helpers.py | https://github.com/pytube/pytube/blob/master/pytube/helpers.py | Unlicense |
def __getitem__(self, key) -> Any:
"""Only generate items as they're asked for."""
# We only allow querying with indexes.
if not isinstance(key, (int, slice)):
raise TypeError('Key must be either a slice or int.')
# Convert int keys to slice
key_slice = key
i... | Only generate items as they're asked for. | __getitem__ | python | pytube/pytube | pytube/helpers.py | https://github.com/pytube/pytube/blob/master/pytube/helpers.py | Unlicense |
def __iter__(self):
"""Custom iterator for dynamically generated list."""
iter_index = 0
while True:
try:
curr_item = self[iter_index]
except IndexError:
return
else:
yield curr_item
iter_index +=... | Custom iterator for dynamically generated list. | __iter__ | python | pytube/pytube | pytube/helpers.py | https://github.com/pytube/pytube/blob/master/pytube/helpers.py | Unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.