code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def download(cls, model_name, *, precision='FP16', download_dir=None, cache_dir=None):
'''
Downloads target model. If the model has already been downloaded,
retrieves the model from the cache instead of downloading it again.
Then creates OpenVINO Intermediate Representation (IR) network ... |
Downloads target model. If the model has already been downloaded,
retrieves the model from the cache instead of downloading it again.
Then creates OpenVINO Intermediate Representation (IR) network model.
Creates an object which stores information about the downloaded and IR model.
... | download | python | openvinotoolkit/open_model_zoo | tools/model_tools/src/omz_tools/models.py | https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/model_tools/src/omz_tools/models.py | Apache-2.0 |
def shapes_arg(values):
"""Checks that the argument represents a tensor shape or a sequence of tensor shapes"""
shapes = ast.literal_eval(values)
if not is_sequence(shapes):
raise argparse.ArgumentTypeError(
'{!r}: must be a sequence'.format(shapes))
if not all(is_sequence(shape) for... | Checks that the argument represents a tensor shape or a sequence of tensor shapes | shapes_arg | python | openvinotoolkit/open_model_zoo | tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | Apache-2.0 |
def load_model(model_name, weights, model_paths, module_name, model_params):
"""Import model and load pretrained weights"""
with prepend_to_path(model_paths):
try:
module = importlib.import_module(module_name)
creator = getattr(module, model_name)
model = creator(**m... | Import model and load pretrained weights | load_model | python | openvinotoolkit/open_model_zoo | tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | Apache-2.0 |
def convert_to_onnx(model, input_shapes, output_file, input_names, output_names, inputs_dtype, conversion_params,
opset_version):
"""Convert PyTorch model to ONNX and check the resulting onnx model"""
output_file.parent.mkdir(parents=True, exist_ok=True)
model.eval()
dummy_inputs = ... | Convert PyTorch model to ONNX and check the resulting onnx model | convert_to_onnx | python | openvinotoolkit/open_model_zoo | tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/model_tools/src/omz_tools/internal_scripts/pytorch_to_onnx.py | Apache-2.0 |
def stream_jsonl(filename: str) -> Iterable[Dict]:
"""
Parses each jsonl line and yields it as a dictionary
"""
if filename.endswith(".gz"):
with open(filename, "rb") as gzfp:
with gzip.open(gzfp, 'rt') as fp:
for line in fp:
if any(not x.isspace()... |
Parses each jsonl line and yields it as a dictionary
| stream_jsonl | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/data.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/data.py | MIT |
def write_jsonl(filename: str, data: Iterable[Dict], append: bool = False):
"""
Writes an iterable of dictionaries to jsonl
"""
if append:
mode = 'ab'
else:
mode = 'wb'
filename = os.path.expanduser(filename)
if filename.endswith(".gz"):
with open(filename, mode) as f... |
Writes an iterable of dictionaries to jsonl
| write_jsonl | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/data.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/data.py | MIT |
def entry_point(
sample_file: str,
k: str = "1,10,100",
n_workers: int = 4,
timeout: float = 3.0,
problem_file: str = "",
is_mbpp: bool = False,
):
"""
Evaluates the functional correctness of generated samples, and writes
results to f"{sample_file}_results.jsonl.gz"
"""
k = l... |
Evaluates the functional correctness of generated samples, and writes
results to f"{sample_file}_results.jsonl.gz"
| entry_point | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/evaluate_functional_correctness.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/evaluate_functional_correctness.py | MIT |
def read_dataset(
data_file: str = None,
dataset_type: str = "humaneval",
num_shot=None,
) -> Dict:
"""
Reads a dataset and returns a dictionary of tasks.
"""
if num_shot is not None:
print(f"{num_shot}-shot setting...")
if "humaneval" in dataset_type.lower():
if data_fil... |
Reads a dataset and returns a dictionary of tasks.
| read_dataset | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/evaluation.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/evaluation.py | MIT |
def estimate_pass_at_k(
num_samples: Union[int, List[int], np.ndarray],
num_correct: Union[List[int], np.ndarray],
k: int
) -> np.ndarray:
"""
Estimates pass@k of each problem and returns them in an array.
"""
def estimator(n: int, c: int, k: int) -> float:
"""
C... |
Estimates pass@k of each problem and returns them in an array.
| estimate_pass_at_k | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/evaluation.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/evaluation.py | MIT |
def evaluate_functional_correctness(
input_file: str = None,
tmp_dir: str = "./",
n_workers: int = 32,
timeout: float = 10.0,
problem_file: str = "../data/humaneval_python.jsonl.gz",
out_dir: str = None,
k: List[int] = [1, 10, 100],
test_groundtruth: bool ... |
Evaluates the functional correctness of a model.
| evaluate_functional_correctness | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/evaluation.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/evaluation.py | MIT |
def check_correctness(
task_id: str,
sample: dict,
language_type: str,
timeout: float = 3.0,
tmp_dir: str = None,
completion_id: Optional[int] = None,
) -> Dict:
"""
Evaluates the functional correctness of a completion by running the test
suite provided in the... |
Evaluates the functional correctness of a completion by running the test
suite provided in the problem.
| check_correctness | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/execution.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/execution.py | MIT |
def reliability_guard(maximum_memory_bytes: Optional[int] = None):
"""
This disables various destructive functions and prevents the generated code
from interfering with the test (e.g. fork bomb, killing other processes,
removing filesystem files, etc.)
WARNING
This function is NOT a security sa... |
This disables various destructive functions and prevents the generated code
from interfering with the test (e.g. fork bomb, killing other processes,
removing filesystem files, etc.)
WARNING
This function is NOT a security sandbox. Untrusted code, including, model-
generated code, should not be... | reliability_guard | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/execution.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/human_eval/execution.py | MIT |
def __init__(self, root, sample_num=1, language="python", issft=False):
"""
root: the path to the HumanEval dataset
sample_num: the number of samples for each prompt
language: the language of the HumanEval dataset
issft: whether to use the SFT setting
"""
self.roo... |
root: the path to the HumanEval dataset
sample_num: the number of samples for each prompt
language: the language of the HumanEval dataset
issft: whether to use the SFT setting
| __init__ | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/utils/dataset.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/utils/dataset.py | MIT |
def get_qa_only_data(self, data_json, sft=False):
"""
data_json: the jsonl file of HumanEval
sft: whether to use the SFT setting
return: a list of dict, each dict contains the prompt, task_id and stopwords
"""
ans = []
for line in data_json:
line = jso... |
data_json: the jsonl file of HumanEval
sft: whether to use the SFT setting
return: a list of dict, each dict contains the prompt, task_id and stopwords
| get_qa_only_data | python | deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/utils/dataset.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/HumanEval/utils/dataset.py | MIT |
def extract_python_block_with_solution(text):
"""
Extract the code block from the text that contains the solution function.
:param text: The text to search for the code block.
:return: The extracted code block.
"""
pattern = r'```python\n(.*?)def solution\(\):\n(.*?)```'
match = re.search(pa... |
Extract the code block from the text that contains the solution function.
:param text: The text to search for the code block.
:return: The extracted code block.
| extract_python_block_with_solution | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/run.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/run.py | MIT |
def load_data(args):
"""
Load data from file.
:param args: Arguments.
:return: A list of examples.
"""
if args.data_name != "math":
prompt = open("prompts/gsm8k.md").read()
else:
prompt = open("prompts/math.md").read()
examples = []
with open(f"datasets/{args.data_na... |
Load data from file.
:param args: Arguments.
:return: A list of examples.
| load_data | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/run.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/run.py | MIT |
def inference(args):
"""
Inference on the dataset.
:param args: Arguments.
:return: None
"""
# load data
samples = load_data(args)
samples = [sample for i,sample in enumerate(samples) if i%args.world_size==args.rank]
# create directory for saving results
os.makedirs(f'outputs/{a... |
Inference on the dataset.
:param args: Arguments.
:return: None
| inference | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/run.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/run.py | MIT |
def eval(args):
"""
Evaluate the results.
:param args: Arguments.
:return: None
"""
# load data
samples = []
for rank in range(args.world_size):
out_file = f"outputs/{args.model_name}/{args.data_name}/world_size_{args.world_size}_rank_{rank}.json"
if not os.path.exists(ou... |
Evaluate the results.
:param args: Arguments.
:return: None
| eval | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/run.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/run.py | MIT |
def math_equal(prediction: Union[bool, float, str],
reference: Union[float, str],
include_percentage: bool = True,
is_close: bool = True,
timeout: bool = False,
) -> bool:
"""
Exact match of math if and only if:
1. numerical equ... |
Exact match of math if and only if:
1. numerical equal: both can convert to float and are equal
2. symbolic equal: both can convert to sympy expression and are equal
| math_equal | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/utils/grader.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/utils/grader.py | MIT |
def extract_program(result: str, last_only=True):
"""
extract the program after "```python", and before "```"
"""
program = ""
start = False
for line in result.split("\n"):
if line.startswith("```python"):
if last_only:
program = "" # only extract the last pro... |
extract the program after "```python", and before "```"
| extract_program | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/utils/parser.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/utils/parser.py | MIT |
def extract_program_output(pred_str):
"""
extract output between the last ```output\n...\n```
"""
if "```output" not in pred_str:
return ""
if '```output' in pred_str:
pred_str = pred_str.split('```output')[-1]
if '```' in pred_str:
pred_str = pred_str.split('```')[0]
... |
extract output between the last ```output
...
```
| extract_program_output | python | deepseek-ai/DeepSeek-Coder | Evaluation/PAL-Math/utils/parser.py | https://github.com/deepseek-ai/DeepSeek-Coder/blob/master/Evaluation/PAL-Math/utils/parser.py | MIT |
def query_table_rows(repo_url, readme_path, table_id, head_num=1):
'''
Use BeautifulSoup to parse the HTML content of a table in a GitHub README.md file
return the number of rows in the table
'''
# make a GET request to the raw content URL of the README.md file
raw_url = f'{repo_url}/raw/main/{r... |
Use BeautifulSoup to parse the HTML content of a table in a GitHub README.md file
return the number of rows in the table
| query_table_rows | python | RenzeLou/awesome-instruction-learning | count_number.py | https://github.com/RenzeLou/awesome-instruction-learning/blob/master/count_number.py | MIT |
def __init__(self):
"""
Mask refinement module
Please refer SiamMask (Appendix A)
https://arxiv.org/abs/1812.05050
"""
super(Refine, self).__init__()
self.v0 = nn.Sequential(nn.Conv2d(64, 16, 3, padding=1), nn.ReLU(),
nn.Conv2d(16, 4, 3,... |
Mask refinement module
Please refer SiamMask (Appendix A)
https://arxiv.org/abs/1812.05050
| __init__ | python | zllrunning/video-object-removal | get_mask/models/custom.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/models/custom.py | MIT |
def resnet34(pretrained=False, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])... | Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet34 | python | zllrunning/video-object-removal | get_mask/models/resnet.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/models/resnet.py | MIT |
def corner2center(corner):
"""
:param corner: Corner or np.array 4*N
:return: Center or 4 np.array N
"""
if isinstance(corner, Corner):
x1, y1, x2, y2 = corner
return Center((x1 + x2) * 0.5, (y1 + y2) * 0.5, (x2 - x1), (y2 - y1))
else:
x1, y1, x2, y2 = corner[0], corner[1... |
:param corner: Corner or np.array 4*N
:return: Center or 4 np.array N
| corner2center | python | zllrunning/video-object-removal | get_mask/utils/bbox_helper.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/bbox_helper.py | MIT |
def center2corner(center):
"""
:param center: Center or np.array 4*N
:return: Corner or np.array 4*N
"""
if isinstance(center, Center):
x, y, w, h = center
return Corner(x - w * 0.5, y - h * 0.5, x + w * 0.5, y + h * 0.5)
else:
x, y, w, h = center[0], center[1], center[2]... |
:param center: Center or np.array 4*N
:return: Corner or np.array 4*N
| center2corner | python | zllrunning/video-object-removal | get_mask/utils/bbox_helper.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/bbox_helper.py | MIT |
def remove_prefix(state_dict, prefix):
''' Old style model is stored with all names of parameters share common prefix 'module.' '''
logger.info('remove prefix \'{}\''.format(prefix))
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.it... | Old style model is stored with all names of parameters share common prefix 'module.' | remove_prefix | python | zllrunning/video-object-removal | get_mask/utils/load_helper.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/load_helper.py | MIT |
def set_tracker(self, path, tracker_names):
"""
Args:
path: path to tracker results,
tracker_names: list of tracker name
"""
self.tracker_path = path
self.tracker_names = tracker_names |
Args:
path: path to tracker results,
tracker_names: list of tracker name
| set_tracker | python | zllrunning/video-object-removal | get_mask/utils/pysot/datasets/dataset.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/datasets/dataset.py | MIT |
def load_tracker(self, path, tracker_names=None, store=True):
"""
Args:
path(str): path to result
tracker_name(list): name of tracker
"""
if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x... |
Args:
path(str): path to result
tracker_name(list): name of tracker
| load_tracker | python | zllrunning/video-object-removal | get_mask/utils/pysot/datasets/video.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/datasets/video.py | MIT |
def create_dataset(**kwargs):
"""
Args:
name: dataset name 'VOT2018', 'VOT2016'
dataset_root: dataset root
Return:
dataset
"""
assert 'name' in kwargs, "should provide dataset name"
name = kwargs['name']
if 'VOT2018' == name or ... |
Args:
name: dataset name 'VOT2018', 'VOT2016'
dataset_root: dataset root
Return:
dataset
| create_dataset | python | zllrunning/video-object-removal | get_mask/utils/pysot/datasets/__init__.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/datasets/__init__.py | MIT |
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
ret: dict of results
"""
if eval_trackers is None:
eval_trackers = self.dataset.tracker_names
if isinstance(ev... |
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
ret: dict of results
| eval | python | zllrunning/video-object-removal | get_mask/utils/pysot/evaluation/ar_benchmark.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/evaluation/ar_benchmark.py | MIT |
def show_result(self, result, eao_result=None, show_video_level=False, helight_threshold=0.5):
"""pretty print result
Args:
result: returned dict from function eval
"""
tracker_name_len = max((max([len(x) for x in result.keys()])+2), 12)
if eao_result is not None:
... | pretty print result
Args:
result: returned dict from function eval
| show_result | python | zllrunning/video-object-removal | get_mask/utils/pysot/evaluation/ar_benchmark.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/evaluation/ar_benchmark.py | MIT |
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
eao: dict of results
"""
if eval_trackers is None:
eval_trackers = self.dataset.tracker_names
if isinstance(ev... |
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
eao: dict of results
| eval | python | zllrunning/video-object-removal | get_mask/utils/pysot/evaluation/eao_benchmark.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/evaluation/eao_benchmark.py | MIT |
def determine_thresholds(confidence, resolution=100):
"""choose threshold according to confidence
Args:
confidence: list or numpy array or numpy array
reolution: number of threshold to choose
Restures:
threshold: numpy array
"""
if isinstance(confidence, list):
conf... | choose threshold according to confidence
Args:
confidence: list or numpy array or numpy array
reolution: number of threshold to choose
Restures:
threshold: numpy array
| determine_thresholds | python | zllrunning/video-object-removal | get_mask/utils/pysot/utils/misc.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/utils/misc.py | MIT |
def calculate_failures(trajectory):
""" Calculate number of failures
Args:
trajectory: list of bbox
Returns:
num_failures: number of failures
failures: failures point in trajectory, start with 0
"""
failures = [i for i, x in zip(range(len(trajectory)), trajectory)
... | Calculate number of failures
Args:
trajectory: list of bbox
Returns:
num_failures: number of failures
failures: failures point in trajectory, start with 0
| calculate_failures | python | zllrunning/video-object-removal | get_mask/utils/pysot/utils/statistics.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/utils/statistics.py | MIT |
def calculate_accuracy(pred_trajectory, gt_trajectory,
burnin=0, ignore_unknown=True, bound=None):
"""Caculate accuracy socre as average overlap over the entire sequence
Args:
trajectory: list of bbox
gt_trajectory: list of bbox
burnin: number of frames that have to be ignored af... | Caculate accuracy socre as average overlap over the entire sequence
Args:
trajectory: list of bbox
gt_trajectory: list of bbox
burnin: number of frames that have to be ignored after the failure
ignore_unknown: ignore frames where the overlap is unknown
bound: bounding region
... | calculate_accuracy | python | zllrunning/video-object-removal | get_mask/utils/pysot/utils/statistics.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/utils/statistics.py | MIT |
def overlap_ratio(rect1, rect2):
'''Compute overlap ratio between two rects
Args
rect:2d array of N x [x,y,w,h]
Return:
iou
'''
# if rect1.ndim==1:
# rect1 = rect1[np.newaxis, :]
# if rect2.ndim==1:
# rect2 = rect2[np.newaxis, :]
left = np.maximum(rect1[:,0], ... | Compute overlap ratio between two rects
Args
rect:2d array of N x [x,y,w,h]
Return:
iou
| overlap_ratio | python | zllrunning/video-object-removal | get_mask/utils/pysot/utils/statistics.py | https://github.com/zllrunning/video-object-removal/blob/master/get_mask/utils/pysot/utils/statistics.py | MIT |
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h) | Wraps hidden states in new Variables, to detach them from their history. | repackage_hidden | python | zllrunning/video-object-removal | inpainting/utils.py | https://github.com/zllrunning/video-object-removal/blob/master/inpainting/utils.py | MIT |
def flow_to_rgb(flow):
"""
Convert flow into middlebury color code image
:param flow: optical flow map
:return: optical flow image in middlebury color
"""
u = flow[:, :, 0]
v = flow[:, :, 1]
maxu = -999.
maxv = -999.
minu = 999.
minv = 999.
idxUnknow = (abs(u) > UNKNOWN... |
Convert flow into middlebury color code image
:param flow: optical flow map
:return: optical flow image in middlebury color
| flow_to_rgb | python | zllrunning/video-object-removal | inpainting/utils.py | https://github.com/zllrunning/video-object-removal/blob/master/inpainting/utils.py | MIT |
def compute_color(u, v):
"""
compute optical flow color map
:param u: optical flow horizontal map
:param v: optical flow vertical map
:return: optical flow in color code
"""
[h, w] = u.shape
img = np.zeros([h, w, 3])
nanIdx = np.isnan(u) | np.isnan(v)
u[nanIdx] = 0
v[nanIdx] ... |
compute optical flow color map
:param u: optical flow horizontal map
:param v: optical flow vertical map
:return: optical flow in color code
| compute_color | python | zllrunning/video-object-removal | inpainting/utils.py | https://github.com/zllrunning/video-object-removal/blob/master/inpainting/utils.py | MIT |
def make_color_wheel():
"""
Generate color wheel according Middlebury color code
:return: Color wheel
"""
RY = 15
YG = 6
GC = 4
CB = 11
BM = 13
MR = 6
ncols = RY + YG + GC + CB + BM + MR
colorwheel = np.zeros([ncols, 3])
col = 0
# RY
colorwheel[0:RY, 0] = ... |
Generate color wheel according Middlebury color code
:return: Color wheel
| make_color_wheel | python | zllrunning/video-object-removal | inpainting/utils.py | https://github.com/zllrunning/video-object-removal/blob/master/inpainting/utils.py | MIT |
def _match(qs, ks):
"""Return True if regexes in qs match any window of strings in tuple ks."""
# compile regexes and force complete match
qts = tuple(map(lambda x: re.compile(x + "$"), qs))
for i in range(len(ks) - len(qs) + 1):
matches = [x.match(y) for x, y in zip(qts, ks[i:])]
if mat... | Return True if regexes in qs match any window of strings in tuple ks. | _match | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def hk_rms_norm(
x: jax.Array,
fixed_scale=False,
sharding=P(None),
) -> jax.Array:
"""Applies a unique LayerNorm to x with default settings."""
ln = RMSNorm(axis=-1, create_scale=not fixed_scale, sharding=sharding)
return ln(x) | Applies a unique LayerNorm to x with default settings. | hk_rms_norm | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def make_attention_mask(
query_input: jax.Array,
key_input: jax.Array,
pairwise_fn: Callable[..., Any] = jnp.multiply,
dtype: Any = jnp.bfloat16,
):
"""Mask-making helper for attention weights.
In case of 1d inputs (i.e., `[batch..., len_q]`, `[batch..., len_kv]`, the
attention weights will... | Mask-making helper for attention weights.
In case of 1d inputs (i.e., `[batch..., len_q]`, `[batch..., len_kv]`, the
attention weights will be `[batch..., heads, len_q, len_kv]` and this
function will produce `[batch..., 1, len_q, len_kv]`.
Args:
query_input: a batched, flat input of query_lengt... | make_attention_mask | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def __call__(
self,
inputs: jax.Array,
) -> jax.Array:
"""Computes a linear transform of the input."""
fprop_dtype = inputs.dtype
if not inputs.shape:
raise ValueError("Input must not be scalar.")
input_size = self.input_size = inputs.shape[-1]
o... | Computes a linear transform of the input. | __call__ | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def rotate_half(
x: jax.Array,
) -> jax.Array:
"""Obtain the rotated counterpart of each feature"""
x1, x2 = jnp.split(x, 2, axis=-1)
return jnp.concatenate((-x2, x1), axis=-1) | Obtain the rotated counterpart of each feature | rotate_half | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def __call__(
self,
inputs: jax.Array, # [B, T, D]
mask: jax.Array, # [B, 1, T, T] or [B, 1, 1, T]
padding_mask: Optional[jax.Array],
layer_memory: Optional[KVMemory],
) -> DecoderOutput:
"""Transforms input embedding sequences to output embedding sequences."""
... | Transforms input embedding sequences to output embedding sequences. | __call__ | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def __call__(
self,
tokens: jax.Array,
memory: Optional[Memory] = None,
*,
batch: Dict[str, jax.Array] = {},
last_hid_only: bool = False,
length: Optional[jax.Array] = None,
) -> LanguageModelOutput:
"""Forward pass, producing a sequence of logits."""
... | Forward pass, producing a sequence of logits. | __call__ | python | xai-org/grok-1 | model.py | https://github.com/xai-org/grok-1/blob/master/model.py | Apache-2.0 |
def format_help(self) -> str:
"""
Overrides ArgumentParser's format_help to dynamically generate a help message
for use with the `--help` flag.
"""
def help_for_group(group: SettingType) -> str:
actions = getattr(self, f"_{group.value}_group")._group_actions
... |
Overrides ArgumentParser's format_help to dynamically generate a help message
for use with the `--help` flag.
| format_help | python | jkwill87/mnamer | mnamer/argument.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/argument.py | MIT |
def omdb_title(
api_key: str,
id_imdb: str | None = None,
media: str | None = None,
title: str | None = None,
season: int | None = None,
episode: int | None = None,
year: int | None = None,
plot: str | None = None,
cache: bool = True,
) -> dict:
"""
Looks up media by id using... |
Looks up media by id using the Open Movie Database.
Online docs: http://www.omdbapi.com/#parameters
| omdb_title | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def omdb_search(
api_key: str,
query: str,
year: int | None = None,
media: str | None = None,
page: int = 1,
cache: bool = True,
) -> dict:
"""
Search for media using the Open Movie Database.
Online docs: http://www.omdbapi.com/#parameters.
"""
if page < 1 or page > 100:
... |
Search for media using the Open Movie Database.
Online docs: http://www.omdbapi.com/#parameters.
| omdb_search | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tmdb_find(
api_key: str,
external_source: str,
external_id: str,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
Search for The Movie Database objects using another DB's foreign key.
Note: language codes aren't checked on this end or by TMDb, so if you
e... |
Search for The Movie Database objects using another DB's foreign key.
Note: language codes aren't checked on this end or by TMDb, so if you
enter an invalid language code your search itself will succeed, but
certain fields like synopsis will just be empty.
Online docs: developers.themovie... | tmdb_find | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tmdb_movies(
api_key: str,
id_tmdb: str,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
Lookup a movie item using The Movie Database.
Online docs: developers.themoviedb.org/3/movies.
"""
url = f"https://api.themoviedb.org/3/movie/{id_tmdb}"
parameters =... |
Lookup a movie item using The Movie Database.
Online docs: developers.themoviedb.org/3/movies.
| tmdb_movies | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tmdb_search_movies(
api_key: str,
title: str,
year: int | str | None = None,
language: Language | None = None,
region: str | None = None,
adult: bool = False,
page: int = 1,
cache: bool = True,
) -> dict:
"""
Search for movies using The Movie Database.
Online docs: devel... |
Search for movies using The Movie Database.
Online docs: developers.themoviedb.org/3/search/search-movies.
| tmdb_search_movies | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_login(api_key: str | None) -> str:
"""
Logs into TVDb using the provided api key.
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login.
"""
url = "https://api.thetvdb.com/login"
body = {"apikey":... |
Logs into TVDb using the provided api key.
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login.
| tvdb_login | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_refresh_token(token: str) -> str:
"""
Refreshes JWT token.
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token.
"""
url = "https://api.thetvdb.com/refresh_token"
headers = {"Authorization": f"Bearer {token}"}
status, content = request_json(url, headers=headers, ... |
Refreshes JWT token.
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token.
| tvdb_refresh_token | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_episodes_id(
token: str,
id_tvdb: str,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
Returns the full information for a given episode id.
Online docs: https://api.thetvdb.com/swagger#!/Episodes.
"""
Language.ensure_valid_for_tvdb(language)
url = f... |
Returns the full information for a given episode id.
Online docs: https://api.thetvdb.com/swagger#!/Episodes.
| tvdb_episodes_id | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_series_id(
token: str,
id_tvdb: str,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
Returns a series records that contains all information known about a
particular series id.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id.
"""
Language... |
Returns a series records that contains all information known about a
particular series id.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id.
| tvdb_series_id | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_series_id_episodes(
token: str,
id_tvdb: str,
page: int = 1,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
All episodes for a given series.
Note: Paginated with 100 results per page.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id_episodes... |
All episodes for a given series.
Note: Paginated with 100 results per page.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id_episodes.
| tvdb_series_id_episodes | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvdb_search_series(
token: str,
series: str | None = None,
id_imdb: str | None = None,
id_zap2it: str | None = None,
language: Language | None = None,
cache: bool = True,
) -> dict:
"""
Allows the user to search for a series based on the following parameters.
Online docs: https:... |
Allows the user to search for a series based on the following parameters.
Online docs: https://api.thetvdb.com/swagger#!/Search/get_search_series
Note: results a maximum of 100 entries per page, no option for pagination.
| tvdb_search_series | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_show(
id_tvmaze: str,
embed_episodes: bool = False,
cache: bool = False,
attempt: int = 1,
):
"""
Retrieve all primary information for a given show.
Online docs: https://www.tvmaze.com/api#show-main-information
"""
url = f"http://api.tvmaze.com/shows/{id_tvmaze}"
para... |
Retrieve all primary information for a given show.
Online docs: https://www.tvmaze.com/api#show-main-information
| tvmaze_show | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_show_search(query: str, cache: bool = True, attempt: int = 1) -> dict:
"""
Search through all the shows in the database by the show's name. A fuzzy
algorithm is used (with a fuzziness value of 2), meaning that shows will be
found even if your query contains small typos. Results are returned i... |
Search through all the shows in the database by the show's name. A fuzzy
algorithm is used (with a fuzziness value of 2), meaning that shows will be
found even if your query contains small typos. Results are returned in order
of relevancy (best matches on top) and contain each show's full information.
... | tvmaze_show_search | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_show_single_search(query: str, cache: bool = True, attempt: int = 1) -> dict:
"""
Singlesearch endpoint either returns exactly one result, or no result at
all. This endpoint is also forgiving of typos, but less so than the regular
search (with a fuzziness of 1 instead of 2), to reduce the cha... |
Singlesearch endpoint either returns exactly one result, or no result at
all. This endpoint is also forgiving of typos, but less so than the regular
search (with a fuzziness of 1 instead of 2), to reduce the chance of a false
positive.
Online docs: https://www.tvmaze.com/api#show-single-search
... | tvmaze_show_single_search | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_show_lookup(
id_imdb: str | None = None,
id_tvdb: str | None = None,
cache: bool = True,
attempt: int = 1,
) -> dict:
"""
If you already know a show's tvrage, thetvdb or IMDB ID, you can use this
endpoint to find this exact show on TVmaze.
Online docs: https://www.tvmaze.com/... |
If you already know a show's tvrage, thetvdb or IMDB ID, you can use this
endpoint to find this exact show on TVmaze.
Online docs: https://www.tvmaze.com/api#show-lookup
| tvmaze_show_lookup | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_show_episodes_list(
id_tvmaze: str,
include_specials: bool = False,
cache: bool = True,
attempt: int = 1,
) -> dict:
"""
A complete list of episodes for the given show. Episodes are returned in
their airing order, and include full episode information. By default,
specials are ... |
A complete list of episodes for the given show. Episodes are returned in
their airing order, and include full episode information. By default,
specials are not included in the list.
Online docs: https://www.tvmaze.com/api#show-episode-list
| tvmaze_show_episodes_list | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_episodes_by_date(
id_tvmaze: str,
air_date: datetime.date | str,
cache: bool = True,
attempt: int = 1,
) -> dict:
"""
Retrieves all episodes from this show that have aired on a specific date.
Useful for daily shows that don't adhere to a common season numbering.
Online docs: ... |
Retrieves all episodes from this show that have aired on a specific date.
Useful for daily shows that don't adhere to a common season numbering.
Online docs: https://www.tvmaze.com/api#episodes-by-date
| tvmaze_episodes_by_date | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def tvmaze_episode_by_number(
id_tvmaze: str,
season: int | None,
episode: int | None,
cache: bool = True,
attempt: int = 1,
) -> dict:
"""
Retrieve one specific episode from this show given its season number and
episode number.
Online docs: https://www.tvmaze.com/api#episode-by-num... |
Retrieve one specific episode from this show given its season number and
episode number.
Online docs: https://www.tvmaze.com/api#episode-by-number
| tvmaze_episode_by_number | python | jkwill87/mnamer | mnamer/endpoints.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/endpoints.py | MIT |
def update(self, metadata: Metadata):
"""Overlays all none value from another Metadata instance."""
for field in dataclasses.asdict(self).keys():
value = getattr(metadata, field)
if value is None:
continue
super().__setattr__(field, value) | Overlays all none value from another Metadata instance. | update | python | jkwill87/mnamer | mnamer/metadata.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/metadata.py | MIT |
def provider_factory(provider: ProviderType, settings: SettingStore) -> Provider:
"""Factory function for DB Provider concrete classes."""
provider_cls = {
ProviderType.TMDB: Tmdb,
ProviderType.TVDB: Tvdb,
ProviderType.TVMAZE: TvMaze,
ProviderType.OMDB: Om... | Factory function for DB Provider concrete classes. | provider_factory | python | jkwill87/mnamer | mnamer/providers.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/providers.py | MIT |
def api_for(self, media_type: MediaType | None) -> ProviderType | None:
"""Returns the ProviderType for a given media type."""
if media_type:
return getattr(self, f"{media_type.value}_api")
return None | Returns the ProviderType for a given media type. | api_for | python | jkwill87/mnamer | mnamer/setting_store.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/setting_store.py | MIT |
def api_key_for(self, provider_type: ProviderType) -> str | None:
"""Returns the API key for a provider type."""
if provider_type:
return getattr(self, f"api_key_{provider_type.value}")
return None | Returns the API key for a provider type. | api_key_for | python | jkwill87/mnamer | mnamer/setting_store.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/setting_store.py | MIT |
def populate_paths(cls: Type[Target], settings: SettingStore) -> list[Target]:
"""Creates a list of Target objects for media files found in paths."""
file_paths = crawl_in(settings.targets, settings.recurse)
file_paths = filter_blacklist(file_paths, settings.ignore)
file_paths = filter_c... | Creates a list of Target objects for media files found in paths. | populate_paths | python | jkwill87/mnamer | mnamer/target.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/target.py | MIT |
def destination(self) -> Path:
"""
The destination Path for the target based on its metadata and user
preferences.
"""
if self.directory:
dir_head_ = format(self.metadata, str(self.directory))
dir_head_ = str_sanitize(dir_head_)
dir_head = Path... |
The destination Path for the target based on its metadata and user
preferences.
| destination | python | jkwill87/mnamer | mnamer/target.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/target.py | MIT |
def query(self) -> list[Metadata]:
"""Queries the target's respective media provider for metadata."""
results = self._provider.search(self.metadata)
if not results:
return []
seen = set()
response = []
for idx, result in enumerate(results, start=1):
... | Queries the target's respective media provider for metadata. | query | python | jkwill87/mnamer | mnamer/target.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/target.py | MIT |
def relocate(self) -> None:
"""Performs the action of renaming and/or moving a file."""
destination_path = Path(self.destination).resolve()
destination_path.parent.mkdir(parents=True, exist_ok=True)
try:
move(str(self.source), destination_path)
except OSError: # prag... | Performs the action of renaming and/or moving a file. | relocate | python | jkwill87/mnamer | mnamer/target.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/target.py | MIT |
def configure(settings: SettingStore):
"""Sets class variables using a settings instance."""
global verbose, no_style
verbose = settings.verbose
no_style = settings.no_style | Sets class variables using a settings instance. | configure | python | jkwill87/mnamer | mnamer/tty.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/tty.py | MIT |
def metadata_prompt(matches: list[Metadata]) -> Metadata: # pragma: no cover
"""Prompts user to choose a match from a list of matches."""
msg("select match")
selector = SelectOne([*matches, *_abort_helpers()], **_chars())
choice = selector.prompt()
if isinstance(choice, (MnamerAbortException, Mname... | Prompts user to choose a match from a list of matches. | metadata_prompt | python | jkwill87/mnamer | mnamer/tty.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/tty.py | MIT |
def metadata_guess(metadata: Metadata) -> Metadata: # pragma: no cover
"""Prompts user to confirm a single match."""
label = str(metadata)
if no_style:
label += " (best guess)"
else:
label += style_format(" (best guess)", "blue")
option = ChoiceHelper(metadata, label)
selector =... | Prompts user to confirm a single match. | metadata_guess | python | jkwill87/mnamer | mnamer/tty.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/tty.py | MIT |
def clean_dict(target_dict: dict, whitelist=None) -> dict:
"""Convenience function that removes a dicts keys that have falsy values."""
return {
str(k).strip(): str(v).strip()
for k, v in target_dict.items()
if v not in (None, Ellipsis, [], (), "") and (not whitelist or k in whitelist)
... | Convenience function that removes a dicts keys that have falsy values. | clean_dict | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def crawl_in(file_paths: list[Path], recurse: bool = False) -> list[Path]:
"""Looks for files amongst or within paths provided."""
found_files = set()
for file_path in file_paths:
if not file_path.exists():
continue
if file_path.is_file():
found_files.add(Path(file_pa... | Looks for files amongst or within paths provided. | crawl_in | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def crawl_out(filename: str | Path | PurePath) -> Path | None:
"""Looks for a file in the home directory and each directory up from cwd."""
working_dir = Path.cwd()
while True:
parent_dir = working_dir.parent
if parent_dir == working_dir: # e.g. fs root or error
break
ta... | Looks for a file in the home directory and each directory up from cwd. | crawl_out | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def filename_replace(filename: str, replacements: dict[str, str]) -> str:
"""Replaces keys in replacements dict with their values."""
base, container = splitext(filename)
base = str_replace(base, replacements)
return base + container | Replaces keys in replacements dict with their values. | filename_replace | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def filter_blacklist(paths: list[Path], blacklist: list[str]) -> list[Path]:
"""Filters (set difference) paths by a collection of regex pattens."""
return [
path.absolute()
for path in paths
if not any(
re.search(pattern, str(path), re.IGNORECASE)
for pattern in b... | Filters (set difference) paths by a collection of regex pattens. | filter_blacklist | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def filter_containers(
file_paths: list[Path], valid_containers: list[str]
) -> list[Path]:
"""Filters (set intersection) a collection of containers."""
valid_containers = normalize_containers(valid_containers)
return [
file_path
for file_path in file_paths
if not valid_container... | Filters (set intersection) a collection of containers. | filter_containers | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def findall(s, ss) -> Iterator[int]:
"""Yields indexes of all start positions of substring matches in string."""
i = s.find(ss)
while i != -1:
yield i
i = s.find(ss, i + 1) | Yields indexes of all start positions of substring matches in string. | findall | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def fn_pipe(*fn_list: Callable) -> Callable:
"""Pipes a list of function calls into one."""
def resolver(x):
for fn in fn_list:
x = fn(x)
return x
return resolver | Pipes a list of function calls into one. | fn_pipe | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def is_subtitle(container: str | Path | None) -> bool:
"""Returns True if container is a subtitle container."""
if not container:
return False
return str(container).endswith(tuple(SUBTITLE_CONTAINERS)) | Returns True if container is a subtitle container. | is_subtitle | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def get_session() -> requests_cache.CachedSession:
"""Convenience function that returns request-cache session singleton."""
def make_session():
session = requests_cache.CachedSession(
cache_name=str(CACHE_PATH),
extension=".sqlite",
expire_after=518_400, # 6 days
... | Convenience function that returns request-cache session singleton. | get_session | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def get_filesize(path: Path) -> str:
"""Returns the human-readable filesize for a given path."""
size = float(getsize(path))
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1024.0:
break
size /= 1024.0
else:
return "undetermined size"
return f"{size:.{2}f}{un... | Returns the human-readable filesize for a given path. | get_filesize | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def normalize_container(container: str) -> str:
"""Ensures all containers begin with a dot."""
assert container
if container and container[0] != ".":
container = f".{container}"
return container.lower() | Ensures all containers begin with a dot. | normalize_container | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def parse_date(value: str | dt.date | dt.datetime) -> dt.date:
"""Converts an ambiguously formatted date type into a date object."""
if isinstance(value, str):
value = value.replace("/", "-")
value = value.replace(".", "-")
value = dt.datetime.strptime(value, "%Y-%m-%d")
if isinstanc... | Converts an ambiguously formatted date type into a date object. | parse_date | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def request_json(
url,
parameters: dict | list | None = None,
body: dict | None = None,
headers: dict | None = None,
cache: bool = True,
) -> tuple[int, dict]:
"""
Queries a url for json data.
Note: Requests are cached using requests_cached for a week, this is done
transparently by ... |
Queries a url for json data.
Note: Requests are cached using requests_cached for a week, this is done
transparently by using the package's monkey patching.
| request_json | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def str_sanitize(filename: str) -> str:
"""Removes illegal filename characters and condenses whitespace."""
base, container = splitext(filename)
if is_subtitle(container):
base = base.rstrip(".")
base, container_prefix = splitext(base)
container = container_prefix + container
bas... | Removes illegal filename characters and condenses whitespace. | str_sanitize | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def str_scenify(filename: str) -> str:
"""Replaces non ascii-alphanumerics with dots."""
filename = normalize("NFKD", filename)
filename.encode("ascii", "ignore")
filename = re.sub(r"\s+", ".", filename)
filename = re.sub(r"[^.\d\w/]", "", filename)
filename = re.sub(r"\.+", ".", filename)
r... | Replaces non ascii-alphanumerics with dots. | str_scenify | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def str_title_case(s: str) -> str:
"""Attempts to intelligently apply title case transformations to strings."""
if not s:
return s
lowercase_exceptions = {
"a",
"an",
"and",
"as",
"at",
"but",
"by",
"de",
"des",
"du",
... | Attempts to intelligently apply title case transformations to strings. | str_title_case | python | jkwill87/mnamer | mnamer/utils.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/utils.py | MIT |
def main(): # pragma: no cover
"""
A wrapper for the program entrypoint that formats uncaught exceptions in a
crash report template.
"""
settings = SettingStore()
try:
settings.load()
except MnamerException as e:
tty.error(e)
raise SystemExit(2)
try:
fron... |
A wrapper for the program entrypoint that formats uncaught exceptions in a
crash report template.
| main | python | jkwill87/mnamer | mnamer/__main__.py | https://github.com/jkwill87/mnamer/blob/master/mnamer/__main__.py | MIT |
def e2e_run(capsys, request):
"""Runs main with provided arguments and returns stdout."""
def fn(*args):
Target.reset_providers()
out = ""
code = 0
for arg in args:
sys.argv.append(arg)
try:
settings = SettingStore()
settings.load()
... | Runs main with provided arguments and returns stdout. | e2e_run | python | jkwill87/mnamer | tests/e2e/conftest.py | https://github.com/jkwill87/mnamer/blob/master/tests/e2e/conftest.py | MIT |
def tvdb_token():
"""Calls mnamer.endpoints.tvdb_login then returns cached token."""
if not hasattr(tvdb_token, "token"):
from mnamer.endpoints import tvdb_login
tvdb_token.token = tvdb_login(Tvdb.api_key)
return tvdb_token.token | Calls mnamer.endpoints.tvdb_login then returns cached token. | tvdb_token | python | jkwill87/mnamer | tests/network/test_endpoints__tvdb.py | https://github.com/jkwill87/mnamer/blob/master/tests/network/test_endpoints__tvdb.py | MIT |
def get_git_root(file_path):
"""
Attempts to get the root of the git repository for the given file.
Parameters:
file_path (str): The path of the file to determine the git root for.
Returns:
str: The absolute path to the git repository root if found,
otherwise None.
"""... |
Attempts to get the root of the git repository for the given file.
Parameters:
file_path (str): The path of the file to determine the git root for.
Returns:
str: The absolute path to the git repository root if found,
otherwise None.
| get_git_root | python | NVIDIA/nv-ingest | api/api_tests/utilities_for_test.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/utilities_for_test.py | Apache-2.0 |
def find_root_by_pattern(pattern, start_dir=None):
"""
Backtracks up the directory tree looking for the first directory
where the specified pattern exists.
Parameters:
pattern (str): The relative path to check for (e.g., "data/test.pdf").
start_dir (str, optional): The starting director... |
Backtracks up the directory tree looking for the first directory
where the specified pattern exists.
Parameters:
pattern (str): The relative path to check for (e.g., "data/test.pdf").
start_dir (str, optional): The starting directory. Defaults to the current working directory.
Returns... | find_root_by_pattern | python | NVIDIA/nv-ingest | api/api_tests/utilities_for_test.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/api_tests/utilities_for_test.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.