index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28,042 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/randomwalks/ppo_randomwalks.py | 55,56 | 1,78 | main | 56,72 | 56,72 | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
PPOConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=TrainConfig(
seq_length=10,
e... | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
PPOConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=TrainConfig(
seq_length=10,
e... | config = TRLConfig.update(default_config, hparams)
metric_fn, prompts, *_ = generate_random_walks(seed=config.train.seed)
trlx.train(
# An "optimality" reward function is used, with scores in [0,1]
# depending on how close the path is to the shortest possible path.
reward_fn=lambda ... | config = TRLConfig.update(default_config, hparams)
metric_fn, prompts, *_ = generate_random_walks(seed=config.train.seed)
trlx.train(
# An "optimality" reward function is used, with scores in [0,1]
# depending on how close the path is to the shortest possible path.
reward_fn=lambda ... | 61 | 655 | 206 | 861 | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
PPOConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=TrainConfig(
seq_length=10,
e... | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
PPOConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=TrainConfig(
seq_length=10,
e... | |
28,043 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/randomwalks/rft_randomwalks.py | 46,47 | 1,65 | main | 47,59 | 47,59 | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.trainer.accelerate_rft_trainer import RFTConfig
default_config = TRLConfig(
train=Tr... | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.trainer.accelerate_rft_trainer import RFTConfig
default_config = TRLConfig(
train=Tr... | config = TRLConfig.update(default_config, hparams)
metric_fn, prompts, *_ = generate_random_walks(seed=config.train.seed)
trlx.train(
reward_fn=lambda samples, **kwargs: metric_fn(samples)["optimality"],
prompts=prompts,
eval_prompts=prompts,
metric_fn=lambda samples, **kwar... | config = TRLConfig.update(default_config, hparams)
metric_fn, prompts, *_ = generate_random_walks(seed=config.train.seed)
trlx.train(
reward_fn=lambda samples, **kwargs: metric_fn(samples)["optimality"],
prompts=prompts,
eval_prompts=prompts,
metric_fn=lambda samples, **kwar... | 22 | 597 | 140 | 737 | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.trainer.accelerate_rft_trainer import RFTConfig
default_config = TRLConfig(
train=Tr... | import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.trainer.accelerate_rft_trainer import RFTConfig
default_config = TRLConfig(
train=Tr... | |
28,044 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/rft_sentiments.py | 61,62 | 1,97 | main | 62,94 | 62,94 | # This script trains a model to output positive reviews
# using rejection finetuning with a sentiment classifier reward function.
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import ... | # This script trains a model to output positive reviews
# using rejection finetuning with a sentiment classifier reward function.
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import ... | config = TRLConfig.update(default_config, hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-imdb",
top_k=2,
truncation=True,
b... | config = TRLConfig.update(default_config, hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-imdb",
top_k=2,
truncation=True,
b... | 72 | 673 | 340 | 1,013 | # This script trains a model to output positive reviews
# using rejection finetuning with a sentiment classifier reward function.
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import ... | # This script trains a model to output positive reviews
# using rejection finetuning with a sentiment classifier reward function.
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import ... | |
28,045 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/sft_sentiments.py | 18,19 | 1,51 | main | 19,48 | 19,48 | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's o... | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's o... | # Merge sweep config with default config if given
config = TRLConfig.update(default_sft_config().to_dict(), hparams)
imdb = load_dataset("imdb", split="train+test")
# Finetune on only positive reviews
imdb = imdb.filter(lambda sample: sample["label"] == 1)
sentiment_fn = pipeline(
"sen... | # Merge sweep config with default config if given
config = TRLConfig.update(default_sft_config().to_dict(), hparams)
imdb = load_dataset("imdb", split="train+test")
# Finetune on only positive reviews
imdb = imdb.filter(lambda sample: sample["label"] == 1)
sentiment_fn = pipeline(
"sen... | 78 | 182 | 351 | 533 | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's o... | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's o... | |
28,047 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 70,72 | 37,75 | from_dict | ModelConfig | 72,75 | 72,75 | @dataclass
class ModelConfig:
"""
Config for a model.
:param model_path: Path or name of the model (local or on huggingface hub)
:type model_path: str
:param model_arch_type: Type of model architecture. Either "causal" or "seq2seq"
:type model_arch_type: str
:param num_layers_unfrozen: Nu... | @dataclass
class ModelConfig:
"""
Config for a model.
:param model_path: Path or name of the model (local or on huggingface hub)
:type model_path: str
:param model_arch_type: Type of model architecture. Either "causal" or "seq2seq"
:type model_arch_type: str
:param num_layers_unfrozen: Nu... | return cls(**config)
| return cls(**config)
| 2 | 445 | 14 | 459 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,048 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 115,117 | 100,120 | from_dict | OptimizerConfig | 117,120 | 117,120 | @dataclass
class OptimizerConfig:
"""
Config for an optimizer.
:param name: Name of the optimizer
:type name: str
:param kwargs: Keyword arguments for the optimizer (e.g. lr, betas, eps, weight_decay)
:type kwargs: Dict[str, Any]
"""
name: str
kwargs: Dict[str, Any] = field(defaul... | @dataclass
class OptimizerConfig:
"""
Config for an optimizer.
:param name: Name of the optimizer
:type name: str
:param kwargs: Keyword arguments for the optimizer (e.g. lr, betas, eps, weight_decay)
:type kwargs: Dict[str, Any]
"""
name: str
kwargs: Dict[str, Any] = field(defaul... | return cls(**config)
| return cls(**config)
| 2 | 157 | 14 | 171 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,049 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 135,137 | 120,140 | from_dict | SchedulerConfig | 137,140 | 137,140 | @dataclass
class SchedulerConfig:
"""
Config for a learning rate scheduler.
:param name: Name of the scheduler
:type name: str
:param kwargs: Keyword arguments for the scheduler instance (e.g. warmup_steps, T_max)
:type kwargs: Dict[str, Any]
"""
name: str
kwargs: Dict[str, Any] =... | @dataclass
class SchedulerConfig:
"""
Config for a learning rate scheduler.
:param name: Name of the scheduler
:type name: str
:param kwargs: Keyword arguments for the scheduler instance (e.g. warmup_steps, T_max)
:type kwargs: Dict[str, Any]
"""
name: str
kwargs: Dict[str, Any] =... | return cls(**config)
| return cls(**config)
| 2 | 156 | 14 | 170 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,050 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 303,305 | 239,336 | update | TRLConfig | 305,331 | 305,331 | @dataclass
class TRLConfig:
"""
Top level config for trlX. Loads configs and can be converted to dictionary.
"""
method: MethodConfig
model: ModelConfig
optimizer: OptimizerConfig
scheduler: SchedulerConfig
tokenizer: TokenizerConfig
train: TrainConfig
@classmethod
def load... | @dataclass
class TRLConfig:
"""
Top level config for trlX. Loads configs and can be converted to dictionary.
"""
method: MethodConfig
model: ModelConfig
optimizer: OptimizerConfig
scheduler: SchedulerConfig
tokenizer: TokenizerConfig
train: TrainConfig
@classmethod
def load... | update = {}
# unflatten a string variable name into a nested dictionary
# key1.key2.key3: value -> {key1: {key2: {key3: value}}}
for name, value in config.items():
if isinstance(value, dict):
update[name] = value
else:
*layers, var ... | update = {}
# unflatten a string variable name into a nested dictionary
# key1.key2.key3: value -> {key1: {key2: {key3: value}}}
for name, value in config.items():
if isinstance(value, dict):
update[name] = value
else:
*layers, var ... | 94 | 691 | 274 | 965 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,051 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 95,97 | 75,100 | from_dict | TokenizerConfig | 97,100 | 97,100 | @dataclass
class TokenizerConfig:
"""
Config for a model.
:param tokenizer_path: Path or name of the tokenizer (local or on huggingface hub)
:type tokenizer_path: str
:param padding_side: Padding side
:type padding_path: str
:param truncation_side: Truncation side
:type truncation_sid... | @dataclass
class TokenizerConfig:
"""
Config for a model.
:param tokenizer_path: Path or name of the tokenizer (local or on huggingface hub)
:type tokenizer_path: str
:param padding_side: Padding side
:type padding_path: str
:param truncation_side: Truncation side
:type truncation_sid... | return cls(**config)
| return cls(**config)
| 2 | 199 | 14 | 213 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,052 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/configs.py | 234,236 | 140,239 | from_dict | TrainConfig | 236,239 | 236,239 | @dataclass
class TrainConfig:
"""
Config for train job on model.
:param total_steps: Total number of training steps
:type total_steps: int
:param seq_length: Number of tokens to use as context (max length for tokenizer)
:type seq_length: int
:param epochs: Total number of passes through d... | @dataclass
class TrainConfig:
"""
Config for train job on model.
:param total_steps: Total number of training steps
:type total_steps: int
:param seq_length: Number of tokens to use as context (max length for tokenizer)
:type seq_length: int
:param epochs: Total number of passes through d... | return cls(**config)
| return cls(**config)
| 2 | 924 | 14 | 938 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
import yaml
from trlx.data.method_configs import MethodConfig, get_method
def merge(base: Dict, update: Dict, updated: Set) -> Dict:
"Recursively updates a nested dictionary with new values"
... |
28,053 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/method_configs.py | 48,49 | 1,57 | get_method | 52,57 | 49,57 | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... | name = name.lower()
if name in _METHODS:
return _METHODS[name]
else:
raise Exception("Error: Trying to access a method that has not been registered")
| """
Return constructor for specified method config
"""
name = name.lower()
if name in _METHODS:
return _METHODS[name]
else:
raise Exception("Error: Trying to access a method that has not been registered")
| 22 | 331 | 54 | 385 | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... | |
28,054 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/data/method_configs.py | 43,45 | 31,48 | from_dict | MethodConfig | 45,48 | 45,48 | @dataclass
@register_method
class MethodConfig:
"""
Config for a certain RL method.
:param name: Name of the method
:type name: str
"""
name: str
@classmethod
def from_dict(cls, config: Dict[str, Any]):
FILL_FUNC_BODY | @dataclass
@register_method
class MethodConfig:
"""
Config for a certain RL method.
:param name: Name of the method
:type name: str
"""
name: str
@classmethod
def from_dict(cls, config: Dict[str, Any]):
FILL_FUNC_BODY | return cls(**config)
| return cls(**config)
| 2 | 90 | 14 | 104 | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... | import sys
from dataclasses import dataclass
from typing import Any, Dict
# specifies a dictionary of method configs
_METHODS: Dict[str, Any] = {} # registry
def register_method(name):
"""Decorator used register a method config
Args:
name: Name of the method
"""
def register_class(cls, name... |
28,055 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/pipeline/ppo_pipeline.py | 14,15 | 1,105 | ppo_collate_fn | 15,53 | 15,53 | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... | if padding_side == "left":
# Left padding of already left-padded queries
query_tensors = pad_sequence(
[elem.query_tensor.flip(0) for elem in elems],
padding_value=pad_token_id,
batch_first=True,
).flip(1)
elif padding_side == "right":
query_te... | if padding_side == "left":
# Left padding of already left-padded queries
query_tensors = pad_sequence(
[elem.query_tensor.flip(0) for elem in elems],
padding_value=pad_token_id,
batch_first=True,
).flip(1)
elif padding_side == "right":
query_te... | 93 | 649 | 393 | 1,042 | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... | |
28,056 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/pipeline/ppo_pipeline.py | 65,66 | 53,105 | push | PPORolloutStorage | 66,68 | 66,68 | class PPORolloutStorage(BaseRolloutStore):
"""
Rollout storage for training PPO
"""
def __init__(self, pad_token_id, padding_side):
super().__init__()
self.pad_token_id = pad_token_id
self.padding_side = padding_side
self.history: Iterable[PPORLElement] = [None]
de... | class PPORolloutStorage(BaseRolloutStore):
"""
Rollout storage for training PPO
"""
def __init__(self, pad_token_id, padding_side):
super().__init__()
self.pad_token_id = pad_token_id
self.padding_side = padding_side
self.history: Iterable[PPORLElement] = [None]
de... | self.history += exps
| self.history += exps
| 3 | 516 | 11 | 527 | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... | import json
import os
import time
from functools import partial
from typing import Iterable
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from trlx.data.ppo_types import PPORLBatch, PPORLElement
from trlx.pipeline import BaseRolloutStore
def ppo_collate_fn(padding_side: str, pa... |
28,058 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/trainer/accelerate_sft_trainer.py | 40,41 | 29,98 | get_arch | AccelerateSFTTrainer | 41,63 | 41,63 | @register_trainer
class AccelerateSFTTrainer(AccelerateRLTrainer):
def __init__(self, config: TRLConfig, **kwargs):
super().__init__(config, **kwargs)
self.generate_kwargs = dict(
config.method.gen_kwargs,
eos_token_id=self.tokenizer.eos_token_id,
pad_token_id=se... | @register_trainer
class AccelerateSFTTrainer(AccelerateRLTrainer):
def __init__(self, config: TRLConfig, **kwargs):
super().__init__(config, **kwargs)
self.generate_kwargs = dict(
config.method.gen_kwargs,
eos_token_id=self.tokenizer.eos_token_id,
pad_token_id=se... | from_fn = AutoModelForCausalLM.from_pretrained
if issubclass(type(config.model.model_path), PretrainedConfig):
from_fn = AutoModelForCausalLM.from_config
model = from_fn(config.model.model_path, **config.model.model_extra_configs)
if config.model.peft_config is not None:
... | from_fn = AutoModelForCausalLM.from_pretrained
if issubclass(type(config.model.model_path), PretrainedConfig):
from_fn = AutoModelForCausalLM.from_config
model = from_fn(config.model.model_path, **config.model.model_extra_configs)
if config.model.peft_config is not None:
... | 59 | 595 | 295 | 890 | from dataclasses import dataclass
from transformers import AutoModelForCausalLM, PretrainedConfig
from trlx.data.configs import TRLConfig
from trlx.data.method_configs import MethodConfig, register_method
from trlx.pipeline.offline_pipeline import (
DialogStore,
PromptPipeline,
tokenize_dialogue,
)
from t... | from dataclasses import dataclass
from transformers import AutoModelForCausalLM, PretrainedConfig
from trlx.data.configs import TRLConfig
from trlx.data.method_configs import MethodConfig, register_method
from trlx.pipeline.offline_pipeline import (
DialogStore,
PromptPipeline,
tokenize_dialogue,
)
from t... |
28,059 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/trlx.py | 15,27 | 1,144 | train | 71,144 | 27,144 | import os
import warnings
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from trlx.data.configs import TRLConfig
from trlx.data.default_configs import (
default_ilql_config,
default_ppo_config,
default_sft_config,
)
from trlx.utils import set_seed
from trlx.utils.loading import get_pipe... | import os
import warnings
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from trlx.data.configs import TRLConfig
from trlx.data.default_configs import (
default_ilql_config,
default_ppo_config,
default_sft_config,
)
from trlx.utils import set_seed
from trlx.utils.loading import get_pipe... | if config is None:
warnings.warn(
"Passing the `config` argument implicitly is depreciated, use or"
"adapt some from `trlx/data/default_configs.py` instead"
)
if reward_fn:
config = default_ppo_config()
elif rewards:
config = default_il... | """
Runs online, offline reinforcement training or supervised finetuning depending on provided arguments.
`reward_fn` and `prompts` are required for online training, `samples` and `rewards` are required for offline training.
Args:
model_path (`Optional[str]`):
Path to either hugging... | 206 | 1,022 | 937 | 1,959 | import os
import warnings
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from trlx.data.configs import TRLConfig
from trlx.data.default_configs import (
default_ilql_config,
default_ppo_config,
default_sft_config,
)
from trlx.utils import set_seed
from trlx.utils.loading import get_pipe... | import os
import warnings
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from trlx.data.configs import TRLConfig
from trlx.data.default_configs import (
default_ilql_config,
default_ppo_config,
default_sft_config,
)
from trlx.utils import set_seed
from trlx.utils.loading import get_pipe... | |
28,060 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/utils/loading.py | 31,32 | 1,51 | get_trainer | 35,42 | 32,42 | from typing import Callable, List
# Register load pipelines via module import
from trlx.pipeline import _DATAPIPELINE
from trlx.pipeline.offline_pipeline import PromptPipeline
# Register load trainers via module import
from trlx.trainer import _TRAINERS, register_trainer
from trlx.trainer.accelerate_ilql_trainer impo... | from typing import Callable, List
# Register load pipelines via module import
from trlx.pipeline import _DATAPIPELINE
from trlx.pipeline.offline_pipeline import PromptPipeline
# Register load trainers via module import
from trlx.trainer import _TRAINERS, register_trainer
from trlx.trainer.accelerate_ilql_trainer impo... | name = name.lower()
if name in _TRAINERS:
return _TRAINERS[name]
else:
raise Exception("Error: Trying to access a trainer that has not been registered")
| """
Return constructor for specified RL model trainer
"""
name = name.lower()
if name in _TRAINERS:
return _TRAINERS[name]
else:
raise Exception("Error: Trying to access a trainer that has not been registered")
| 22 | 547 | 61 | 608 | from typing import Callable, List
# Register load pipelines via module import
from trlx.pipeline import _DATAPIPELINE
from trlx.pipeline.offline_pipeline import PromptPipeline
# Register load trainers via module import
from trlx.trainer import _TRAINERS, register_trainer
from trlx.trainer.accelerate_ilql_trainer impo... | from typing import Callable, List
# Register load pipelines via module import
from trlx.pipeline import _DATAPIPELINE
from trlx.pipeline.offline_pipeline import PromptPipeline
# Register load trainers via module import
from trlx.trainer import _TRAINERS, register_trainer
from trlx.trainer.accelerate_ilql_trainer impo... | |
28,062 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/utils/logging.py | 290,291 | 278,302 | empty_fn | EmptyTqdm | 291,293 | 291,293 | class EmptyTqdm:
"""Dummy tqdm which doesn't do anything."""
def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
self._iterator = args[0] if args else None
def __iter__(self):
return iter(self._iterator)
def __getattr__(self, _):
"""Return empty function.""... | class EmptyTqdm:
"""Dummy tqdm which doesn't do anything."""
def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
self._iterator = args[0] if args else None
def __iter__(self):
return iter(self._iterator)
def __getattr__(self, _):
"""Return empty function.""... | return
| return
| 1 | 176 | 6 | 182 | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
28,063 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/utils/logging.py | 108,109 | 105,127 | log | MultiProcessAdapter | 115,122 | 109,122 | class MultiProcessAdapter(logging.LoggerAdapter):
"""A logger adapter for handling multi-process logging"""
def log(self, level, msg, *args, **kwargs):
FILL_FUNC_BODY def process(self, msg, kwargs):
this_rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
return ... | class MultiProcessAdapter(logging.LoggerAdapter):
"""A logger adapter for handling multi-process logging"""
def log(self, level, msg, *args, **kwargs):
"""
Consumes an additional kwarg called `ranks` to determine which processes should log.
NOTE: To specify all processes, pass in an emp... | # By default, silence all non-main processes
ranks = kwargs.pop("ranks", ["0"])
should_log = os.environ.get("RANK", "0") in ranks or len(ranks) == 0
if self.isEnabledFor(level) and should_log:
msg, kwargs = self.process(msg, kwargs)
self.logger._log(level, msg, ar... | """
Consumes an additional kwarg called `ranks` to determine which processes should log.
NOTE: To specify all processes, pass in an empty list `ranks=[]`
Default: ["0"], i.e. only the main process logs
"""
# By default, silence all non-main processes
ranks = kwar... | 34 | 184 | 118 | 302 | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
28,064 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/trlx/utils/logging.py | 312,313 | 305,322 | set_lock | _tqdm_cls | 313,317 | 313,317 | class _tqdm_cls:
def __call__(self, *args, **kwargs):
if _tqdm_active:
return tqdm_lib.tqdm(*args, **kwargs)
else:
return EmptyTqdm(*args, **kwargs)
def set_lock(self, *args, **kwargs):
FILL_FUNC_BODY def get_lock(self):
if _tqdm_active:
return tqd... | class _tqdm_cls:
def __call__(self, *args, **kwargs):
if _tqdm_active:
return tqdm_lib.tqdm(*args, **kwargs)
else:
return EmptyTqdm(*args, **kwargs)
def set_lock(self, *args, **kwargs):
FILL_FUNC_BODY def get_lock(self):
if _tqdm_active:
return tqd... | self._lock = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
| self._lock = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
| 8 | 133 | 44 | 177 | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2023 Optuna, Hugging Face, CarperAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
28,065 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/cache.py | 60,61 | 13,72 | clear | Cache | 67,72 | 61,72 | class Cache:
"""Cache IPC interface"""
def get(self, bucket, identifier):
"""Get a item from cache bucket"""
call_args = {
'bucket': bucket,
'identifier': identifier
}
return make_call('get', call_args, IPC_ENDPOINT_CACHE)
def add(self, bucket, ident... | class Cache:
"""Cache IPC interface"""
def get(self, bucket, identifier):
"""Get a item from cache bucket"""
call_args = {
'bucket': bucket,
'identifier': identifier
}
return make_call('get', call_args, IPC_ENDPOINT_CACHE)
def add(self, bucket, ident... | call_args = {
'buckets': buckets,
'clear_database': clear_database
}
make_call('clear', call_args, IPC_ENDPOINT_CACHE)
| """
Clear the cache
:param buckets: list of buckets to clear, if not specified clear all the cache
:param clear_database: if True clear also the database data
"""
call_args = {
'buckets': buckets,
'clear_database': clear_database
}
... | 11 | 546 | 58 | 604 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Cache IPC interface - allow access to the add-on service cache from an add-on "frontend" instance
SPDX-License-Identifier: MIT
See LICENSES/MI... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Cache IPC interface - allow access to the add-on service cache from an add-on "frontend" instance
SPDX-License-Identifier: MIT
See LICENSES/MI... |
28,066 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/cache_utils.py | 106,107 | 1,112 | deserialize_data | 107,112 | 107,112 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for cache
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from functo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for cache
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from functo... | try:
return pickle.loads(value)
except pickle.UnpicklingError as exc:
LOG.error('It was not possible to deserialize the cache data, try purge cache from expert settings menu')
raise CacheMiss from exc
| try:
return pickle.loads(value)
except pickle.UnpicklingError as exc:
LOG.error('It was not possible to deserialize the cache data, try purge cache from expert settings menu')
raise CacheMiss from exc
| 27 | 1,692 | 67 | 1,759 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for cache
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from functo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for cache
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from functo... | |
28,068 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/data_conversion.py | 67,68 | 1,74 | _conv_string_to_datetime | 68,74 | 68,74 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Data type conversion
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import datetime
import json
from... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Data type conversion
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import datetime
import json
from... | try:
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f')
except (TypeError, ImportError):
# Python bug https://bugs.python.org/issue27400
import time
return datetime.datetime(*(time.strptime(value, '%Y-%m-%d %H:%M:%S.%f')[0:6]))
| try:
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f')
except (TypeError, ImportError):
# Python bug https://bugs.python.org/issue27400
import time
return datetime.datetime(*(time.strptime(value, '%Y-%m-%d %H:%M:%S.%f')[0:6]))
| 18 | 580 | 118 | 698 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Data type conversion
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import datetime
import json
from... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Data type conversion
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import datetime
import json
from... | |
28,070 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/fileops.py | 74,75 | 1,199 | save_file_def | 81,84 | 75,84 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for file operations
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
import xml.etree.ElementTree as... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for file operations
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
import xml.etree.ElementTree as... | save_file(os.path.join(G.DATA_PATH, filename), content, mode)
| """
Saves the given content under given filename, in the default add-on data folder
:param filename: The filename
:param content: The content of the file
:param mode: optional mode options
"""
save_file(os.path.join(G.DATA_PATH, filename), content, mode)
| 4 | 1,806 | 29 | 1,835 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for file operations
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
import xml.etree.ElementTree as... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for file operations
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
import xml.etree.ElementTree as... | |
28,074 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/kodi_wrappers.py | 114,115 | 44,165 | getArt | ListItemW | 115,119 | 115,119 | class ListItemW(xbmcgui.ListItem):
"""
Wrapper for xbmcgui.ListItem to add support for Pickle serialisation and add some helper functions
('offscreen' will be True by default)
"""
def __init__(self, label='', label2='', path=''):
super().__init__(label, label2, path, True)
self.__di... | class ListItemW(xbmcgui.ListItem):
"""
Wrapper for xbmcgui.ListItem to add support for Pickle serialisation and add some helper functions
('offscreen' will be True by default)
"""
def __init__(self, label='', label2='', path=''):
super().__init__(label, label2, path, True)
self.__di... | if G.IS_SERVICE:
return self.__dict__['art'].get(key)
return super().getArt(key)
| if G.IS_SERVICE:
return self.__dict__['art'].get(key)
return super().getArt(key)
| 6 | 1,339 | 39 | 1,378 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT (original implementation module)
Wrappers of Kodi methods and objects
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from typing impo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT (original implementation module)
Wrappers of Kodi methods and objects
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from typing impo... |
28,076 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/misc_utils.py | 253,254 | 194,258 | __conv_to_list | CmpVersion | 255,258 | 254,258 | class CmpVersion:
"""Comparator for version numbers"""
def __init__(self, version):
self.__version = str(version or '')
self.__ver_list = (self.__version or '0').split('.')
def __str__(self):
return self.__version
def __repr__(self):
return self.__version
def __boo... | class CmpVersion:
"""Comparator for version numbers"""
def __init__(self, version):
self.__version = str(version or '')
self.__ver_list = (self.__version or '0').split('.')
def __str__(self):
return self.__version
def __repr__(self):
return self.__version
def __boo... | if isinstance(value, CmpVersion):
return list(value)
return str(value or '0').split('.')
| """Convert a string or number or CmpVersion object to a list of strings"""
if isinstance(value, CmpVersion):
return list(value)
return str(value or '0').split('.')
| 9 | 667 | 35 | 702 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Miscellaneous utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import operator
from urllib.parse import quote... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Miscellaneous utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import operator
from urllib.parse import quote... |
28,077 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/common/pathops.py | 49,50 | 1,84 | get_multiple_paths | 58,68 | 50,68 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for retrieving values from nested dicts
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
def get_path(path, ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for retrieving values from nested dicts
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
def get_path(path, ... | if not isinstance(search_space, (dict, list)):
return default
if isinstance(path[0], list):
return _branch(path, search_space, default)
current_value = search_space.get(path[0], default)
return (current_value
if len(path) == 1
else get_multiple_paths(path[1:], cur... | """Retrieve multiple values from a nested dict by following the path.
The path may branch into multiple paths at any point.
A branch point is a list of different keys to follow down the path.
Returns a nested dict structure with nested dicts for each branch point in
the path. This essentially reduce... | 28 | 840 | 114 | 954 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for retrieving values from nested dicts
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
def get_path(path, ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions for retrieving values from nested dicts
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
def get_path(path, ... | |
28,081 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/database/db_base.py | 45,46 | 12,73 | get_cursor | BaseDatabase | 50,52 | 46,52 | class BaseDatabase:
"""
Base class to handle various types of databases
"""
def __init__(self):
self.conn = None
self._initialize_connection()
def _initialize_connection(self):
"""
Checks database existence and performs first connection tests
"""
rais... | class BaseDatabase:
"""
Base class to handle various types of databases
"""
def __init__(self):
self.conn = None
self._initialize_connection()
def _initialize_connection(self):
"""
Checks database existence and performs first connection tests
"""
rais... | raise NotImplementedError
| """
Get an instance of standard cursor
:return: cursor
"""
raise NotImplementedError
| 2 | 455 | 11 | 466 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Common interface for all types of databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
class B... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Common interface for all types of databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
class B... |
28,086 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/database/db_create_mysql.py | 15,16 | 1,110 | create_database | 17,110 | 16,110 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new MySQL database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import mysql... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new MySQL database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import mysql... | db_name = config.pop('database', None)
LOG.debug('The MySQL database {} does not exist, creating a new one', db_name)
conn = mysql.connector.connect(**config)
cur = conn.cursor()
schema = ('CREATE DATABASE netflix_addon '
'CHARACTER SET utf8mb4 '
'COLLATE utf8mb4_unicode... | """Create a new database"""
db_name = config.pop('database', None)
LOG.debug('The MySQL database {} does not exist, creating a new one', db_name)
conn = mysql.connector.connect(**config)
cur = conn.cursor()
schema = ('CREATE DATABASE netflix_addon '
'CHARACTER SET utf8mb4 '
... | 367 | 153 | 1,506 | 1,659 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new MySQL database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import mysql... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new MySQL database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import mysql... | |
28,087 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/database/db_create_sqlite.py | 79,80 | 1,142 | _create_shared_database | 81,142 | 80,142 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new SQLite database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import sqli... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new SQLite database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import sqli... | conn = sql.connect(db_file_path)
cur = conn.cursor()
table = str('CREATE TABLE profiles ('
'ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'
'Guid TEXT NOT NULL UNIQUE,'
'SortOrder INTEGER NOT NULL);')
cur.execute(table)
table = str('CR... | """Create a new shared database"""
conn = sql.connect(db_file_path)
cur = conn.cursor()
table = str('CREATE TABLE profiles ('
'ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'
'Guid TEXT NOT NULL UNIQUE,'
'SortOrder INTEGER NOT NULL);')
... | 209 | 820 | 739 | 1,559 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new SQLite database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import sqli... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions to create a new SQLite database
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import sqli... | |
28,091 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/database/db_update.py | 43,44 | 1,98 | run_shared_db_updates | 45,98 | 44,98 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions for updating the databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.l... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions for updating the databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.l... | # The changes must be left in sequence to allow cascade operations on non-updated databases
if current_version < '0.2':
# Changes: added table 'watched_status_override'
# SQLite
import sqlite3 as sql
from resources.lib.database.db_base_sqlite import CONN_ISOLATION_LEVEL
... | """Perform database actions for a db version change"""
# The changes must be left in sequence to allow cascade operations on non-updated databases
if current_version < '0.2':
# Changes: added table 'watched_status_override'
# SQLite
import sqlite3 as sql
from resources.lib.... | 194 | 534 | 764 | 1,298 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions for updating the databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.l... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Functions for updating the databases
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.l... | |
28,092 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/database/db_utils.py | 83,84 | 1,115 | mysql_insert_or_update | 87,101 | 84,101 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Miscellaneous database utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
i... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Miscellaneous database utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
i... | columns[0:0] = id_columns
sets_columns = [f'@{col}' for col in columns]
sets = [f'{col} = %s' for col in sets_columns]
query_set = f'SET {", ".join(sets)};'
query_columns = ', '.join(columns)
values = ', '.join(sets_columns)
query_insert = f'INSERT INTO {table} ({query_columns}) VALUES ({val... | """
Create a MySQL insert or update query (required multi=True)
"""
columns[0:0] = id_columns
sets_columns = [f'@{col}' for col in columns]
sets = [f'{col} = %s' for col in sets_columns]
query_set = f'SET {", ".join(sets)};'
query_columns = ', '.join(columns)
values = ', '.join(sets_... | 76 | 1,138 | 237 | 1,375 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Miscellaneous database utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
i... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Miscellaneous database utility functions
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
i... | |
28,095 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/context_menu.py | 128,129 | 1,136 | _ctx_item | 130,136 | 129,136 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions to generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions to generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common ... | # Do not move the import to the top of the module header, see context_menu_utils.py
from resources.lib.kodi.context_menu_utils import CONTEXT_MENU_ACTIONS
label = CONTEXT_MENU_ACTIONS[template]['label']
if label_format:
label = label.format(label_format)
return label, common.run_plugin_actio... | """Create a context menu item based on the given template and videoid"""
# Do not move the import to the top of the module header, see context_menu_utils.py
from resources.lib.kodi.context_menu_utils import CONTEXT_MENU_ACTIONS
label = CONTEXT_MENU_ACTIONS[template]['label']
if label_format:
... | 31 | 1,908 | 131 | 2,039 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions to generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Helper functions to generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common ... | |
28,096 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/context_menu_utils.py | 20,21 | 1,93 | ctx_item_url | 22,28 | 21,28 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
i... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
i... | def ctx_url_builder(videoid, params):
"""Build a context menu item URL"""
return common.build_url(paths, videoid, params, mode=mode)
return ctx_url_builder
| """Return a function that builds an URL from a videoid for the predefined path"""
def ctx_url_builder(videoid, params):
"""Build a context menu item URL"""
return common.build_url(paths, videoid, params, mode=mode)
return ctx_url_builder
| 16 | 1,315 | 62 | 1,377 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
i... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for generating context menu items
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
i... | |
28,104 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/nfo.py | 57,59 | 17,95 | movie_prompt_dialog | NFOSettings | 60,62 | 59,62 | class NFOSettings:
def __init__(self, enforce=None):
"""
:param enforce: Used for export new episode, to force the nfo export status
"""
if enforce is None:
self._enabled = G.ADDON.getSettingBool('enable_nfo_export')
self._export_tvshow_id = G.ADDON.getSetting... | class NFOSettings:
def __init__(self, enforce=None):
"""
:param enforce: Used for export new episode, to force the nfo export status
"""
if enforce is None:
self._enabled = G.ADDON.getSettingBool('enable_nfo_export')
self._export_tvshow_id = G.ADDON.getSetting... | return self._enabled and self._export_movie_id == 2
| """Ask to user when export Movie NFO"""
return self._enabled and self._export_movie_id == 2
| 6 | 1,133 | 20 | 1,153 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Smeulf (original implementation module)
Functions for Kodi library NFO creation
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xml.etree.ElementTree as ET
fr... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Smeulf (original implementation module)
Functions for Kodi library NFO creation
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xml.etree.ElementTree as ET
fr... |
28,106 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/dialogs.py | 232,233 | 197,239 | is_cancelled | ProgressBarBG | 233,236 | 233,236 | class ProgressBarBG(xbmcgui.DialogProgressBG):
"""Context manager to handle a progress bar in background"""
# Keep the same arguments for all progress bar classes
def __init__(self, is_enabled, title, initial_value=None, max_value=None):
super().__init__()
self.is_enabled = is_enabled
... | class ProgressBarBG(xbmcgui.DialogProgressBG):
"""Context manager to handle a progress bar in background"""
# Keep the same arguments for all progress bar classes
def __init__(self, is_enabled, title, initial_value=None, max_value=None):
super().__init__()
self.is_enabled = is_enabled
... | # Not supported - only need to ensure consistency in dynamic class management
return False
| # Not supported - only need to ensure consistency in dynamic class management
return False
| 15 | 449 | 23 | 472 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various simple dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import xbmcgui
from resources.lib.globals ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various simple dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import xbmcgui
from resources.lib.globals ... |
28,107 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/dialogs.py | 188,189 | 159,197 | perform_step | ProgressDialog | 189,192 | 189,192 | class ProgressDialog(xbmcgui.DialogProgress):
"""Context manager to handle a progress dialog window"""
# Keep the same arguments for all progress bar classes
def __init__(self, is_enabled, title=None, initial_value=0, max_value=1):
super().__init__()
self.is_enabled = is_enabled
self... | class ProgressDialog(xbmcgui.DialogProgress):
"""Context manager to handle a progress dialog window"""
# Keep the same arguments for all progress bar classes
def __init__(self, is_enabled, title=None, initial_value=0, max_value=1):
super().__init__()
self.is_enabled = is_enabled
self... | self.value += 1
self._percent = int(self.value * 100 / self.max_value)
| self.value += 1
self._percent = int(self.value * 100 / self.max_value)
| 10 | 395 | 34 | 429 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various simple dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import xbmcgui
from resources.lib.globals ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various simple dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import xbmcgui
from resources.lib.globals ... |
28,110 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/xmldialog_parental.py | 61,62 | 26,126 | onClick | ParentalControl | 62,83 | 62,83 | class ParentalControl(xbmcgui.WindowXMLDialog):
"""
Dialog for parental control settings
"""
def __init__(self, *args, **kwargs):
# Keep pin option, there is still some reference in the netflix code
# self.current_pin = kwargs.get('pin')
self.data = kwargs['data']
self.ra... | class ParentalControl(xbmcgui.WindowXMLDialog):
"""
Dialog for parental control settings
"""
def __init__(self, *args, **kwargs):
# Keep pin option, there is still some reference in the netflix code
# self.current_pin = kwargs.get('pin')
self.data = kwargs['data']
self.ra... | if controlId == 10028: # Save and close dialog
# pin = self.getControl(10002).getText()
# # Validate pin length
# if not self._validate_pin(pin):
# return
import resources.lib.utils.api_requests as api
data = {'guid': self.data['profil... | if controlId == 10028: # Save and close dialog
# pin = self.getControl(10002).getText()
# # Validate pin length
# if not self._validate_pin(pin):
# return
import resources.lib.utils.api_requests as api
data = {'guid': self.data['profil... | 97 | 1,245 | 342 | 1,587 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
from resources.lib.globals import ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
from resources.lib.globals import ... |
28,111 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/xmldialog_profiles.py | 47,48 | 18,59 | onClick | Profiles | 48,56 | 48,56 | class Profiles(xbmcgui.WindowXMLDialog):
"""Dialog for profile selection"""
def __init__(self, *args, **kwargs):
self.ctrl_list = None
self.return_value = None
self.title = kwargs['title']
self.dir_items = kwargs['dir_items']
self.preselect_guid = kwargs.get('preselect_g... | class Profiles(xbmcgui.WindowXMLDialog):
"""Dialog for profile selection"""
def __init__(self, *args, **kwargs):
self.ctrl_list = None
self.return_value = None
self.title = kwargs['title']
self.dir_items = kwargs['dir_items']
self.preselect_guid = kwargs.get('preselect_g... | if controlId == 10001: # Save and close dialog
sel_list_item = self.ctrl_list.getSelectedItem()
# 'nf_guid' property is set to Listitems from _create_profile_item of dir_builder_items.py
self.return_value = sel_list_item.getProperty('nf_guid')
self.close()
... | if controlId == 10001: # Save and close dialog
sel_list_item = self.ctrl_list.getSelectedItem()
# 'nf_guid' property is set to Listitems from _create_profile_item of dir_builder_items.py
self.return_value = sel_list_item.getProperty('nf_guid')
self.close()
... | 35 | 418 | 132 | 550 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
ACTION_PREVIOUS_MENU = 10
ACTION_P... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
ACTION_PREVIOUS_MENU = 10
ACTION_P... |
28,112 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/xmldialog_ratingthumb.py | 36,37 | 19,71 | onInit | RatingThumb | 37,58 | 37,58 | class RatingThumb(xbmcgui.WindowXMLDialog):
"""Dialog for rating a tv show or movie"""
def __init__(self, *args, **kwargs):
self.videoid = kwargs['videoid']
self.track_id_jaw = kwargs['track_id_jaw']
self.title = kwargs.get('title', '--')
self.user_rating = kwargs.get('user_rati... | class RatingThumb(xbmcgui.WindowXMLDialog):
"""Dialog for rating a tv show or movie"""
def __init__(self, *args, **kwargs):
self.videoid = kwargs['videoid']
self.track_id_jaw = kwargs['track_id_jaw']
self.title = kwargs.get('title', '--')
self.user_rating = kwargs.get('user_rati... | self.getControl(10000).setLabel(self.title)
# Kodi does not allow to change button textures in runtime
# and you can not add nested controls via code,
# so the only alternative is to create double XML buttons
# and eliminate those that are not needed
focus_id = 10010
... | self.getControl(10000).setLabel(self.title)
# Kodi does not allow to change button textures in runtime
# and you can not add nested controls via code,
# so the only alternative is to create double XML buttons
# and eliminate those that are not needed
focus_id = 10010
... | 80 | 448 | 365 | 813 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
ACTION_PREVIOUS_MENU = 10
ACTION_P... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
XML based dialog
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmcgui
ACTION_PREVIOUS_MENU = 10
ACTION_P... |
28,113 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/xmldialogs.py | 28,29 | 1,145 | show_modal_dialog | 36,43 | 29,43 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... | # WARNING: doModal when invoked does not release the function immediately!
# it seems that doModal waiting for all window operations to be completed before return,
# for example the "Skip" dialog takes about 30 seconds to release the function (probably for the included animation)
# To be taken into acco... | """
Show a modal Dialog in the UI.
Pass kwargs minutes and/or seconds to have the dialog automatically
close after the specified time.
:return if exists return self.return_value value of dlg_class (if non_blocking=True return always None)
"""
# WARNING: doModal when invoked does not release... | 71 | 1,514 | 128 | 1,642 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... | |
28,114 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/kodi/ui/xmldialogs.py | 74,75 | 62,87 | onInit | Skip | 75,77 | 75,77 | class Skip(xbmcgui.WindowXMLDialog):
"""Dialog for skipping video parts (intro, recap, ...)"""
def __init__(self, *args, **kwargs):
self.seek_time = kwargs['seek_time']
self.label = kwargs['label']
self.action_exit_keys_id = [ACTION_PREVIOUS_MENU,
ACT... | class Skip(xbmcgui.WindowXMLDialog):
"""Dialog for skipping video parts (intro, recap, ...)"""
def __init__(self, *args, **kwargs):
self.seek_time = kwargs['seek_time']
self.label = kwargs['label']
self.action_exit_keys_id = [ACTION_PREVIOUS_MENU,
ACT... | self.getControl(6012).setLabel(self.label) # pylint: disable=no-member
| self.getControl(6012).setLabel(self.label) # pylint: disable=no-member
| 4 | 241 | 33 | 274 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
XML based dialogs
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import xbmcgui
from resources.lib.... |
28,120 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/navigation/keymaps.py | 101,102 | 1,121 | _is_library_ops_allowed | 103,118 | 102,118 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... | allow_lib_operations = True
if not G.ADDON.getSettingBool('lib_enabled'):
return False
is_lib_sync_with_mylist = (G.ADDON.getSettingBool('lib_sync_mylist') and
G.ADDON.getSettingInt('lib_auto_upd_mode') in [0, 2])
if is_lib_sync_with_mylist:
# If the synchr... | """Check if library operations are allowed"""
allow_lib_operations = True
if not G.ADDON.getSettingBool('lib_enabled'):
return False
is_lib_sync_with_mylist = (G.ADDON.getSettingBool('lib_sync_mylist') and
G.ADDON.getSettingInt('lib_auto_upd_mode') in [0, 2])
i... | 72 | 1,377 | 276 | 1,653 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... | |
28,121 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/navigation/keymaps.py | 72,74 | 43,93 | change_watched_status | KeymapsActionExecutor | 75,80 | 74,80 | class KeymapsActionExecutor:
"""Executes keymaps actions"""
def __init__(self, params):
LOG.debug('Initializing "KeymapsActionExecutor" with params: {}', params)
self.params = params
@allow_execution_decorator(check_lib=True, inject_videoid=True)
def lib_export(self, pathitems, videoid... | class KeymapsActionExecutor:
"""Executes keymaps actions"""
def __init__(self, params):
LOG.debug('Initializing "KeymapsActionExecutor" with params: {}', params)
self.params = params
@allow_execution_decorator(check_lib=True, inject_videoid=True)
def lib_export(self, pathitems, videoid... | if videoid.mediatype not in [common.VideoId.MOVIE, common.VideoId.EPISODE]:
return
if G.ADDON.getSettingBool('sync_watched_status'):
change_watched_status_locally(videoid)
| """Change the watched status of a video, only when sync of watched status with NF is enabled"""
if videoid.mediatype not in [common.VideoId.MOVIE, common.VideoId.EPISODE]:
return
if G.ADDON.getSettingBool('sync_watched_status'):
change_watched_status_locally(videoid)
| 10 | 737 | 76 | 813 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation handler for keyboard shortcut keys
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from functools import... |
28,126 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/run_service.py | 111,112 | 1,122 | run | 112,122 | 112,122 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... | # Initialize globals right away to avoid stale values from the last addon invocation.
# Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
# PR: https://github.com/xbmc/xbmc/pull/13814
G.init_globals(argv)
_set_service_status(G.SERVICE_STATUS_UPGRADE)
check_service_upg... | # Initialize globals right away to avoid stale values from the last addon invocation.
# Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
# PR: https://github.com/xbmc/xbmc/pull/13814
G.init_globals(argv)
_set_service_status(G.SERVICE_STATUS_UPGRADE)
check_service_upg... | 37 | 1,299 | 172 | 1,471 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... | |
28,127 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/run_service.py | 58,59 | 24,111 | start_services | NetflixService | 60,72 | 59,72 | class NetflixService:
"""Netflix addon service"""
HOST_ADDRESS = '127.0.0.1'
def __init__(self):
self.library_updater = None
self.nf_server_instance = None
self.nf_server_thread = None
def init_servers(self):
"""Initialize the HTTP server"""
try:
# I... | class NetflixService:
"""Netflix addon service"""
HOST_ADDRESS = '127.0.0.1'
def __init__(self):
self.library_updater = None
self.nf_server_instance = None
self.nf_server_thread = None
def init_servers(self):
"""Initialize the HTTP server"""
try:
# I... | from resources.lib.services.library_updater import LibraryUpdateService
self.nf_server_instance.server_activate()
self.nf_server_thread.start()
LOG.info('[NF_SERVER] Thread started')
self.library_updater = LibraryUpdateService()
# We reset the value in case of any event... | """Start the background services"""
from resources.lib.services.library_updater import LibraryUpdateService
self.nf_server_instance.server_activate()
self.nf_server_thread.start()
LOG.info('[NF_SERVER] Thread started')
self.library_updater = LibraryUpdateService()
... | 36 | 925 | 162 | 1,087 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Functions for starting the service
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import threading
from socket import gaierror
from resources.lib.common import select_port, WndHomeProps
f... |
28,131 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/http_server.py | 29,30 | 22,62 | do_GET | NetflixHttpRequestHandler | 30,40 | 30,40 | class NetflixHttpRequestHandler(BaseHTTPRequestHandler):
"""Handles and translates requests from IPC via HTTP"""
# pylint: disable=invalid-name
def do_HEAD(self):
"""Answers head requests with a success code"""
self.send_response(200)
def do_GET(self):
FILL_FUNC_BODY def do_POST(self... | class NetflixHttpRequestHandler(BaseHTTPRequestHandler):
"""Handles and translates requests from IPC via HTTP"""
# pylint: disable=invalid-name
def do_HEAD(self):
"""Answers head requests with a success code"""
self.send_response(200)
def do_GET(self):
FILL_FUNC_BODY def do_POST(self... | LOG.debug('HTTP Server: received GET request {}', self.path)
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
endpoint, func_name = parsed_url.path.rsplit('/', 1)
if endpoint == IPC_ENDPOINT_MSL:
handle_msl_request(self, func_name, None, params)
... | LOG.debug('HTTP Server: received GET request {}', self.path)
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
endpoint, func_name = parsed_url.path.rsplit('/', 1)
if endpoint == IPC_ENDPOINT_MSL:
handle_msl_request(self, func_name, None, params)
... | 31 | 407 | 141 | 548 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo (original implementation module)
HTTP Server for Netflix session, cache, proxy for InputStream Adaptive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo (original implementation module)
HTTP Server for Netflix session, cache, proxy for InputStream Adaptive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
... |
28,133 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/library_updater.py | 124,125 | 20,151 | check_awaiting_operations | LibraryUpdateService | 125,132 | 125,132 | class LibraryUpdateService(xbmc.Monitor):
"""
Checks if a library update is scheduled and triggers it
"""
def __init__(self):
super().__init__()
try:
self.enabled = (G.ADDON.getSettingBool('lib_enabled')
and G.ADDON.getSettingInt('lib_auto_upd_mode... | class LibraryUpdateService(xbmc.Monitor):
"""
Checks if a library update is scheduled and triggers it
"""
def __init__(self):
super().__init__()
try:
self.enabled = (G.ADDON.getSettingBool('lib_enabled')
and G.ADDON.getSettingInt('lib_auto_upd_mode... | if self.clean_awaiting:
LOG.debug('Kodi library clean requested (from awaiting)')
self.start_clean_kodi_library()
if self.scan_awaiting:
LOG.debug('Kodi library scan requested (from awaiting)')
self.start_update_kodi_library()
| if self.clean_awaiting:
LOG.debug('Kodi library clean requested (from awaiting)')
self.start_clean_kodi_library()
if self.scan_awaiting:
LOG.debug('Kodi library scan requested (from awaiting)')
self.start_update_kodi_library()
| 18 | 1,477 | 90 | 1,567 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Automatic updates of items exported to the Kodi library
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from datetime import d... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Automatic updates of items exported to the Kodi library
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from datetime import d... |
28,136 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/directorybuilder/dir_builder_utils.py | 21,23 | 1,64 | add_items_previous_next_page | 23,48 | 23,48 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for directory builder
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
im... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for directory builder
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
im... | if pathitems and perpetual_range_selector:
if 'previous_start' in perpetual_range_selector:
params = {'perpetual_range_start': perpetual_range_selector.get('previous_start'),
'sub_genre_id': sub_genre_id}
if path_params:
params.update(path_params... | if pathitems and perpetual_range_selector:
if 'previous_start' in perpetual_range_selector:
params = {'perpetual_range_start': perpetual_range_selector.get('previous_start'),
'sub_genre_id': sub_genre_id}
if path_params:
params.update(path_params... | 71 | 486 | 457 | 943 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for directory builder
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
im... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for directory builder
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import os
im... | |
28,139 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/msl/base_crypto.py | 35,36 | 20,142 | load_msl_data | MSLBaseCrypto | 36,41 | 36,41 | class MSLBaseCrypto:
"""
Common base class for MSL crypto operations.
Handles MasterToken and sequence number
"""
def __init__(self):
self._msl_data = None
self.mastertoken = None
self.serial_number = None
self.sequence_number = None
self.renewal_window = Non... | class MSLBaseCrypto:
"""
Common base class for MSL crypto operations.
Handles MasterToken and sequence number
"""
def __init__(self):
self._msl_data = None
self.mastertoken = None
self.serial_number = None
self.sequence_number = None
self.renewal_window = Non... | self._msl_data = msl_data if msl_data else {}
if msl_data:
self.set_mastertoken(msl_data['tokens']['mastertoken'])
self.bound_esn = msl_data.get('bound_esn', get_esn())
| self._msl_data = msl_data if msl_data else {}
if msl_data:
self.set_mastertoken(msl_data['tokens']['mastertoken'])
self.bound_esn = msl_data.get('bound_esn', get_esn())
| 14 | 1,672 | 80 | 1,752 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Common base for crypto handlers
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import json
import base64
import time
import ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Common base for crypto handlers
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import json
import base64
import time
import ... |
28,141 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/msl/default_crypto.py | 121,122 | 1,126 | _base64key_decode | 122,126 | 122,126 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... | padding = len(b64) % 4
if padding != 0:
b64 += '=' * (4 - padding)
return base64.urlsafe_b64decode(b64.encode('utf8'))
| padding = len(b64) % 4
if padding != 0:
b64 += '=' * (4 - padding)
return base64.urlsafe_b64decode(b64.encode('utf8'))
| 18 | 1,516 | 65 | 1,581 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... | |
28,142 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/msl/default_crypto.py | 42,43 | 33,117 | load_crypto_session | DefaultMSLCrypto | 43,58 | 43,58 | class DefaultMSLCrypto(MSLBaseCrypto):
"""Crypto Handler for non-Android platforms"""
def __init__(self):
super().__init__()
self.rsa_key = None
self.encryption_key = None
self.sign_key = None
def load_crypto_session(self, msl_data=None):
FILL_FUNC_BODY def key_request_d... | class DefaultMSLCrypto(MSLBaseCrypto):
"""Crypto Handler for non-Android platforms"""
def __init__(self):
super().__init__()
self.rsa_key = None
self.encryption_key = None
self.sign_key = None
def load_crypto_session(self, msl_data=None):
FILL_FUNC_BODY def key_request_d... | try:
self.encryption_key = base64.standard_b64decode(
msl_data['encryption_key'])
self.sign_key = base64.standard_b64decode(
msl_data['sign_key'])
if not self.encryption_key or not self.sign_key:
raise MSLError('Missing encrypti... | try:
self.encryption_key = base64.standard_b64decode(
msl_data['encryption_key'])
self.sign_key = base64.standard_b64decode(
msl_data['sign_key'])
if not self.encryption_key or not self.sign_key:
raise MSLError('Missing encrypti... | 42 | 913 | 223 | 1,136 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2017 Trummerjo (original implementation module)
Copyright (C) 2018 Caphm
Crypto handler for non-Android platforms
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impo... |
28,145 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/msl/msl_request_builder.py | 108,109 | 27,176 | _encrypted_chunk | MSLRequestBuilder | 109,124 | 109,124 | class MSLRequestBuilder:
"""Provides mechanisms to create MSL requests"""
def __init__(self, nfsession):
self.nfsession: 'NFSessionOperations' = nfsession
self.current_message_id = None
self.rndm = random.SystemRandom()
# Set the Crypto handler
if common.get_system_platf... | class MSLRequestBuilder:
"""Provides mechanisms to create MSL requests"""
def __init__(self, nfsession):
self.nfsession: 'NFSessionOperations' = nfsession
self.current_message_id = None
self.rndm = random.SystemRandom()
# Set the Crypto handler
if common.get_system_platf... | if data:
data = base64.standard_b64encode(json.dumps(data).encode('utf-8')).decode('utf-8')
payload = json.dumps({
'messageid': self.current_message_id,
'data': data,
'sequencenumber': 1,
'endofmsg': True
})
if envelope_payload:... | if data:
data = base64.standard_b64encode(json.dumps(data).encode('utf-8')).decode('utf-8')
payload = json.dumps({
'messageid': self.current_message_id,
'data': data,
'sequencenumber': 1,
'endofmsg': True
})
if envelope_payload:... | 34 | 1,760 | 196 | 1,956 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL request building
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import json
import base64
import random
import time
from ... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL request building
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import json
import base64
import random
import time
from ... |
28,149 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/msl/profiles.py | 102,103 | 1,107 | _additional_profiles | 103,107 | 103,107 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL video profiles
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import G
import resources.lib.co... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL video profiles
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import G
import resources.lib.co... | return (PROFILES[profiles]
if (all(G.ADDON.getSettingBool(setting) for setting in common.make_list(req_settings)) and
not any(G.ADDON.getSettingBool(setting) for setting in common.make_list(forb_settings)))
else [])
| return (PROFILES[profiles]
if (all(G.ADDON.getSettingBool(setting) for setting in common.make_list(req_settings)) and
not any(G.ADDON.getSettingBool(setting) for setting in common.make_list(forb_settings)))
else [])
| 17 | 1,639 | 81 | 1,720 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL video profiles
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import G
import resources.lib.co... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
MSL video profiles
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import G
import resources.lib.co... | |
28,150 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/nfsession.py | 44,45 | 19,60 | library_auto_update | NetflixSession | 46,52 | 45,52 | class NetflixSession:
"""Stateful netflix session management"""
http_ipc_slots = {}
def __init__(self):
# Create and establish the Netflix session
self.nfsession = NFSessionOperations()
# Create MSL handler
self.msl_handler = MSLHandler(self.nfsession)
# Set to the ... | class NetflixSession:
"""Stateful netflix session management"""
http_ipc_slots = {}
def __init__(self):
# Create and establish the Netflix session
self.nfsession = NFSessionOperations()
# Create MSL handler
self.msl_handler = MSLHandler(self.nfsession)
# Set to the ... | try:
# Call the function in a thread to return immediately without blocking the service
common.run_threaded(True, self._run_library_auto_update)
except Exception as exc: # pylint: disable=broad-except
LOG.error('library_auto_update raised an error: {}', exc)
| """Run the library auto update"""
try:
# Call the function in a thread to return immediately without blocking the service
common.run_threaded(True, self._run_library_auto_update)
except Exception as exc: # pylint: disable=broad-except
LOG.error('library_auto_... | 30 | 467 | 86 | 553 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Stateful Netflix session management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common as common
from... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Stateful Netflix session management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import resources.lib.common as common
from... |
28,154 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/session/base.py | 59,61 | 22,62 | auth_url | SessionBase | 61,62 | 61,62 | class SessionBase:
"""Initialize the netflix session"""
session = None
"""The requests.session object to handle communication to Netflix"""
# Functions from derived classes to allow perform particular operations in parent classes
external_func_activate_profile = None # (set by nfsession_op.py)
... | class SessionBase:
"""Initialize the netflix session"""
session = None
"""The requests.session object to handle communication to Netflix"""
# Functions from derived classes to allow perform particular operations in parent classes
external_func_activate_profile = None # (set by nfsession_op.py)
... | G.LOCAL_DB.set_value('auth_url', value, TABLE_SESSION)
| G.LOCAL_DB.set_value('auth_url', value, TABLE_SESSION)
| 3 | 378 | 24 | 402 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Initialize the netflix session
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more informatio... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Initialize the netflix session
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more informatio... |
28,155 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/session/cookie.py | 24,25 | 21,55 | _load_cookies | SessionCookie | 26,39 | 25,39 | class SessionCookie(SessionBase):
"""Handle the cookies"""
def _load_cookies(self):
FILL_FUNC_BODY def _verify_session_cookies(self):
"""Verify that the session cookies have not expired"""
if not self.session.cookies:
return False
for cookie_name in LOGIN_COOKIES:
... | class SessionCookie(SessionBase):
"""Handle the cookies"""
def _load_cookies(self):
"""Load stored cookies from disk"""
FILL_FUNC_BODY def _verify_session_cookies(self):
"""Verify that the session cookies have not expired"""
if not self.session.cookies:
return False
... | # pylint: disable=broad-except
if not self.session.cookies:
try:
self.session.cookies = cookies.load()
except MissingCookiesError:
return False
except Exception as exc:
import traceback
LOG.error('Failed ... | """Load stored cookies from disk"""
# pylint: disable=broad-except
if not self.session.cookies:
try:
self.session.cookies = cookies.load()
except MissingCookiesError:
return False
except Exception as exc:
import ... | 32 | 228 | 122 | 350 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Handle the cookies
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impor... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Handle the cookies
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
impor... |
28,159 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/nfsession/session/path_requests.py | 94,96 | 20,144 | perpetual_path_request_switch_profiles | SessionPathRequests | 100,115 | 96,115 | class SessionPathRequests(SessionAccess):
"""Manages the PATH requests"""
@measure_exec_time_decorator(is_immediate=True)
def path_request(self, paths):
"""Perform a path request against the Shakti API"""
LOG.debug('Executing path request: {}', paths)
custom_params = {}
# Us... | class SessionPathRequests(SessionAccess):
"""Manages the PATH requests"""
@measure_exec_time_decorator(is_immediate=True)
def path_request(self, paths):
"""Perform a path request against the Shakti API"""
LOG.debug('Executing path request: {}', paths)
custom_params = {}
# Us... | # Profile chosen by the user for the synchronization from which to get My List videos
mylist_profile_guid = G.SHARED_DB.get_value('sync_mylist_profile_guid',
G.LOCAL_DB.get_guid_owner_profile())
# Current profile active
current_profile_... | """
Perform a perpetual path request by activating a specified profile,
Used exclusively to get My List of a profile other than the current one
"""
# Profile chosen by the user for the synchronization from which to get My List videos
mylist_profile_guid = G.SHARED_DB.get_... | 73 | 1,585 | 283 | 1,868 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Manages the PATH requests
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
""... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT
Manages the PATH requests
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
""... |
28,162 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/playback/action_controller.py | 398,399 | 384,401 | stop_join | PlaybackTick | 399,401 | 399,401 | class PlaybackTick(threading.Thread):
"""Thread to send a notification every second of playback"""
def __init__(self, on_playback_tick):
self._on_playback_tick = on_playback_tick
self._stop_event = threading.Event()
self.is_playback_paused = False
super().__init__()
def run(... | class PlaybackTick(threading.Thread):
"""Thread to send a notification every second of playback"""
def __init__(self, on_playback_tick):
self._on_playback_tick = on_playback_tick
self._stop_event = threading.Event()
self.is_playback_paused = False
super().__init__()
def run(... | self._stop_event.set()
self.join()
| self._stop_event.set()
self.join()
| 2 | 173 | 18 | 191 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Playback tracking and coordination of several actions during playback
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import j... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Playback tracking and coordination of several actions during playback
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import j... |
28,163 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/playback/action_manager.py | 48,49 | 14,145 | call_initialize | ActionManager | 52,57 | 49,57 | class ActionManager:
"""
Base class for managers that handle executing of specific actions during playback
"""
SETTING_ID = None # ID of the settings.xml property
def __init__(self):
self._enabled = None
self.videoid = None
self.videoid_parent = None
"""If the 'vid... | class ActionManager:
"""
Base class for managers that handle executing of specific actions during playback
"""
SETTING_ID = None # ID of the settings.xml property
def __init__(self):
self._enabled = None
self.videoid = None
self.videoid_parent = None
"""If the 'vid... | self.videoid = data['videoid']
self.videoid_parent = data['videoid_parent']
self._call_if_enabled(self.initialize, data=data)
LOG.debug('Initialized {}: {}', self.name, self)
| """
Initialize the manager with data when the addon initiates a playback.
"""
self.videoid = data['videoid']
self.videoid_parent = data['videoid_parent']
self._call_if_enabled(self.initialize, data=data)
LOG.debug('Initialized {}: {}', self.name, self)
| 13 | 1,191 | 75 | 1,266 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Common base for all playback action managers
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Common base for all playback action managers
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from resources.lib.globals import... |
28,164 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/playback/am_playback.py | 71,72 | 21,118 | on_tick | AMPlayback | 72,80 | 72,80 | class AMPlayback(ActionManager):
"""Operations for changing the playback status"""
SETTING_ID = 'ResumeManager_enabled'
def __init__(self):
super().__init__()
self.resume_position = None
self.enabled = True
self.start_time = None
self.is_player_in_pause = False
... | class AMPlayback(ActionManager):
"""Operations for changing the playback status"""
SETTING_ID = 'ResumeManager_enabled'
def __init__(self):
super().__init__()
self.resume_position = None
self.enabled = True
self.start_time = None
self.is_player_in_pause = False
... | # Stops playback when paused for more than one hour.
# Some users leave the playback paused also for more than 12 hours,
# this complicates things to resume playback, because the manifest data expires and with it also all
# the streams urls are no longer guaranteed, so we force the stop ... | # Stops playback when paused for more than one hour.
# Some users leave the playback paused also for more than 12 hours,
# this complicates things to resume playback, because the manifest data expires and with it also all
# the streams urls are no longer guaranteed, so we force the stop ... | 79 | 1,333 | 153 | 1,486 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Smeulf (original implementation module)
Operations for changing the playback status
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import x... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Smeulf (original implementation module)
Operations for changing the playback status
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import time
import xbmc
import x... |
28,165 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/playback/am_section_skipping.py | 61,62 | 20,86 | _auto_skip | AMSectionSkipper | 62,75 | 62,75 | class AMSectionSkipper(ActionManager):
"""
Checks if a skippable section has been reached and takes appropriate action
"""
SETTING_ID = 'SectionSkipper_enabled'
def __init__(self):
super().__init__()
self.markers = {}
self.auto_skip = False
self.pause_on_skip = Fals... | class AMSectionSkipper(ActionManager):
"""
Checks if a skippable section has been reached and takes appropriate action
"""
SETTING_ID = 'SectionSkipper_enabled'
def __init__(self):
super().__init__()
self.markers = {}
self.auto_skip = False
self.pause_on_skip = Fals... | LOG.info('Auto-skipping {}', section)
player = xbmc.Player()
ui.show_notification(
common.get_local_string(SKIPPABLE_SECTIONS[section]))
if self.pause_on_skip:
player.pause()
xbmc.sleep(1000) # give kodi the chance to execute
player.seekTi... | LOG.info('Auto-skipping {}', section)
player = xbmc.Player()
ui.show_notification(
common.get_local_string(SKIPPABLE_SECTIONS[section]))
if self.pause_on_skip:
player.pause()
xbmc.sleep(1000) # give kodi the chance to execute
player.seekTi... | 41 | 656 | 202 | 858 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Skipping of video sections (recap, intro)
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import resources.lib.co... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Skipping of video sections (recap, intro)
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import xbmc
import resources.lib.co... |
28,170 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/playback/markers.py | 30,31 | 1,53 | get_offset_markers | 32,39 | 31,39 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various timeline markers provided by Netflix
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
SKIPPABLE_SECTIONS = {'credit': 3... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various timeline markers provided by Netflix
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
SKIPPABLE_SECTIONS = {'credit': 3... | return {
marker: metadata[marker]
for marker in [OFFSET_CREDITS, OFFSET_WATCHED_TO_END]
if metadata.get(marker) is not None
}
| """Extract offset timeline markers from metadata if they exist"""
return {
marker: metadata[marker]
for marker in [OFFSET_CREDITS, OFFSET_WATCHED_TO_END]
if metadata.get(marker) is not None
}
| 15 | 453 | 63 | 516 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various timeline markers provided by Netflix
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
SKIPPABLE_SECTIONS = {'credit': 3... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Various timeline markers provided by Netflix
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
SKIPPABLE_SECTIONS = {'credit': 3... | |
28,171 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/settings_monitor.py | 126,127 | 1,133 | _check_watched_status_sync | 128,133 | 127,133 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... | progress_manager_enabled = G.ADDON.getSettingBool('sync_watched_status')
progress_manager_enabled_old = G.LOCAL_DB.get_value('sync_watched_status', True, TABLE_SETTINGS_MONITOR)
if progress_manager_enabled != progress_manager_enabled_old:
G.LOCAL_DB.set_value('sync_watched_status', progress_manager_... | """Check if NF watched status sync setting is changed"""
progress_manager_enabled = G.ADDON.getSettingBool('sync_watched_status')
progress_manager_enabled_old = G.LOCAL_DB.get_value('sync_watched_status', True, TABLE_SETTINGS_MONITOR)
if progress_manager_enabled != progress_manager_enabled_old:
... | 17 | 1,798 | 154 | 1,952 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... | |
28,172 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/settings_monitor.py | 38,39 | 22,126 | onSettingsChanged | SettingsMonitor | 39,52 | 39,52 | class SettingsMonitor(xbmc.Monitor):
"""Checks when settings are changed (all code is executed in the service instance only)"""
def __init__(self):
super().__init__()
self.ignore_n_events = 0
@contextmanager
def ignore_events(self, ignore_n_events):
"""Context to set how many on... | class SettingsMonitor(xbmc.Monitor):
"""Checks when settings are changed (all code is executed in the service instance only)"""
def __init__(self):
super().__init__()
self.ignore_n_events = 0
@contextmanager
def ignore_events(self, ignore_n_events):
"""Context to set how many on... | # This method will be called when user change add-on settings or every time ADDON.setSetting...() is called
if self.ignore_n_events > 0:
self.ignore_n_events -= 1
LOG.debug('SettingsMonitor: onSettingsChanged event ignored (remaining {})', self.ignore_n_events)
return... | # This method will be called when user change add-on settings or every time ADDON.setSetting...() is called
if self.ignore_n_events > 0:
self.ignore_n_events -= 1
LOG.debug('SettingsMonitor: onSettingsChanged event ignored (remaining {})', self.ignore_n_events)
return... | 66 | 1,379 | 196 | 1,575 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo (original implementation module)
Checks when settings are changed
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from contextlib import contextmana... |
28,173 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/tcp_keep_alive.py | 56,57 | 1,80 | enable_tcp_keep_alive | 58,80 | 57,80 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | # More info on PR: https://github.com/CastagnaIT/plugin.video.netflix/pull/1065
sock_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
if sys.platform == 'linux':
# TCP Keep Alive Probes for Linux/Android
if hasattr(socket, 'TCP_KEEPIDLE'):
sock_options.append((socket.IPPRO... | """Enable TCP Keep-Alive (by default on urllib3 used by Requests is disabled)"""
# More info on PR: https://github.com/CastagnaIT/plugin.video.netflix/pull/1065
sock_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
if sys.platform == 'linux':
# TCP Keep Alive Probes for Linux/Android
... | 133 | 772 | 603 | 1,375 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | |
28,174 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/tcp_keep_alive.py | 24,25 | 22,29 | init_poolmanager | KeepAliveHTTPAdapter | 25,29 | 25,29 | class KeepAliveHTTPAdapter(HTTPAdapter):
"""Transport adapter that allows us to use TCP Keep-Alive over HTTPS."""
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
FILL_FUNC_BODY | class KeepAliveHTTPAdapter(HTTPAdapter):
"""Transport adapter that allows us to use TCP Keep-Alive over HTTPS."""
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
FILL_FUNC_BODY | self.poolmanager = KeepAlivePoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
| self.poolmanager = KeepAlivePoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
| 7 | 70 | 48 | 118 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... |
28,175 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/services/tcp_keep_alive.py | 45,46 | 42,56 | _validate_conn | TCPKeepAliveHTTPSConnectionPool | 47,56 | 46,56 | class TCPKeepAliveHTTPSConnectionPool(HTTPSConnectionPool):
"""This class overrides the _validate_conn method in the HTTPSConnectionPool class. This is the entry point to use
for modifying the socket as it is called after the socket is created and before the request is made."""
def _validate_conn(self, conn... | class TCPKeepAliveHTTPSConnectionPool(HTTPSConnectionPool):
"""This class overrides the _validate_conn method in the HTTPSConnectionPool class. This is the entry point to use
for modifying the socket as it is called after the socket is created and before the request is made."""
def _validate_conn(self, conn... | super()._validate_conn(conn)
# NOTE: conn.sock can be of many types of classes, some classes like (WrappedSocket)
# not inherit all socket methods and conn.sock.socket is not always available,
# then the best way is to use default_socket_options, with the exception of Windows... | """Called right before a request is made, after the socket is created."""
super()._validate_conn(conn)
# NOTE: conn.sock can be of many types of classes, some classes like (WrappedSocket)
# not inherit all socket methods and conn.sock.socket is not always available,
# ... | 62 | 110 | 178 | 288 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2021 Stefano Gottardo - @CastagnaIT
Helper to enable TCP Keep Alive
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import socket
import sys
from requests.adapters impor... |
28,176 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/upgrade_actions.py | 34,35 | 1,118 | migrate_library | 35,61 | 35,61 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Defines upgrade actions to the frontend and backend, to be performed by upgrade_controller
SPDX-License-Identifier: MIT
See LICE... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Defines upgrade actions to the frontend and backend, to be performed by upgrade_controller
SPDX-License-Identifier: MIT
See LICE... | # Migrate the Kodi library to the new format of STRM path
# - Old STRM: '/play/show/xxxxxxxx/season/xxxxxxxx/episode/xxxxxxxx/' (used before ver 1.7.0)
# - New STRM: '/play_strm/show/xxxxxxxx/season/xxxxxxxx/episode/xxxxxxxx/' (used from ver 1.7.0)
folders = get_library_subfolders(FOLDER_NAME_MOVIES) + ... | # Migrate the Kodi library to the new format of STRM path
# - Old STRM: '/play/show/xxxxxxxx/season/xxxxxxxx/episode/xxxxxxxx/' (used before ver 1.7.0)
# - New STRM: '/play_strm/show/xxxxxxxx/season/xxxxxxxx/episode/xxxxxxxx/' (used from ver 1.7.0)
folders = get_library_subfolders(FOLDER_NAME_MOVIES) + ... | 123 | 1,534 | 454 | 1,988 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Defines upgrade actions to the frontend and backend, to be performed by upgrade_controller
SPDX-License-Identifier: MIT
See LICE... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2019 Stefano Gottardo - @CastagnaIT (original implementation module)
Defines upgrade actions to the frontend and backend, to be performed by upgrade_controller
SPDX-License-Identifier: MIT
See LICE... | |
28,180 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/cookies.py | 104,105 | 1,157 | load | 106,130 | 105,130 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... | file_path = cookie_file_path()
if not xbmcvfs.exists(file_path):
LOG.debug('Cookies file does not exist')
raise MissingCookiesError
cookie_file = xbmcvfs.File(file_path, 'rb')
try:
cookie_jar = pickle.loads(cookie_file.readBytes())
# Clear flwssn cookie if present, as it ... | """Load cookies for a given account and check them for validity"""
file_path = cookie_file_path()
if not xbmcvfs.exists(file_path):
LOG.debug('Cookies file does not exist')
raise MissingCookiesError
cookie_file = xbmcvfs.File(file_path, 'rb')
try:
cookie_jar = pickle.loads(co... | 87 | 1,489 | 308 | 1,797 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... | |
28,181 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/cookies.py | 55,56 | 22,81 | _find_no_duplicates | PickleableCookieJar | 67,81 | 56,81 | class PickleableCookieJar(CookieJar):
"""A pickleable CookieJar class"""
# This code has been adapted from RequestsCookieJar of "Requests" module
@classmethod
def cast(cls, cookie_jar: CookieJar):
"""Make a kind of cast to convert the class from CookieJar to PickleableCookieJar"""
assert... | class PickleableCookieJar(CookieJar):
"""A pickleable CookieJar class"""
# This code has been adapted from RequestsCookieJar of "Requests" module
@classmethod
def cast(cls, cookie_jar: CookieJar):
"""Make a kind of cast to convert the class from CookieJar to PickleableCookieJar"""
assert... | to_return = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if to_return is not None:
# if there are multiple c... | """Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises K... | 77 | 540 | 190 | 730 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Persistent cookie management
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import pickle
from http.cookiejar import CookieJa... |
28,183 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 219,220 | 206,224 | get | CustomVideoList | 221,224 | 220,224 | class CustomVideoList:
"""A video list"""
def __init__(self, path_response):
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.videos = OrderedDict(self.data.get('videos', {}))
# self.artitem = next(self.videos.values())... | class CustomVideoList:
"""A video list"""
def __init__(self, path_response):
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.videos = OrderedDict(self.data.get('videos', {}))
# self.artitem = next(self.videos.values())... | return _check_sentinel(self.data.get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data.get(key, default))
| 3 | 215 | 25 | 240 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,184 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 44,45 | 19,69 | lists_by_context | LoCo | 52,60 | 45,60 | class LoCo:
"""List of components (LoCo)"""
def __init__(self, path_response):
self.data = path_response
LOG.debug('LoCo data: {}', self.data)
self.id = next(iter(self.data['locos'])) # Get loco root id
_filterout_loco_contexts(self.id, self.data, ['billboard'])
def __getit... | class LoCo:
"""List of components (LoCo)"""
def __init__(self, path_response):
self.data = path_response
LOG.debug('LoCo data: {}', self.data)
self.id = next(iter(self.data['locos'])) # Get loco root id
_filterout_loco_contexts(self.id, self.data, ['billboard'])
def __getit... | lists = {}
for list_id, list_data in self.data['lists'].items():
if list_data['componentSummary'].get('value', {}).get('context') in contexts:
lists.update({list_id: VideoListLoCo(self.data, list_id)})
if break_on_first:
break
retur... | """
Get all video lists of the given contexts
:param contexts: list of context names
:param break_on_first: stop the research at first match
:return iterable items of a dict where key=list id, value=VideoListLoCo object data
"""
lists = {}
for list_id, li... | 21 | 501 | 98 | 599 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,185 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 299,300 | 285,309 | lists | LoLoMoCategory | 304,309 | 300,309 | class LoLoMoCategory:
"""'List of Lists of Movies' by category (LoLoMoByCategory)"""
def __init__(self, path_response):
self.data = path_response
# LOG.debug('LoLoMoByCategory data: {}', self.data)
self.id = next(iter(self.data['locos'])) # Get loco root id
def __getitem__(self, ke... | class LoLoMoCategory:
"""'List of Lists of Movies' by category (LoLoMoByCategory)"""
def __init__(self, path_response):
self.data = path_response
# LOG.debug('LoLoMoByCategory data: {}', self.data)
self.id = next(iter(self.data['locos'])) # Get loco root id
def __getitem__(self, ke... | # It is as property to avoid slow down the loading of main menu
for list_id, list_data in self.data['lists'].items(): # pylint: disable=unused-variable
yield list_id, list_data['componentSummary'].get('value', {}), VideoListLoCo(self.data, list_id)
| """
Generator to get all lists of videos
:return tuples as: list ID, summary data (dict), video list
"""
# It is as property to avoid slow down the loading of main menu
for list_id, list_data in self.data['lists'].items(): # pylint: disable=unused-variable
yi... | 28 | 237 | 87 | 324 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,186 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 201,202 | 178,206 | get | SearchVideoList | 203,206 | 202,206 | class SearchVideoList:
"""A video list with search results"""
def __init__(self, path_response):
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
has_data = 'search' in path_response
self.videos = OrderedDict()
self.... | class SearchVideoList:
"""A video list with search results"""
def __init__(self, path_response):
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
has_data = 'search' in path_response
self.videos = OrderedDict()
self.... | return _check_sentinel(self.data['search'].get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data['search'].get(key, default))
| 3 | 399 | 27 | 426 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,187 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 129,130 | 101,134 | get | VideoList | 131,134 | 130,134 | class VideoList:
"""A video list"""
def __init__(self, path_response, list_id=None):
# LOG.debug('VideoList data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
has_data = bool(path_response.get('lists'... | class VideoList:
"""A video list"""
def __init__(self, path_response, list_id=None):
# LOG.debug('VideoList data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
has_data = bool(path_response.get('lists'... | return _check_sentinel(self.data['lists'][self.videoid.value].get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data['lists'][self.videoid.value].get(key, default))
| 3 | 438 | 36 | 474 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,188 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 96,97 | 69,101 | get | VideoListLoCo | 98,101 | 97,101 | class VideoListLoCo:
"""A video list, for LoCo data"""
def __init__(self, path_response, list_id):
# LOG.debug('VideoListLoCo data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.list_id = list_id
... | class VideoListLoCo:
"""A video list, for LoCo data"""
def __init__(self, path_response, list_id):
# LOG.debug('VideoListLoCo data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.list_id = list_id
... | return _check_sentinel(self.data['lists'][self.list_id]['componentSummary'].get('value', {}).get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data['lists'][self.list_id]['componentSummary'].get('value', {}).get(key, default))
| 4 | 442 | 44 | 486 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,189 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 166,167 | 134,171 | get | VideoListSorted | 168,171 | 167,171 | class VideoListSorted:
"""A video list"""
def __init__(self, path_response, context_name, context_id, req_sort_order_type):
# LOG.debug('VideoListSorted data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
... | class VideoListSorted:
"""A video list"""
def __init__(self, path_response, context_name, context_id, req_sort_order_type):
# LOG.debug('VideoListSorted data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
... | return _check_sentinel(self.data_lists.get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data_lists.get(key, default))
| 3 | 519 | 27 | 546 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,190 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/data_types.py | 241,242 | 224,246 | get | VideosList | 243,246 | 242,246 | class VideosList:
"""A video's list"""
def __init__(self, path_response, list_info_path):
# LOG.debug('VideosList data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.videos = OrderedDict(self.data... | class VideosList:
"""A video's list"""
def __init__(self, path_response, list_info_path):
# LOG.debug('VideosList data: {}', path_response)
self.perpetual_range_selector = path_response.get('_perpetual_range_selector')
self.data = path_response
self.videos = OrderedDict(self.data... | return _check_sentinel(self.data.get(key, default))
| """Pass call on to the backing dict of this VideoList."""
return _check_sentinel(self.data.get(key, default))
| 3 | 287 | 25 | 312 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Convenience representations of data types returned by the API
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
# pylint: disabl... |
28,192 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/logging.py | 106,107 | 1,156 | logdetails_decorator | 108,132 | 107,132 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... | name = func.__name__
@wraps(func)
def wrapped(*args, **kwargs):
"""Wrapper function to maintain correct stack traces"""
that = args[0]
class_name = that.__class__.__name__
arguments = [f':{key} = {value}:'
for key, value in kwargs.items()
... | """Log decorator that is used to annotate methods & output everything to the Kodi debug log"""
name = func.__name__
@wraps(func)
def wrapped(*args, **kwargs):
"""Wrapper function to maintain correct stack traces"""
that = args[0]
class_name = that.__class__.__name__
argu... | 68 | 1,447 | 270 | 1,717 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... | |
28,193 | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix | /home/hieuvd/dung_repo/raw/stars_02/CastagnaIT_plugin.video.netflix/plugin.video.netflix/resources/lib/utils/logging.py | 92,93 | 17,106 | log_time_trace | Logging | 94,106 | 93,106 | class Logging:
"""A helper class for logging"""
def __init__(self):
self.__addon_id = None
self.__plugin_handle = None
self.is_enabled = None
self.is_time_trace_enabled = False
self.time_trace_level = -2
self.__time_trace_data = []
self.debug = self._debu... | class Logging:
"""A helper class for logging"""
def __init__(self):
self.__addon_id = None
self.__plugin_handle = None
self.is_enabled = None
self.is_time_trace_enabled = False
self.time_trace_level = -2
self.__time_trace_data = []
self.debug = self._debu... | if not self.is_time_trace_enabled:
return
time_trace = ['Execution time measured for this run:\n']
self.__time_trace_data.reverse()
for trace in self.__time_trace_data:
time_trace.append(' ' * trace[2])
time_trace.append(format(trace[0], '<30'))
... | """Write the time tracing info to the debug log"""
if not self.is_time_trace_enabled:
return
time_trace = ['Execution time measured for this run:\n']
self.__time_trace_data.reverse()
for trace in self.__time_trace_data:
time_trace.append(' ' * trace[2])
... | 27 | 884 | 151 | 1,035 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Copyright (C) 2020 Stefano Gottardo
Logging and measuring execution times
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
... |
28,344 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/commons.py | 28,29 | 1,97 | intersperse | 29,34 | 29,34 | import torch
from torch.nn import functional as F
import torch.jit
def script_method(fn, _rcb=None):
return fn
def script(obj, optimize=True, _frames_up=0, _rcb=None):
return obj
torch.jit.script_method = script_method
torch.jit.script = script
def init_weights(m, mean=0.0, std=0.01):
classname = m.__clas... | import torch
from torch.nn import functional as F
import torch.jit
def script_method(fn, _rcb=None):
return fn
def script(obj, optimize=True, _frames_up=0, _rcb=None):
return obj
torch.jit.script_method = script_method
torch.jit.script = script
def init_weights(m, mean=0.0, std=0.01):
classname = m.__clas... | result = [item] * (len(lst) * 2 + 1)
result[1::2] = lst
return result
| result = [item] * (len(lst) * 2 + 1)
result[1::2] = lst
return result
| 14 | 1,027 | 42 | 1,069 | import torch
from torch.nn import functional as F
import torch.jit
def script_method(fn, _rcb=None):
return fn
def script(obj, optimize=True, _frames_up=0, _rcb=None):
return obj
torch.jit.script_method = script_method
torch.jit.script = script
def init_weights(m, mean=0.0, std=0.01):
classname = m.__clas... | import torch
from torch.nn import functional as F
import torch.jit
def script_method(fn, _rcb=None):
return fn
def script(obj, optimize=True, _frames_up=0, _rcb=None):
return obj
torch.jit.script_method = script_method
torch.jit.script = script
def init_weights(m, mean=0.0, std=0.01):
classname = m.__clas... | |
28,346 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 86,87 | 74,97 | forward | FeatureExtractor | 87,97 | 87,97 | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | x = F.gelu(self.norm0(self.conv0(x)))
x = F.gelu(self.conv1(x))
x = F.gelu(self.conv2(x))
x = F.gelu(self.conv3(x))
x = F.gelu(self.conv4(x))
x = F.gelu(self.conv5(x))
x = F.gelu(self.conv6(x))
return x
| x = F.gelu(self.norm0(self.conv0(x)))
x = F.gelu(self.conv1(x))
x = F.gelu(self.conv2(x))
x = F.gelu(self.conv3(x))
x = F.gelu(self.conv4(x))
x = F.gelu(self.conv5(x))
x = F.gelu(self.conv6(x))
return x
| 23 | 319 | 140 | 459 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,347 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 104,105 | 97,111 | forward | FeatureProjection | 105,111 | 105,111 | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| 11 | 114 | 44 | 158 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,348 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 48,49 | 10,63 | logits | Hubert | 49,56 | 49,56 | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | logits = torch.cosine_similarity(
x.unsqueeze(2),
self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
dim=-1,
)
return logits / 0.1
| logits = torch.cosine_similarity(
x.unsqueeze(2),
self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
dim=-1,
)
return logits / 0.1
| 11 | 640 | 78 | 718 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,349 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 67,69 | 63,74 | units | HubertSoft | 69,74 | 69,74 | class HubertSoft(Hubert):
def __init__(self):
super().__init__()
@torch.inference_mode()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | class HubertSoft(Hubert):
def __init__(self):
super().__init__()
@torch.inference_mode()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| 19 | 71 | 69 | 140 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,350 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 123,124 | 111,129 | forward | PositionalConvEmbedding | 124,129 | 124,129 | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | x = self.conv(x.transpose(1, 2))
x = F.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| x = self.conv(x.transpose(1, 2))
x = F.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| 12 | 149 | 57 | 206 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,351 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/hubert_model.py | 139,146 | 129,154 | forward | TransformerEncoder | 146,154 | 146,154 | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
s... | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
s... | output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| 16 | 193 | 66 | 259 | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... | import copy
from typing import Optional, Tuple
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super(... |
28,352 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 116,117 | 96,133 | forward | DurationPredictor | 117,133 | 117,133 | class DurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.gin_channels = ... | class DurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.gin_channels = ... | x = torch.detach(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.norm_1(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
x = torch.relu(x)
x = self.norm_2(x)
x = self.drop(x)
x = self.proj(x * x_m... | x = torch.detach(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.norm_1(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
x = torch.relu(x)
x = self.norm_2(x)
x = self.drop(x)
x = self.proj(x * x_m... | 53 | 343 | 184 | 527 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,353 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 276,277 | 250,298 | forward | Generator | 277,298 | 277,298 | class Generator(torch.nn.Module):
def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
se... | class Generator(torch.nn.Module):
def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
se... | x = self.conv_pre(x)
if g is not None:
x = x + self.cond(g)
for i in range(self.num_upsamples):
x = F.leaky_relu(x, modules.LRELU_SLOPE)
x = self.ups[i](x)
xs = None
for j in range(self.num_kernels):
if xs is None:
... | x = self.conv_pre(x)
if g is not None:
x = x + self.cond(g)
for i in range(self.num_upsamples):
x = F.leaky_relu(x, modules.LRELU_SLOPE)
x = self.ups[i](x)
xs = None
for j in range(self.num_kernels):
if xs is None:
... | 58 | 494 | 241 | 735 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,354 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 240,241 | 218,250 | forward | PosteriorEncoder | 241,250 | 241,250 | class PosteriorEncoder(nn.Module):
def __init__(self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = h... | class PosteriorEncoder(nn.Module):
def __init__(self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = h... | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m... | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m... | 40 | 292 | 164 | 456 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,355 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 208,209 | 185,218 | forward | ResidualCouplingBlock | 209,218 | 209,218 | class ResidualCouplingBlock(nn.Module):
def __init__(self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
n_flows=4,
gin_channels=0):
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel... | class ResidualCouplingBlock(nn.Module):
def __init__(self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
n_flows=4,
gin_channels=0):
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel... | if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x = flow(x, x_mask, g=g, reverse=reverse)
return x
| if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x = flow(x, x_mask, g=g, reverse=reverse)
return x
| 27 | 289 | 92 | 381 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,356 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 48,49 | 15,96 | forward | StochasticDurationPredictor | 49,96 | 49,96 | class StochasticDurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
super().__init__()
filter_channels = in_channels # it needs to be removed from future version.
self.in_channels = in_channels
self.filter_channels = filter... | class StochasticDurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
super().__init__()
filter_channels = in_channels # it needs to be removed from future version.
self.in_channels = in_channels
self.filter_channels = filter... | x = torch.detach(x)
x = self.pre(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.convs(x, x_mask)
x = self.proj(x) * x_mask
if not reverse:
flows = self.flows
assert w is not None
logdet_tot_q = 0
h_w = self.post_pre(w)
h_w = se... | x = torch.detach(x)
x = self.pre(x)
if g is not None:
g = torch.detach(g)
x = x + self.cond(g)
x = self.convs(x, x_mask)
x = self.proj(x) * x_mask
if not reverse:
flows = self.flows
assert w is not None
logdet_tot_q = 0
h_w = self.post_pre(w)
h_w = se... | 213 | 634 | 800 | 1,434 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,357 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 369,370 | 298,405 | infer | SynthesizerTrn | 370,395 | 370,395 | class SynthesizerTrn(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
n_vocab,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resbloc... | class SynthesizerTrn(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
n_vocab,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resbloc... | x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
if self.n_speakers > 0:
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
else:
g = None
if self.use_sdp:
logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
else:
logw = self.dp(x, x_mask, ... | x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
if self.n_speakers > 0:
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
else:
g = None
if self.use_sdp:
logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
else:
logw = self.dp(x, x_mask, ... | 133 | 1,146 | 593 | 1,739 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,358 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/models.py | 170,171 | 133,185 | forward | TextEncoder | 171,185 | 171,185 | class TextEncoder(nn.Module):
def __init__(self,
n_vocab,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
emotion_embedding):
super().__init__()
self.n_vocab = n_vocab
self.out_channels = out_channels
self... | class TextEncoder(nn.Module):
def __init__(self,
n_vocab,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
emotion_embedding):
super().__init__()
self.n_vocab = n_vocab
self.out_channels = out_channels
self... | if self.n_vocab!=0:
x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
if emotion_embedding is not None:
x = x + self.emo_proj(emotion_embedding.unsqueeze(1))
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dt... | if self.n_vocab!=0:
x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
if emotion_embedding is not None:
x = x + self.emo_proj(emotion_embedding.unsqueeze(1))
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dt... | 57 | 422 | 235 | 657 | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... | import math
import torch
from torch import nn
from torch.nn import functional as F
import commons
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm
from commons import init_weights
class StochasticDurationPredictor(nn.Module):
def __init__(self, i... |
28,359 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 360,361 | 343,388 | forward | ConvFlow | 361,388 | 361,388 | class ConvFlow(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.num_bins = num_... | class ConvFlow(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.num_bins = num_... | x0, x1 = torch.split(x, [self.half_channels]*2, 1)
h = self.pre(x0)
h = self.convs(h, x_mask, g=g)
h = self.proj(h) * x_mask
b, c, t = x0.shape
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_... | x0, x1 = torch.split(x, [self.half_channels]*2, 1)
h = self.pre(x0)
h = self.convs(h, x_mask, g=g)
h = self.proj(h) * x_mask
b, c, t = x0.shape
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_... | 93 | 310 | 414 | 724 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,360 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 57,58 | 32,67 | forward | ConvReluNorm | 58,67 | 58,67 | class ConvReluNorm(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layer... | class ConvReluNorm(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layer... | x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
| x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
| 27 | 422 | 98 | 520 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,361 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 93,94 | 67,108 | forward | DDSConv | 94,108 | 94,108 | class DDSConv(nn.Module):
"""
Dilated and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Drop... | class DDSConv(nn.Module):
"""
Dilated and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Drop... | if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
| if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
| 46 | 364 | 159 | 523 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,362 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 284,285 | 277,295 | forward | ElementwiseAffine | 285,295 | 285,295 | class ElementwiseAffine(nn.Module):
def __init__(self, channels):
super().__init__()
self.channels = channels
self.m = nn.Parameter(torch.zeros(channels,1))
self.logs = nn.Parameter(torch.zeros(channels,1))
def forward(self, x, x_mask, reverse=False, **kwargs):
FILL_FUNC_BODY | class ElementwiseAffine(nn.Module):
def __init__(self, channels):
super().__init__()
self.channels = channels
self.m = nn.Parameter(torch.zeros(channels,1))
self.logs = nn.Parameter(torch.zeros(channels,1))
def forward(self, x, x_mask, reverse=False, **kwargs):
FILL_FUNC_BODY | if not reverse:
y = self.m + torch.exp(self.logs) * x
y = y * x_mask
logdet = torch.sum(self.logs * x_mask, [1,2])
return y, logdet
else:
x = (x - self.m) * torch.exp(-self.logs) * x_mask
return x
| if not reverse:
y = self.m + torch.exp(self.logs) * x
y = y * x_mask
logdet = torch.sum(self.logs * x_mask, [1,2])
return y, logdet
else:
x = (x - self.m) * torch.exp(-self.logs) * x_mask
return x
| 36 | 114 | 112 | 226 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
28,363 | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe | /home/hieuvd/dung_repo/raw/stars_02/CjangCjengh_MoeGoe/MoeGoe/modules.py | 268,269 | 267,277 | forward | Flip | 269,277 | 269,277 | class Flip(nn.Module):
def forward(self, x, *args, reverse=False, **kwargs):
FILL_FUNC_BODY | class Flip(nn.Module):
def forward(self, x, *args, reverse=False, **kwargs):
FILL_FUNC_BODY | x = torch.flip(x, [1])
if not reverse:
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
return x, logdet
else:
return x
| x = torch.flip(x, [1])
if not reverse:
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
return x, logdet
else:
return x
| 17 | 38 | 79 | 117 | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... | import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
import commons
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.