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
1,267
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/io/async_plugin.py
40,42
24,66
save_checkpoint
AsyncCheckpointIO
43,58
42,58
class AsyncCheckpointIO(_WrappingCheckpointIO): """``AsyncCheckpointIO`` enables saving the checkpoints asynchronously in a thread. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: checkpoint_io: A checkpoint IO plugin that is used as the basis for async ch...
class AsyncCheckpointIO(_WrappingCheckpointIO): """``AsyncCheckpointIO`` enables saving the checkpoints asynchronously in a thread. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: checkpoint_io: A checkpoint IO plugin that is used as the basis for async ch...
def _save_checkpoint(*args: Any, **kwargs: Any) -> None: try: assert self.checkpoint_io is not None self.checkpoint_io.save_checkpoint(*args, **kwargs) except BaseException as ex: self._error = ex self._executor.submit(_save_check...
"""Uses the ``ThreadPoolExecutor`` to save the checkpoints using the base ``checkpoint_io``.""" def _save_checkpoint(*args: Any, **kwargs: Any) -> None: try: assert self.checkpoint_io is not None self.checkpoint_io.save_checkpoint(*args, **kwargs) ...
50
310
160
470
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,268
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/io/wrapper.py
68,70
21,73
load_checkpoint
_WrappingCheckpointIO
71,73
70,73
class _WrappingCheckpointIO(CheckpointIO): """``_WrappingCheckpointIO`` is a wrapper checkpoint_io that uses a base checkpoint_io to handle checkpointing. Args: checkpoint_io: A checkpoint IO plugin that is used as the basis. """ def __init__(self, checkpoint_io: Optional["CheckpointIO"] = No...
class _WrappingCheckpointIO(CheckpointIO): """``_WrappingCheckpointIO`` is a wrapper checkpoint_io that uses a base checkpoint_io to handle checkpointing. Args: checkpoint_io: A checkpoint IO plugin that is used as the basis. """ def __init__(self, checkpoint_io: Optional["CheckpointIO"] = No...
assert self.checkpoint_io is not None return self.checkpoint_io.load_checkpoint(*args, **kwargs)
"""Uses the base ``checkpoint_io`` to load the checkpoint.""" assert self.checkpoint_io is not None return self.checkpoint_io.load_checkpoint(*args, **kwargs)
8
636
34
670
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,269
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/layer_sync.py
59,61
36,94
revert
TorchSyncBatchNorm
70,94
61,94
class TorchSyncBatchNorm(LayerSync): """A plugin that wraps all batch normalization layers of a model with synchronization logic for multiprocessing. This plugin has no effect in single-device operation. """ @override def apply(self, model: Module) -> Module: """Add global batchnorm for a...
class TorchSyncBatchNorm(LayerSync): """A plugin that wraps all batch normalization layers of a model with synchronization logic for multiprocessing. This plugin has no effect in single-device operation. """ @override def apply(self, model: Module) -> Module: """Add global batchnorm for a...
# Code adapted from https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547 # Original author: Kapil Yedidi (@kapily) converted_module = model if isinstance(model, torch.nn.modules.batchnorm.SyncBatchNorm): # Unfortunately, LayerSync does not store the original...
"""Convert the wrapped batchnorm layers back to regular batchnorm layers. Args: model: Reference to the current LightningModule Return: LightningModule with regular batchnorm layers that will no longer sync across processes. """ # Code adapted from http...
85
273
350
623
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,270
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/layer_sync.py
95,97
94,102
_check_input_dim
_BatchNormXd
97,102
97,102
class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): @override def _check_input_dim(self, input: Tensor) -> None: FILL_FUNC_BODY
class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): @override def _check_input_dim(self, input: Tensor) -> None: FILL_FUNC_BODY
# The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc # is this method that is overwritten by the subclass. # Here, we are bypassing some tensor sanity checks and trusting that the user # provides the right input dimensions at inference. return
# The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc # is this method that is overwritten by the subclass. # Here, we are bypassing some tensor sanity checks and trusting that the user # provides the right input dimensions at inference. return
42
57
80
137
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,271
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/amp.py
58,60
28,132
pre_backward
MixedPrecision
60,64
60,64
class MixedPrecision(Precision): """Plugin for Automatic Mixed Precision (AMP) training with ``torch.autocast``. Args: precision: Whether to use ``torch.float16`` (``'16-mixed'``) or ``torch.bfloat16`` (``'bf16-mixed'``). device: The device for ``torch.autocast``. scaler: An optional :c...
class MixedPrecision(Precision): """Plugin for Automatic Mixed Precision (AMP) training with ``torch.autocast``. Args: precision: Whether to use ``torch.float16`` (``'16-mixed'``) or ``torch.bfloat16`` (``'bf16-mixed'``). device: The device for ``torch.autocast``. scaler: An optional :c...
if self.scaler is not None: tensor = self.scaler.scale(tensor) return super().pre_backward(tensor, module)
if self.scaler is not None: tensor = self.scaler.scale(tensor) return super().pre_backward(tensor, module)
11
1,347
43
1,390
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
1,272
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/deepspeed.py
82,84
40,149
tensor_init_context
DeepSpeedPrecision
84,88
84,88
class DeepSpeedPrecision(Precision): """Precision plugin for DeepSpeed integration. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: precision: Full precision (32-true), half precision (16-true, bf16-true) or mixed precision (16-mixed, bf16-mixe...
class DeepSpeedPrecision(Precision): """Precision plugin for DeepSpeed integration. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: precision: Full precision (32-true), half precision (16-true, bf16-true) or mixed precision (16-mixed, bf16-mixe...
if "true" not in self.precision: return nullcontext() return _DtypeContextManager(self._desired_dtype)
if "true" not in self.precision: return nullcontext() return _DtypeContextManager(self._desired_dtype)
9
1,197
41
1,238
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,273
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/double.py
58,60
30,63
convert_input
DoublePrecision
60,63
60,63
class DoublePrecision(Precision): """Plugin for training with double (``torch.float64``) precision.""" precision: Literal["64-true"] = "64-true" @override def convert_module(self, module: nn.Module) -> nn.Module: return module.double() @override def tensor_init_context(self) -> Contex...
class DoublePrecision(Precision): """Plugin for training with double (``torch.float64``) precision.""" precision: Literal["64-true"] = "64-true" @override def convert_module(self, module: nn.Module) -> nn.Module: return module.double() @override def tensor_init_context(self) -> Contex...
return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.double)
return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.double)
5
270
41
311
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,274
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/double.py
90,91
63,120
training_step
LightningDoublePrecisionModule
91,96
91,96
class LightningDoublePrecisionModule(_DeviceDtypeModuleMixin, nn.Module): """LightningModule wrapper which converts incoming floating point data in ``*_step`` and ``forward`` to double (``torch.float64``) precision. .. deprecated:: Use :meth:`~lightning.pytorch.core.hooks.ModelHooks.configure_model` instea...
class LightningDoublePrecisionModule(_DeviceDtypeModuleMixin, nn.Module): """LightningModule wrapper which converts incoming floating point data in ``*_step`` and ``forward`` to double (``torch.float64``) precision. .. deprecated:: Use :meth:`~lightning.pytorch.core.hooks.ModelHooks.configure_model` instea...
return self.module.training_step( *LightningDoublePrecisionModule._move_float_tensors_to_double(args), **LightningDoublePrecisionModule._move_float_tensors_to_double(kwargs), )
return self.module.training_step( *LightningDoublePrecisionModule._move_float_tensors_to_double(args), **LightningDoublePrecisionModule._move_float_tensors_to_double(kwargs), )
5
767
68
835
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,275
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/fsdp.py
85,87
34,178
mixed_precision_config
FSDPPrecision
87,111
87,111
class FSDPPrecision(Precision): """Precision plugin for training with Fully Sharded Data Parallel (FSDP). .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: precision: Full precision (32-true), half precision (16-true, bf16-true) or mixed precisio...
class FSDPPrecision(Precision): """Precision plugin for training with Fully Sharded Data Parallel (FSDP). .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: precision: Full precision (32-true), half precision (16-true, bf16-true) or mixed precisio...
from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision if self.precision == "16-mixed": param_dtype = torch.float32 reduce_dtype = buffer_dtype = torch.float16 elif self.precision == "bf16-mixed": param_dtype = to...
from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision if self.precision == "16-mixed": param_dtype = torch.float32 reduce_dtype = buffer_dtype = torch.float16 elif self.precision == "bf16-mixed": param_dtype = to...
80
1,666
357
2,023
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,276
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/half.py
53,56
27,71
forward_context
HalfPrecision
61,68
56,68
class HalfPrecision(Precision): """Plugin for training with half precision. Args: precision: Whether to use ``torch.float16`` (``'16-true'``) or ``torch.bfloat16`` (``'bf16-true'``). """ precision: Literal["bf16-true", "16-true"] = "16-true" def __init__(self, precision: Literal["bf16-tr...
class HalfPrecision(Precision): """Plugin for training with half precision. Args: precision: Whether to use ``torch.float16`` (``'16-true'``) or ``torch.bfloat16`` (``'bf16-true'``). """ precision: Literal["bf16-true", "16-true"] = "16-true" def __init__(self, precision: Literal["bf16-tr...
default_dtype = torch.get_default_dtype() torch.set_default_dtype(self._desired_input_dtype) try: yield finally: torch.set_default_dtype(default_dtype)
"""A context manager to change the default tensor type when tensors get created during the module's forward. See: :meth:`torch.set_default_tensor_type` """ default_dtype = torch.get_default_dtype() torch.set_default_dtype(self._desired_input_dtype) try: yiel...
8
455
75
530
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,277
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/plugins/precision/precision.py
124,131
32,190
_clip_gradients
Precision
131,143
131,143
class Precision(FabricPrecision, CheckpointHooks): """Base class for all plugins handling the precision-specific parts of the training. The class attribute precision must be overwritten in child classes. The default value reflects fp32 training. """ def connect( self, model: Module, optimizer...
class Precision(FabricPrecision, CheckpointHooks): """Base class for all plugins handling the precision-specific parts of the training. The class attribute precision must be overwritten in child classes. The default value reflects fp32 training. """ def connect( self, model: Module, optimizer...
if not isinstance(model, pl.LightningModule) or not model.automatic_optimization: # the configuration validator disallows clipping on manual return call._call_lightning_module_hook( model.trainer, "configure_gradient_clipping", optimizer, ...
if not isinstance(model, pl.LightningModule) or not model.automatic_optimization: # the configuration validator disallows clipping on manual return call._call_lightning_module_hook( model.trainer, "configure_gradient_clipping", optimizer, ...
23
1,666
120
1,786
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,278
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/profilers/advanced.py
65,67
30,100
start
AdvancedProfiler
67,71
67,71
class AdvancedProfiler(Profiler): """This profiler uses Python's cProfiler to record more detailed information about time spent in each function call recorded during a given action. The output is quite verbose and you should only use this if you want very detailed reports. """ def __init__( ...
class AdvancedProfiler(Profiler): """This profiler uses Python's cProfiler to record more detailed information about time spent in each function call recorded during a given action. The output is quite verbose and you should only use this if you want very detailed reports. """ def __init__( ...
if action_name not in self.profiled_actions: self.profiled_actions[action_name] = cProfile.Profile() self.profiled_actions[action_name].enable()
if action_name not in self.profiled_actions: self.profiled_actions[action_name] = cProfile.Profile() self.profiled_actions[action_name].enable()
9
776
57
833
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,279
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/profilers/profiler.py
105,106
28,152
describe
Profiler
107,118
106,118
class Profiler(ABC): """If you wish to write a custom profiler, you should inherit from this class.""" def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename ...
class Profiler(ABC): """If you wish to write a custom profiler, you should inherit from this class.""" def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename ...
# users might call `describe` directly as the profilers can be used by themselves. # to allow this, we open and close the files within this function by calling `_prepare_streams` and `teardown` # manually instead of letting the `Trainer` do it through `setup` and `teardown` self._prepare...
"""Logs a profile report after the conclusion of run.""" # users might call `describe` directly as the profilers can be used by themselves. # to allow this, we open and close the files within this function by calling `_prepare_streams` and `teardown` # manually instead of letting the `Tr...
64
1,155
167
1,322
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,281
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/profilers/pytorch.py
70,71
46,102
_start_recording_forward
RegisterRecordFunction
71,77
71,77
class RegisterRecordFunction: """While profiling autograd operations, this class will add labels for module names around the forward function. The Lightning PyTorch Profiler will activate this feature automatically. It can be deactivated as follows: Example:: from lightning.pytorch.profilers impor...
class RegisterRecordFunction: """While profiling autograd operations, this class will add labels for module names around the forward function. The Lightning PyTorch Profiler will activate this feature automatically. It can be deactivated as follows: Example:: from lightning.pytorch.profilers impor...
# Add [pl][module] in name for pytorch profiler to recognize record = record_function("[pl][module]" + record_name) record.__enter__() self._records[record_name] = record return input
# Add [pl][module] in name for pytorch profiler to recognize record = record_function("[pl][module]" + record_name) record.__enter__() self._records[record_name] = record return input
21
597
68
665
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,282
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/profilers/pytorch.py
165,166
102,217
_step
ScheduleWrapper
166,180
166,180
class ScheduleWrapper: """This class is used to override the schedule logic from the profiler and perform recording for both `training_step`, `validation_step`.""" def __init__(self, schedule: Callable) -> None: if not _KINETO_AVAILABLE: raise ModuleNotFoundError("You are trying to use ...
class ScheduleWrapper: """This class is used to override the schedule logic from the profiler and perform recording for both `training_step`, `validation_step`.""" def __init__(self, schedule: Callable) -> None: if not _KINETO_AVAILABLE: raise ModuleNotFoundError("You are trying to use ...
if self.is_training: self._num_training_step += 1 elif self.is_validating: assert self._start_action_name is not None if self._start_action_name.endswith("on_fit_start"): if self._num_training_step > 0: self._num_validation_step += ...
if self.is_training: self._num_training_step += 1 elif self.is_validating: assert self._start_action_name is not None if self._start_action_name.endswith("on_fit_start"): if self._num_training_step > 0: self._num_validation_step += ...
35
1,138
160
1,298
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,283
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/profilers/simple.py
84,85
36,164
_make_report_extended
SimpleProfiler
85,100
85,100
class SimpleProfiler(Profiler): """This profiler simply records the duration of actions (in seconds) and reports the mean duration of each action and the total time spent over the entire training run.""" def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optio...
class SimpleProfiler(Profiler): """This profiler simply records the duration of actions (in seconds) and reports the mean duration of each action and the total time spent over the entire training run.""" def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optio...
total_duration = time.monotonic() - self.start_time report = [] for a, d in self.recorded_durations.items(): d_tensor = torch.tensor(d) len_d = len(d) sum_d = torch.sum(d_tensor).item() percentage_d = 100.0 * sum_d / total_duration re...
total_duration = time.monotonic() - self.start_time report = [] for a, d in self.recorded_durations.items(): d_tensor = torch.tensor(d) len_d = len(d) sum_d = torch.sum(d_tensor).item() percentage_d = 100.0 * sum_d / total_duration re...
51
1,511
197
1,708
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,284
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/serve/servable_module.py
74,76
8,95
serve_step
ServableModule
76,92
76,92
class ServableModule(ABC, torch.nn.Module): """The ServableModule provides a simple API to make your model servable. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Here is an example of how to use the ``ServableModule`` module. .. code-block:: python from...
class ServableModule(ABC, torch.nn.Module): """The ServableModule provides a simple API to make your model servable. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Here is an example of how to use the ``ServableModule`` module. .. code-block:: python from...
r"""Returns the predictions of your model as a dictionary. .. code-block:: python def serve_step(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: return {"predictions": self(x)} Args: args: The output from de-serializer functions provided by the ``con...
r"""Returns the predictions of your model as a dictionary. .. code-block:: python def serve_step(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: return {"predictions": self(x)} Args: args: The output from de-serializer functions provided by the ``con...
58
752
162
914
from abc import ABC, abstractmethod from typing import Any, Callable, Dict, Tuple import torch from torch import Tensor class ServableModule(ABC, torch.nn.Module): """The ServableModule provides a simple API to make your model servable. .. warning:: This is an :ref:`experimental <versioning:Experimental AP...
from abc import ABC, abstractmethod from typing import Any, Callable, Dict, Tuple import torch from torch import Tensor class ServableModule(ABC, torch.nn.Module): """The ServableModule provides a simple API to make your model servable. .. warning:: This is an :ref:`experimental <versioning:Experimental AP...
1,285
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/serve/servable_module_validator.py
142,144
28,178
_start_server
ServableModuleValidator
145,178
144,178
class ServableModuleValidator(Callback): """The ServableModuleValidator validates to validate a model correctly implement the ServableModule API. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Arguments: optimization: The format in which the model should be tes...
class ServableModuleValidator(Callback): """The ServableModuleValidator validates to validate a model correctly implement the ServableModule API. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Arguments: optimization: The format in which the model should be tes...
from fastapi import Body, FastAPI from uvicorn import run app = FastAPI() deserializers, serializers = servable_model.configure_serialization() # Note: This isn't the original version, but a copy. servable_model.eval() @app.get("/ping") def ping() -> b...
"""This method starts a server with a serve and ping endpoints.""" from fastapi import Body, FastAPI from uvicorn import run app = FastAPI() deserializers, serializers = servable_model.configure_serialization() # Note: This isn't the original version, but a copy. ...
88
1,490
318
1,808
import contextlib import logging import time from multiprocessing import Process from typing import Any, Dict, Literal, Optional import requests import torch from lightning_utilities.core.imports import RequirementCache from typing_extensions import override import lightning.pytorch as pl from lightning.pytorch.callb...
import contextlib import logging import time from multiprocessing import Process from typing import Any, Dict, Literal, Optional import requests import torch from lightning_utilities.core.imports import RequirementCache from typing_extensions import override import lightning.pytorch as pl from lightning.pytorch.callb...
1,287
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/strategies/ddp.py
423,425
422,434
on_after_inner_forward
_DDPForwardRedirection
425,430
425,430
class _DDPForwardRedirection(_ForwardRedirection): @override def on_after_inner_forward(self, wrapper_module: Module, original_module: "pl.LightningModule") -> None: FILL_FUNC_BODY @override def on_after_outer_forward(self, wrapper_module: Module, original_module: "pl.LightningModule") -> None: i...
class _DDPForwardRedirection(_ForwardRedirection): @override def on_after_inner_forward(self, wrapper_module: Module, original_module: "pl.LightningModule") -> None: FILL_FUNC_BODY @override def on_after_outer_forward(self, wrapper_module: Module, original_module: "pl.LightningModule") -> None: i...
# In manual_optimization, we need to prevent DDP reducer as # it is done manually in `LightningModule.manual_backward` if isinstance(wrapper_module, DistributedDataParallel) and not original_module.automatic_optimization: wrapper_module.require_backward_grad_sync = False
# In manual_optimization, we need to prevent DDP reducer as # it is done manually in `LightningModule.manual_backward` if isinstance(wrapper_module, DistributedDataParallel) and not original_module.automatic_optimization: wrapper_module.require_backward_grad_sync = False
26
147
87
234
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,289
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/strategies/launchers/multiprocessing.py
304,306
280,321
capture
_GlobalStateSnapshot
307,314
306,314
@dataclass class _GlobalStateSnapshot: """Captures a hand-selected set of (global) variables in modules and provides a way to restore them. It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state across process boundaries when launching processes...
@dataclass class _GlobalStateSnapshot: """Captures a hand-selected set of (global) variables in modules and provides a way to restore them. It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state across process boundaries when launching processes...
return cls( use_deterministic_algorithms=torch.are_deterministic_algorithms_enabled(), use_deterministic_algorithms_warn_only=torch.is_deterministic_algorithms_warn_only_enabled(), cudnn_benchmark=torch.backends.cudnn.benchmark, rng_states=_collect_rng_states(), ...
"""Capture a few global states from torch, numpy, etc., that we want to restore in a spawned worker process.""" return cls( use_deterministic_algorithms=torch.are_deterministic_algorithms_enabled(), use_deterministic_algorithms_warn_only=torch.is_deterministic_algorithms_warn_onl...
7
379
112
491
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,291
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/strategies/parallel.py
81,83
30,134
distributed_sampler_kwargs
ParallelStrategy
83,88
83,88
class ParallelStrategy(Strategy, ABC): """Strategy for training with multiple processes in parallel.""" def __init__( self, accelerator: Optional["pl.accelerators.Accelerator"] = None, parallel_devices: Optional[List[torch.device]] = None, cluster_environment: Optional[ClusterEn...
class ParallelStrategy(Strategy, ABC): """Strategy for training with multiple processes in parallel.""" def __init__( self, accelerator: Optional["pl.accelerators.Accelerator"] = None, parallel_devices: Optional[List[torch.device]] = None, cluster_environment: Optional[ClusterEn...
return { "num_replicas": len(self.parallel_devices) if self.parallel_devices is not None else 0, "rank": self.global_rank, }
return { "num_replicas": len(self.parallel_devices) if self.parallel_devices is not None else 0, "rank": self.global_rank, }
14
1,060
54
1,114
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,292
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/strategies/single_device.py
76,78
30,102
model_to_device
SingleDeviceStrategy
78,81
78,81
class SingleDeviceStrategy(Strategy): """Strategy that handles communication on a single device.""" strategy_name = "single_device" def __init__( self, device: _DEVICE = "cpu", accelerator: pl.accelerators.accelerator.Accelerator | None = None, checkpoint_io: CheckpointIO |...
class SingleDeviceStrategy(Strategy): """Strategy that handles communication on a single device.""" strategy_name = "single_device" def __init__( self, device: _DEVICE = "cpu", accelerator: pl.accelerators.accelerator.Accelerator | None = None, checkpoint_io: CheckpointIO |...
assert self.model is not None, "self.model must be set before self.model.to()" self.model.to(self.root_device)
assert self.model is not None, "self.model must be set before self.model.to()" self.model.to(self.root_device)
12
627
42
669
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,294
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/strategies/strategy.py
627,628
601,649
wrapped_forward
_ForwardRedirection
628,638
628,638
class _ForwardRedirection: """Implements the `forward-redirection`. A method call to a wrapped module gets rerouted through the wrapper's `forward` method instead. """ def __call__( self, wrapper_module: Module, original_module: "pl.LightningModule", method_name: str, *args: Any, **kwargs: An...
class _ForwardRedirection: """Implements the `forward-redirection`. A method call to a wrapped module gets rerouted through the wrapper's `forward` method instead. """ def __call__( self, wrapper_module: Module, original_module: "pl.LightningModule", method_name: str, *args: Any, **kwargs: An...
# Unpatch ourselves immediately before calling the method `method_name` # because itself may want to call the real `forward` original_module.forward = original_forward # type: ignore[method-assign] # Call the actual method e.g. `.training_step(...)` method = ...
# Unpatch ourselves immediately before calling the method `method_name` # because itself may want to call the real `forward` original_module.forward = original_forward # type: ignore[method-assign] # Call the actual method e.g. `.training_step(...)` method = ...
60
477
156
633
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,301
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/connectors/data_connector.py
349,350
328,375
get_instance
_DataHookSelector
350,375
350,375
@dataclass class _DataHookSelector: """Stores the info about the shared DataHooks within ``LightningModule`` and ``LightningDataModule``. The hook source can be: 1. the :class:`~lightning.pytorch.core.LightningModule`, 2. the :class:`~lightning.pytorch.core.datamodule.LightningDataModule`, Argume...
@dataclass class _DataHookSelector: """Stores the info about the shared DataHooks within ``LightningModule`` and ``LightningDataModule``. The hook source can be: 1. the :class:`~lightning.pytorch.core.LightningModule`, 2. the :class:`~lightning.pytorch.core.datamodule.LightningDataModule`, Argume...
if hook_name not in self._valid_hooks: raise ValueError( f"`{hook_name}` is not a shared hook within `LightningModule` and `LightningDataModule`." f" Valid hooks are {self._valid_hooks}." ) if self.datamodule is None: return self.model...
if hook_name not in self._valid_hooks: raise ValueError( f"`{hook_name}` is not a shared hook within `LightningModule` and `LightningDataModule`." f" Valid hooks are {self._valid_hooks}." ) if self.datamodule is None: return self.model...
85
266
309
575
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,302
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/connectors/data_connector.py
282,283
262,313
dataloader
_DataLoaderSource
288,296
283,296
@dataclass class _DataLoaderSource: """Stores the information where the dataloaders come from. The source can be 1. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.LightningModule`, 2. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.datamodule.LightningD...
@dataclass class _DataLoaderSource: """Stores the information where the dataloaders come from. The source can be 1. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.LightningModule`, 2. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.datamodule.LightningD...
if isinstance(self.instance, pl.LightningModule): return call._call_lightning_module_hook(self.instance.trainer, self.name, pl_module=self.instance) if isinstance(self.instance, pl.LightningDataModule): assert self.instance.trainer is not None return call._call_lightn...
"""Returns the dataloader from the source. If the source is a module, the method with the corresponding :attr:`name` gets called. """ if isinstance(self.instance, pl.LightningModule): return call._call_lightning_module_hook(self.instance.trainer, self.name, pl_module=self.i...
25
530
130
660
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,305
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/connectors/logger_connector/result.py
175,177
106,184
is_min_reduction
_Metadata
177,179
177,179
@dataclass class _Metadata: fx: str name: str prog_bar: bool = False logger: bool = True on_step: bool = False on_epoch: bool = True # https://github.com/pytorch/pytorch/issues/96197 reduce_fx: Callable = "mean" if _TORCH_EQUAL_2_0 else torch.mean # type: ignore[assignment] enable_g...
@dataclass class _Metadata: fx: str name: str prog_bar: bool = False logger: bool = True on_step: bool = False on_epoch: bool = True # https://github.com/pytorch/pytorch/issues/96197 reduce_fx: Callable = "mean" if _TORCH_EQUAL_2_0 else torch.mean # type: ignore[assignment] enable_g...
return self.reduce_fx in (torch.min, min)
return self.reduce_fx in (torch.min, min)
5
857
21
878
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,307
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/connectors/logger_connector/result.py
276,278
184,313
wrapped_func
_ResultMetric
278,292
278,292
class _ResultMetric(Metric): """Wraps the value provided to `:meth:`~lightning.pytorch.core.LightningModule.log`""" def __init__(self, metadata: _Metadata, is_tensor: bool) -> None: super().__init__() self.is_tensor = is_tensor self.meta = metadata self.has_reset = False ...
class _ResultMetric(Metric): """Wraps the value provided to `:meth:`~lightning.pytorch.core.LightningModule.log`""" def __init__(self, metadata: _Metadata, is_tensor: bool) -> None: super().__init__() self.is_tensor = is_tensor self.meta = metadata self.has_reset = False ...
update_called = self.update_called if _TORCHMETRICS_GREATER_EQUAL_1_0_0 else self._update_called if not update_called: rank_zero_warn( f"The ``compute`` method of metric {self.__class__.__name__}" " was called before the ``update`` method w...
update_called = self.update_called if _TORCHMETRICS_GREATER_EQUAL_1_0_0 else self._update_called if not update_called: rank_zero_warn( f"The ``compute`` method of metric {self.__class__.__name__}" " was called before the ``update`` method w...
56
1,469
170
1,639
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,308
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/connectors/logger_connector/result.py
64,66
49,106
should
_Sync
66,70
66,70
@dataclass class _Sync: fn: Optional[Callable] = None _should: bool = False rank_zero_only: bool = False _op: Optional[str] = None _group: Optional[Any] = None def __post_init__(self) -> None: self._generate_sync_fn() @property def should(self) -> bool: return self._sho...
@dataclass class _Sync: fn: Optional[Callable] = None _should: bool = False rank_zero_only: bool = False _op: Optional[str] = None _group: Optional[Any] = None def __post_init__(self) -> None: self._generate_sync_fn() @property def should(self) -> bool: return self._sho...
self._should = should # `self._fn` needs to be re-generated. self._generate_sync_fn()
self._should = should # `self._fn` needs to be re-generated. self._generate_sync_fn()
10
511
37
548
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,309
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/states.py
67,69
44,74
dataloader_prefix
RunningStage
69,74
69,74
class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStag...
class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStag...
if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value
if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value
9
315
40
355
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,310
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/states.py
82,84
74,89
finished
TrainerState
84,86
84,86
@dataclass class TrainerState: """Dataclass to encapsulate the current :class:`~lightning.pytorch.trainer.trainer.Trainer` state.""" status: TrainerStatus = TrainerStatus.INITIALIZING fn: Optional[TrainerFn] = None stage: Optional[RunningStage] = None @property def finished(self) -> bool: FILL...
@dataclass class TrainerState: """Dataclass to encapsulate the current :class:`~lightning.pytorch.trainer.trainer.Trainer` state.""" status: TrainerStatus = TrainerStatus.INITIALIZING fn: Optional[TrainerFn] = None stage: Optional[RunningStage] = None @property def finished(self) -> bool: FILL...
return self.status == TrainerStatus.FINISHED
return self.status == TrainerStatus.FINISHED
4
140
18
158
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,311
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/trainer/states.py
28,30
20,33
stopped
TrainerStatus
30,33
30,33
class TrainerStatus(LightningEnum): """Enum for the status of the :class:`~lightning.pytorch.trainer.trainer.Trainer`""" INITIALIZING = "initializing" # trainer creation RUNNING = "running" FINISHED = "finished" INTERRUPTED = "interrupted" @property def stopped(self) -> bool: FILL_FUNC_BO...
class TrainerStatus(LightningEnum): """Enum for the status of the :class:`~lightning.pytorch.trainer.trainer.Trainer`""" INITIALIZING = "initializing" # trainer creation RUNNING = "running" FINISHED = "finished" INTERRUPTED = "interrupted" @property def stopped(self) -> bool: FILL_FUNC_BO...
return self in (self.FINISHED, self.INTERRUPTED)
return self in (self.FINISHED, self.INTERRUPTED)
5
119
26
145
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,315
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/_pytree.py
6,7
1,40
_is_leaf_or_primitive_container
8,18
7,18
from typing import Any, List, Tuple from torch.utils._pytree import SUPPORTED_NODES, LeafSpec, PyTree, TreeSpec, _get_node_type, tree_unflatten def _is_leaf_or_primitive_container(pytree: PyTree) -> bool: FILL_FUNC_BODYdef _tree_flatten(pytree: PyTree) -> Tuple[List[Any], TreeSpec]: """Copy of :func:`torch.utils...
from typing import Any, List, Tuple from torch.utils._pytree import SUPPORTED_NODES, LeafSpec, PyTree, TreeSpec, _get_node_type, tree_unflatten def _is_leaf_or_primitive_container(pytree: PyTree) -> bool: """Customized :func:`torch.utils._pytree._is_leaf` to avoid flattening containers of primitives.""" FILL_FUN...
is_leaf = _get_node_type(pytree) not in SUPPORTED_NODES if is_leaf: return True node_type = _get_node_type(pytree) flatten_fn = SUPPORTED_NODES[node_type].flatten_fn child_pytrees, _ = flatten_fn(pytree) return all(isinstance(child, (int, float, str)) for child in child_pytrees)
"""Customized :func:`torch.utils._pytree._is_leaf` to avoid flattening containers of primitives.""" is_leaf = _get_node_type(pytree) not in SUPPORTED_NODES if is_leaf: return True node_type = _get_node_type(pytree) flatten_fn = SUPPORTED_NODES[node_type].flatten_fn child_pytrees, _ = fl...
29
415
128
543
from typing import Any, List, Tuple from torch.utils._pytree import SUPPORTED_NODES, LeafSpec, PyTree, TreeSpec, _get_node_type, tree_unflatten def _is_leaf_or_primitive_container(pytree: PyTree) -> bool: FILL_FUNC_BODYdef _tree_flatten(pytree: PyTree) -> Tuple[List[Any], TreeSpec]: """Copy of :func:`torch.utils...
from typing import Any, List, Tuple from torch.utils._pytree import SUPPORTED_NODES, LeafSpec, PyTree, TreeSpec, _get_node_type, tree_unflatten def _is_leaf_or_primitive_container(pytree: PyTree) -> bool: """Customized :func:`torch.utils._pytree._is_leaf` to avoid flattening containers of primitives.""" FILL_FUN...
1,316
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/argparse.py
27,28
1,73
_parse_env_variables
43,56
28,56
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
env_args = {} for arg_name in inspect.signature(cls).parameters: env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()} val = os.environ.get(env) if not (val is None or val == ""): # todo: specify the possible exception with suppress...
"""Parse environment arguments if they are defined. Examples: >>> from lightning.pytorch import Trainer >>> _parse_env_variables(Trainer) Namespace() >>> import os >>> os.environ["PL_TRAINER_DEVICES"] = '42' >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23' ...
50
677
156
833
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,317
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/compile.py
25,26
1,131
from_compiled
37,70
26,70
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if not isinstance(model, OptimizedModule): raise ValueError(f"`model` is required to be a `OptimizedModule`. Found a `{type(model).__name__}` instead.") orig_module = model._orig_mod if not isinstance(orig_module, pl.LightningModule): _check_mixed_imports(model) raise ValueError( ...
"""Returns an instance LightningModule from the output of ``torch.compile``. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. The ``torch.compile`` function returns a ``torch._dynamo.OptimizedModule``, which wraps the LightningModule passed in as an argument, but doe...
105
1,295
614
1,909
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,318
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/consolidate_checkpoint.py
10,11
1,31
_format_checkpoint
12,25
11,25
import re from typing import Any, Dict import torch from lightning.fabric.utilities.consolidate_checkpoint import _parse_cli_args, _process_cli_args from lightning.fabric.utilities.load import _load_distributed_checkpoint def _format_checkpoint(checkpoint: Dict[str, Any]) -> Dict[str, Any]: FILL_FUNC_BODYif __name_...
import re from typing import Any, Dict import torch from lightning.fabric.utilities.consolidate_checkpoint import _parse_cli_args, _process_cli_args from lightning.fabric.utilities.load import _load_distributed_checkpoint def _format_checkpoint(checkpoint: Dict[str, Any]) -> Dict[str, Any]: """Converts the spec...
# Rename the model key checkpoint["state_dict"] = checkpoint.pop("model") optimizer_keys = [key for key in checkpoint if re.match("optimizer_[0-9]+", key)] if not optimizer_keys: return checkpoint # Optimizers are saved in special keys named `optimizer_0`, `optimizer_1`, etc. # These n...
"""Converts the special FSDP checkpoint format to the standard format the Lightning Trainer can load.""" # Rename the model key checkpoint["state_dict"] = checkpoint.pop("model") optimizer_keys = [key for key in checkpoint if re.match("optimizer_[0-9]+", key)] if not optimizer_keys: return ...
54
218
174
392
import re from typing import Any, Dict import torch from lightning.fabric.utilities.consolidate_checkpoint import _parse_cli_args, _process_cli_args from lightning.fabric.utilities.load import _load_distributed_checkpoint def _format_checkpoint(checkpoint: Dict[str, Any]) -> Dict[str, Any]: FILL_FUNC_BODYif __name_...
import re from typing import Any, Dict import torch from lightning.fabric.utilities.consolidate_checkpoint import _parse_cli_args, _process_cli_args from lightning.fabric.utilities.load import _load_distributed_checkpoint def _format_checkpoint(checkpoint: Dict[str, Any]) -> Dict[str, Any]: """Converts the spec...
1,319
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/enums.py
34,36
21,41
supported_type
GradClipAlgorithmType
36,38
36,38
class GradClipAlgorithmType(LightningEnum): """Define gradient_clip_algorithm types - training-tricks. NORM type means "clipping gradients by norm". This computed over all model parameters together. VALUE type means "clipping gradients by value". This will clip the gradient value for each parameter. Re...
class GradClipAlgorithmType(LightningEnum): """Define gradient_clip_algorithm types - training-tricks. NORM type means "clipping gradients by norm". This computed over all model parameters together. VALUE type means "clipping gradients by value". This will clip the gradient value for each parameter. Re...
return any(x.value == val for x in GradClipAlgorithmType)
return any(x.value == val for x in GradClipAlgorithmType)
8
242
23
265
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,320
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/exceptions.py
35,36
1,39
_augment_message
36,39
36,39
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
exception.args = tuple( new_message if isinstance(arg, str) and re.match(pattern, arg, re.DOTALL) else arg for arg in exception.args )
exception.args = tuple( new_message if isinstance(arg, str) and re.match(pattern, arg, re.DOTALL) else arg for arg in exception.args )
18
390
50
440
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,321
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/grads.py
22,23
1,54
grad_norm
41,54
23,54
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
norm_type = float(norm_type) if norm_type <= 0: raise ValueError(f"`norm_type` must be a positive number or 'inf' (infinity norm). Got {norm_type}") norms = { f"grad_{norm_type}_norm{group_separator}{name}": p.grad.data.norm(norm_type) for name, p in module.named_parameters() ...
"""Compute each parameter's gradient's norm and their overall norm. The overall norm is computed over all gradients together, as if they were concatenated into a single vector. Args: module: :class:`torch.nn.Module` to inspect. norm_type: The type of the used p-norm, cast to float if n...
46
424
190
614
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,322
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/imports.py
47,48
1,51
_habana_available_and_importable
48,51
48,51
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# This is defined as a function instead of a constant to avoid circular imports, because `lightning_habana` # also imports Lightning return bool(_LIGHTNING_HABANA_AVAILABLE) and _try_import_module("lightning_habana")
# This is defined as a function instead of a constant to avoid circular imports, because `lightning_habana` # also imports Lightning return bool(_LIGHTNING_HABANA_AVAILABLE) and _try_import_module("lightning_habana")
25
661
72
733
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,323
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/memory.py
83,84
1,93
garbage_collection_cuda
85,93
84,93
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
gc.collect() try: # This is the last thing that should cause an OOM error, but seemingly it can. torch.cuda.empty_cache() except RuntimeError as exception: if not is_oom_error(exception): # Only handle OOM errors raise
"""Garbage collection Torch (CUDA) memory.""" gc.collect() try: # This is the last thing that should cause an OOM error, but seemingly it can. torch.cuda.empty_cache() except RuntimeError as exception: if not is_oom_error(exception): # Only handle OOM errors ...
32
923
83
1,006
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,326
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/migration/utils.py
192,194
184,201
find_class
_RedirectingUnpickler
194,201
194,201
class _RedirectingUnpickler(pickle._Unpickler): """Redirects the unpickling of `pytorch_lightning` classes to `lightning.pytorch`. In legacy versions of Lightning, callback classes got pickled into the checkpoint. These classes are defined in the `pytorch_lightning` but need to be loaded from `lightning.py...
class _RedirectingUnpickler(pickle._Unpickler): """Redirects the unpickling of `pytorch_lightning` classes to `lightning.pytorch`. In legacy versions of Lightning, callback classes got pickled into the checkpoint. These classes are defined in the `pytorch_lightning` but need to be loaded from `lightning.py...
new_module = _patch_pl_to_mirror_if_necessary(module) # this warning won't trigger for standalone as these imports are identical if module != new_module: warnings.warn(f"Redirecting import of {module}.{name} to {new_module}.{name}") return super().find_class(new_module, name)...
new_module = _patch_pl_to_mirror_if_necessary(module) # this warning won't trigger for standalone as these imports are identical if module != new_module: warnings.warn(f"Redirecting import of {module}.{name} to {new_module}.{name}") return super().find_class(new_module, name)...
28
143
103
246
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,327
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/model_summary/model_summary_deepspeed.py
33,34
1,120
deepspeed_param_size
34,38
34,38
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
assert hasattr(p, "ds_numel") return p.ds_numel
assert hasattr(p, "ds_numel") return p.ds_numel
5
1,392
29
1,421
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
1,328
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/model_summary/model_summary_deepspeed.py
45,47
38,55
average_shard_parameters
DeepSpeedLayerSummary
48,55
47,55
class DeepSpeedLayerSummary(LayerSummary): @property @override def num_parameters(self) -> int: """Returns the number of parameters in this module.""" return sum(deepspeed_param_size(p) if not _is_lazy_weight_tensor(p) else 0 for p in self._module.parameters()) @property def average...
class DeepSpeedLayerSummary(LayerSummary): @property @override def num_parameters(self) -> int: """Returns the number of parameters in this module.""" return sum(deepspeed_param_size(p) if not _is_lazy_weight_tensor(p) else 0 for p in self._module.parameters()) @property def average...
def partitioned_size(p: Parameter) -> int: return p.partitioned_size() if RequirementCache("deepspeed<0.6.6") else p.partition_numel() return sum(partitioned_size(p) if not _is_lazy_weight_tensor(p) else 0 for p in self._module.parameters())
"""Returns the number of parameters in this module.""" def partitioned_size(p: Parameter) -> int: return p.partitioned_size() if RequirementCache("deepspeed<0.6.6") else p.partition_numel() return sum(partitioned_size(p) if not _is_lazy_weight_tensor(p) else 0 for p in self._module...
22
129
101
230
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
1,329
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/model_summary/model_summary_deepspeed.py
89,91
55,120
_get_summary_data
DeepSpeedSummary
96,114
91,114
class DeepSpeedSummary(ModelSummary): @override def summarize(self) -> Dict[str, DeepSpeedLayerSummary]: # type: ignore[override] summary = OrderedDict((name, DeepSpeedLayerSummary(module)) for name, module in self.named_modules) if self._model.example_input_array is not None: self....
class DeepSpeedSummary(ModelSummary): @override def summarize(self) -> Dict[str, DeepSpeedLayerSummary]: # type: ignore[override] summary = OrderedDict((name, DeepSpeedLayerSummary(module)) for name, module in self.named_modules) if self._model.example_input_array is not None: self....
arrays = [ (" ", list(map(str, range(len(self._layer_summary))))), ("Name", self.layer_names), ("Type", self.layer_types), ("Params", list(map(get_human_readable_count, self.param_nums))), ("Params per Device", list(map(get_human_readable_count, self.p...
"""Makes a summary listing with: Layer Name, Layer Type, Number of Parameters, Input Sizes, Output Sizes, Model Size """ arrays = [ (" ", list(map(str, range(len(self._layer_summary))))), ("Name", self.layer_names), ("Type", self.layer_types), ...
62
582
286
868
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# Copyright 2020 The PyTorch Lightning team and Microsoft Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
1,330
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/parameter_tying.py
31,32
1,69
_find_shared_parameters
32,49
32,49
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if tied_parameters is None: tied_parameters = {} for name, param in module._parameters.items(): param_prefix = prefix + ("." if prefix else "") + name if param is None: continue if param not in tied_parameters: tied_parameters[param] = [] tied_para...
if tied_parameters is None: tied_parameters = {} for name, param in module._parameters.items(): param_prefix = prefix + ("." if prefix else "") + name if param is None: continue if param not in tied_parameters: tied_parameters[param] = [] tied_para...
71
597
192
789
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,331
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/seed.py
22,24
1,47
isolate_rng
44,47
24,47
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
states = _collect_rng_states(include_cuda) yield _set_rng_states(states)
"""A context manager that resets the global random state on exit to what it was before entering. It supports isolating the states for PyTorch, Numpy, and Python built-in random number generators. Args: include_cuda: Whether to allow this function to also control the `torch.cuda` random number gene...
5
497
35
532
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,332
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/signature_utils.py
18,21
1,38
is_param_in_hook_signature
28,38
21,38
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if hasattr(hook_fx, "__wrapped__"): # in case the hook has a decorator hook_fx = hook_fx.__wrapped__ parameters = inspect.getfullargspec(hook_fx) args = parameters.args[1:] # ignore `self` return ( param in args or (not explicit and (parameters.varargs is not None)) ...
""" Args: hook_fx: the hook callable param: the name of the parameter to check explicit: whether the parameter has to be explicitly declared min_args: whether the `signature` has at least `min_args` parameters """ if hasattr(hook_fx, "__wrapped__"): # in case the ...
44
286
133
419
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,333
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/types.py
75,76
58,80
no_sync
DistributedDataParallel
76,77
76,77
@runtime_checkable class DistributedDataParallel(Protocol): def __init__( self, module: torch.nn.Module, device_ids: Optional[List[Union[int, torch.device]]] = None, output_device: Optional[Union[int, torch.device]] = None, dim: int = 0, broadcast_buffers: bool = True...
@runtime_checkable class DistributedDataParallel(Protocol): def __init__( self, module: torch.nn.Module, device_ids: Optional[List[Union[int, torch.device]]] = None, output_device: Optional[Union[int, torch.device]] = None, dim: int = 0, broadcast_buffers: bool = True...
def no_sync(self) -> Generator: ...
def no_sync(self) -> Generator: ...
5
218
16
234
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,334
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/utilities/upgrade_checkpoint.py
70,71
1,103
main
71,101
71,101
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
parser = ArgumentParser( description=( "A utility to upgrade old checkpoints to the format of the current Lightning version." " This will also save a backup of the original files." ) ) parser.add_argument( "path", type=str, help="Path to a chec...
parser = ArgumentParser( description=( "A utility to upgrade old checkpoints to the format of the current Lightning version." " This will also save a backup of the original files." ) ) parser.add_argument( "path", type=str, help="Path to a chec...
101
729
275
1,004
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,335
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/store/store.py
23,29
1,93
upload_model
42,58
29,58
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
client = _Client() user = client.auth_service_get_user() # TODO: Allow passing this project_id = _get_project(client).project_id # TODO: Post model parts if the file size is over threshold body = V1UploadModelRequest( name=f"{user.username}/{name}", version=version, proj...
"""Upload a model to the lightning cloud. Args: name: The model name. path: The path to the checkpoint to be uploaded. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: ...
39
699
167
866
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,336
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/store/utils.py
41,42
1,68
_download_file_from_url
42,64
42,64
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
with requests.get(url, stream=True) as req_stream: total_size_in_bytes = int(req_stream.headers.get("content-length", 0)) block_size = 1000 * 1000 # 1 MB download_progress_bar = None if progress_bar: download_progress_bar = tqdm( desc="Downloading", ...
with requests.get(url, stream=True) as req_stream: total_size_in_bytes = int(req_stream.headers.get("content-length", 0)) block_size = 1000 * 1000 # 1 MB download_progress_bar = None if progress_bar: download_progress_bar = tqdm( desc="Downloading", ...
47
510
257
767
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,337
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning_app/__setup__.py
50,51
1,123
_setup_args
51,123
51,123
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_...
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_...
assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, versio...
assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, versio...
270
708
1,058
1,766
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_...
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_...
1,338
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning_fabric/__setup__.py
52,53
1,114
_setup_args
53,114
53,114
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT,...
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT,...
assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, versio...
assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, versio...
227
729
874
1,603
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT,...
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT,...
1,339
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/pytorch_lightning/__setup__.py
32,33
1,116
_prepare_extras
33,52
33,52
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_...
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_...
assistant = _load_assistant() # https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras # Define package extras. These are only installed if you specify them. # From remote, use like `pip install "pytorch-lightning[dev, docs]"` # From local copy of repo, use like `PACKAGE_NAME=p...
assistant = _load_assistant() # https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras # Define package extras. These are only installed if you specify them. # From remote, use like `pip install "pytorch-lightning[dev, docs]"` # From local copy of repo, use like `PACKAGE_NAME=p...
98
1,224
366
1,590
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_...
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_...
2,161
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa/example/authmodule.py
102,103
71,217
_addMethod
AuthPolicy
106,134
103,134
class AuthPolicy: awsAccountId = "" """The AWS account id the policy will be generated for. This is used to create the method ARNs.""" principalId = "" """The principal used for the policy, this should be a unique identifier for the end user.""" version = "2012-10-17" """The policy version used ...
class AuthPolicy: awsAccountId = "" """The AWS account id the policy will be generated for. This is used to create the method ARNs.""" principalId = "" """The principal used for the policy, this should be a unique identifier for the end user.""" version = "2012-10-17" """The policy version used ...
if verb != "*" and not hasattr(HttpVerb, verb): raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class") resourcePattern = re.compile(self.pathRegex) if not resourcePattern.match(resource): raise NameError("Invalid resource path: " + resource + "...
"""Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.""" if verb != "*" and not hasattr(HttpVerb, verb): raise NameError("Invalid HTTP verb ...
99
1,383
295
1,678
""" Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanyin...
""" Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanyin...
2,162
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa/example/mymodule.py
5,6
1,9
myfunc_with_events
6,9
6,9
def myfunc(): print('Running my function in a schedule!') def myfunc_with_events(event, context): FILL_FUNC_BODY
def myfunc(): print('Running my function in a schedule!') def myfunc_with_events(event, context): FILL_FUNC_BODY
print('Event time was', event['time']) print('This log is', context.log_group_name, context.log_stream_name) print('Time left for execution:', context.get_remaining_time_in_millis())
print('Event time was', event['time']) print('This log is', context.log_group_name, context.log_stream_name) print('Time left for execution:', context.get_remaining_time_in_millis())
14
42
63
105
def myfunc(): print('Running my function in a schedule!') def myfunc_with_events(event, context): FILL_FUNC_BODY
def myfunc(): print('Running my function in a schedule!') def myfunc_with_events(event, context): FILL_FUNC_BODY
2,163
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa
/home/hieuvd/dung_repo/raw/stars_01/Miserlou_Zappa/Zappa/test_settings.py
62,63
1,68
authorizer_event
63,66
63,66
APP_MODULE = 'tests.test_app' APP_FUNCTION = 'hello_world' DJANGO_SETTINGS = None DEBUG = 'True' LOG_LEVEL = 'DEBUG' SCRIPT_NAME = 'hello_world' DOMAIN = None API_STAGE = 'ttt888' PROJECT_NAME = 'ttt888' REMOTE_ENV='s3://lmbda/test_env.json' ## test_env.json #{ # "hello": "world" #} # AWS_EVENT_MAPPING = { 'ar...
APP_MODULE = 'tests.test_app' APP_FUNCTION = 'hello_world' DJANGO_SETTINGS = None DEBUG = 'True' LOG_LEVEL = 'DEBUG' SCRIPT_NAME = 'hello_world' DOMAIN = None API_STAGE = 'ttt888' PROJECT_NAME = 'ttt888' REMOTE_ENV='s3://lmbda/test_env.json' ## test_env.json #{ # "hello": "world" #} # AWS_EVENT_MAPPING = { 'ar...
return "AUTHORIZER_EVENT"
return "AUTHORIZER_EVENT"
2
566
17
583
APP_MODULE = 'tests.test_app' APP_FUNCTION = 'hello_world' DJANGO_SETTINGS = None DEBUG = 'True' LOG_LEVEL = 'DEBUG' SCRIPT_NAME = 'hello_world' DOMAIN = None API_STAGE = 'ttt888' PROJECT_NAME = 'ttt888' REMOTE_ENV='s3://lmbda/test_env.json' ## test_env.json #{ # "hello": "world" #} # AWS_EVENT_MAPPING = { 'ar...
APP_MODULE = 'tests.test_app' APP_FUNCTION = 'hello_world' DJANGO_SETTINGS = None DEBUG = 'True' LOG_LEVEL = 'DEBUG' SCRIPT_NAME = 'hello_world' DOMAIN = None API_STAGE = 'ttt888' PROJECT_NAME = 'ttt888' REMOTE_ENV='s3://lmbda/test_env.json' ## test_env.json #{ # "hello": "world" #} # AWS_EVENT_MAPPING = { 'ar...
2,191
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/async_db.py
40,41
10,97
item_to_table
AsyncMysqlDB
47,59
41,59
class AsyncMysqlDB: def __init__(self, pool: aiomysql.Pool) -> None: self.__pool = pool async def query(self, sql: str, *args: Union[str, int]) -> List[Dict[str, Any]]: """ 从给定的 SQL 中查询记录,返回的是一个列表 :param sql: 查询的sql :param args: sql中传递动态参数列表 :return: """ ...
class AsyncMysqlDB: def __init__(self, pool: aiomysql.Pool) -> None: self.__pool = pool async def query(self, sql: str, *args: Union[str, int]) -> List[Dict[str, Any]]: """ 从给定的 SQL 中查询记录,返回的是一个列表 :param sql: 查询的sql :param args: sql中传递动态参数列表 :return: """ ...
fields = list(item.keys()) values = list(item.values()) fields = [f'`{field}`' for field in fields] fieldstr = ','.join(fields) valstr = ','.join(['%s'] * len(item)) sql = "INSERT INTO %s (%s) VALUES(%s)" % (table_name, fieldstr, valstr) async with self.__pool.acq...
""" 表中插入数据 :param table_name: 表名 :param item: 一条记录的字典信息 :return: """ fields = list(item.keys()) values = list(item.values()) fields = [f'`{field}`' for field in fields] fieldstr = ','.join(fields) valstr = ','.join(['%s'] * len(item...
50
827
173
1,000
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:21 # @Desc : 异步Aiomysql的增删改查封装 from typing import Any, Dict, List, Union import aiomysql class AsyncMysqlDB: def __init__(self, pool: aiomysql.Pool) -> None: self.__pool = pool async def query(self, sql: str, *args: ...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:21 # @Desc : 异步Aiomysql的增删改查封装 from typing import Any, Dict, List, Union import aiomysql class AsyncMysqlDB: def __init__(self, pool: aiomysql.Pool) -> None: self.__pool = pool async def query(self, sql: str, *args: ...
2,192
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/base/base_crawler.py
49,51
44,59
store_comment
AbstractStore
51,56
51,56
class AbstractStore(ABC): @abstractmethod async def store_content(self, content_item: Dict): pass @abstractmethod async def store_comment(self, comment_item: Dict): FILL_FUNC_BODY async def store_creator(self, creator: Dict): pass
class AbstractStore(ABC): @abstractmethod async def store_content(self, content_item: Dict): pass @abstractmethod async def store_comment(self, comment_item: Dict): FILL_FUNC_BODY async def store_creator(self, creator: Dict): pass
pass # TODO support all platform # only xhs is supported, so @abstractmethod is commented # @abstractmethod
pass # TODO support all platform # only xhs is supported, so @abstractmethod is commented # @abstractmethod
17
89
39
128
from abc import ABC, abstractmethod from typing import Dict, Optional from playwright.async_api import BrowserContext, BrowserType class AbstractCrawler(ABC): @abstractmethod def init_config(self, platform: str, login_type: str, crawler_type: str, start_page: int, keyword: str): pass @abstractme...
from abc import ABC, abstractmethod from typing import Dict, Optional from playwright.async_api import BrowserContext, BrowserType class AbstractCrawler(ABC): @abstractmethod def init_config(self, platform: str, login_type: str, crawler_type: str, start_page: int, keyword: str): pass @abstractme...
2,193
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/db.py
79,80
1,97
init_table_schema
85,95
80,95
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:54 # @Desc : mediacrawler db 管理 import asyncio from typing import Dict from urllib.parse import urlparse import aiofiles import aiomysql import config from async_db import AsyncMysqlDB from tools import utils from var import db_conn_p...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:54 # @Desc : mediacrawler db 管理 import asyncio from typing import Dict from urllib.parse import urlparse import aiofiles import aiomysql import config from async_db import AsyncMysqlDB from tools import utils from var import db_conn_p...
utils.logger.info("[init_table_schema] begin init mysql table schema ...") await init_mediacrawler_db() async_db_obj: AsyncMysqlDB = media_crawler_db_var.get() async with aiofiles.open("schema/tables.sql", mode="r") as f: schema_sql = await f.read() await async_db_obj.execute(schema_sql)...
""" 用来初始化数据库表结构,请在第一次需要创建表结构的时候使用,多次执行该函数会将已有的表以及数据全部删除 Returns: """ utils.logger.info("[init_table_schema] begin init mysql table schema ...") await init_mediacrawler_db() async_db_obj: AsyncMysqlDB = media_crawler_db_var.get() async with aiofiles.open("schema/tables.sql", mode="r") as...
33
812
155
967
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:54 # @Desc : mediacrawler db 管理 import asyncio from typing import Dict from urllib.parse import urlparse import aiofiles import aiomysql import config from async_db import AsyncMysqlDB from tools import utils from var import db_conn_p...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 14:54 # @Desc : mediacrawler db 管理 import asyncio from typing import Dict from urllib.parse import urlparse import aiofiles import aiomysql import config from async_db import AsyncMysqlDB from tools import utils from var import db_conn_p...
2,194
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/main.py
32,33
1,71
main
33,65
33,65
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
# define command line params ... parser = argparse.ArgumentParser(description='Media crawler program.') parser.add_argument('--platform', type=str, help='Media platform select (xhs | dy | ks | bili | wb)', choices=["xhs", "dy", "ks", "bili", "wb"], default=config.PLATFORM) parser...
# define command line params ... parser = argparse.ArgumentParser(description='Media crawler program.') parser.add_argument('--platform', type=str, help='Media platform select (xhs | dy | ks | bili | wb)', choices=["xhs", "dy", "ks", "bili", "wb"], default=config.PLATFORM) parser...
104
369
476
845
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
2,195
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/main.py
24,26
15,32
create_crawler
CrawlerFactory
26,32
26,32
class CrawlerFactory: CRAWLERS = { "xhs": XiaoHongShuCrawler, "dy": DouYinCrawler, "ks": KuaishouCrawler, "bili": BilibiliCrawler, "wb": WeiboCrawler } @staticmethod def create_crawler(platform: str) -> AbstractCrawler: FILL_FUNC_BODY
class CrawlerFactory: CRAWLERS = { "xhs": XiaoHongShuCrawler, "dy": DouYinCrawler, "ks": KuaishouCrawler, "bili": BilibiliCrawler, "wb": WeiboCrawler } @staticmethod def create_crawler(platform: str) -> AbstractCrawler: FILL_FUNC_BODY
crawler_class = CrawlerFactory.CRAWLERS.get(platform) if not crawler_class: raise ValueError("Invalid Media Platform Currently only supported xhs or dy or ks or bili ...") return crawler_class()
crawler_class = CrawlerFactory.CRAWLERS.get(platform) if not crawler_class: raise ValueError("Invalid Media Platform Currently only supported xhs or dy or ks or bili ...") return crawler_class()
23
122
71
193
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
import argparse import asyncio import sys import config import db from base.base_crawler import AbstractCrawler from media_platform.bilibili import BilibiliCrawler from media_platform.douyin import DouYinCrawler from media_platform.kuaishou import KuaishouCrawler from media_platform.weibo import WeiboCrawler from medi...
2,196
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/bilibili/help.py
35,36
13,58
sign
BilibiliSign
42,58
36,58
class BilibiliSign: def __init__(self, img_key: str, sub_key: str): self.img_key = img_key self.sub_key = sub_key self.map_table = [ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 1...
class BilibiliSign: def __init__(self, img_key: str, sub_key: str): self.img_key = img_key self.sub_key = sub_key self.map_table = [ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 1...
current_ts = utils.get_unix_timestamp() req_data.update({"wts": current_ts}) req_data = dict(sorted(req_data.items())) req_data = { # 过滤 value 中的 "!'()*" 字符 k: ''.join(filter(lambda ch: ch not in "!'()*", str(v))) for k, v in req_data.items...
""" 请求参数中加上当前时间戳对请求参数中的key进行字典序排序 再将请求参数进行 url 编码集合 salt 进行 md5 就可以生成w_rid参数了 :param req_data: :return: """ current_ts = utils.get_unix_timestamp() req_data.update({"wts": current_ts}) req_data = dict(sorted(req_data.items())) req_data = { ...
50
497
209
706
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 23:26 # @Desc : bilibili 请求参数签名 # 逆向实现参考:https://socialsisteryi.github.io/bilibili-API-collect/docs/misc/sign/wbi.html#wbi%E7%AD%BE%E5%90%8D%E7%AE%97%E6%B3%95 import urllib.parse from hashlib import md5 from typing import Dict from t...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 23:26 # @Desc : bilibili 请求参数签名 # 逆向实现参考:https://socialsisteryi.github.io/bilibili-API-collect/docs/misc/sign/wbi.html#wbi%E7%AD%BE%E5%90%8D%E7%AE%97%E6%B3%95 import urllib.parse from hashlib import md5 from typing import Dict from t...
2,197
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/bilibili/login.py
59,60
19,107
login_by_qrcode
BilibiliLogin
61,95
60,95
class BilibiliLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_...
class BilibiliLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_...
utils.logger.info("[BilibiliLogin.login_by_qrcode] Begin login bilibili by qrcode ...") # click login button login_button_ele = self.context_page.locator( "xpath=//div[@class='right-entry__outside go-login-btn']//div" ) await login_button_ele.click() # find ...
"""login bilibili website and keep webdriver login state""" utils.logger.info("[BilibiliLogin.login_by_qrcode] Begin login bilibili by qrcode ...") # click login button login_button_ele = self.context_page.locator( "xpath=//div[@class='right-entry__outside go-login-btn']//di...
99
657
524
1,181
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 18:44 # @Desc : bilibli登录实现类 import asyncio import functools import sys from typing import Optional from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, ...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 18:44 # @Desc : bilibli登录实现类 import asyncio import functools import sys from typing import Optional from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, ...
2,198
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/kuaishou/graphql.py
13,14
6,23
load_graphql_queries
KuaiShouGraphQL
14,21
14,21
class KuaiShouGraphQL: graphql_queries: Dict[str, str]= {} def __init__(self): self.graphql_dir = "media_platform/kuaishou/graphql/" self.load_graphql_queries() def load_graphql_queries(self): FILL_FUNC_BODY def get(self, query_name: str) -> str: return self.graphql_queries.get(...
class KuaiShouGraphQL: graphql_queries: Dict[str, str]= {} def __init__(self): self.graphql_dir = "media_platform/kuaishou/graphql/" self.load_graphql_queries() def load_graphql_queries(self): FILL_FUNC_BODY def get(self, query_name: str) -> str: return self.graphql_queries.get(...
graphql_files = ["search_query.graphql", "video_detail.graphql", "comment_list.graphql", "vision_profile.graphql"] for file in graphql_files: with open(self.graphql_dir + file, mode="r") as f: query_name = file.split(".")[0] self.graphql_queries[query_name] =...
graphql_files = ["search_query.graphql", "video_detail.graphql", "comment_list.graphql", "vision_profile.graphql"] for file in graphql_files: with open(self.graphql_dir + file, mode="r") as f: query_name = file.split(".")[0] self.graphql_queries[query_name] =...
23
133
113
246
# 快手的数据传输是基于GraphQL实现的 # 这个类负责获取一些GraphQL的schema from typing import Dict class KuaiShouGraphQL: graphql_queries: Dict[str, str]= {} def __init__(self): self.graphql_dir = "media_platform/kuaishou/graphql/" self.load_graphql_queries() def load_graphql_queries(self): FILL_FUNC_BODY def ...
# 快手的数据传输是基于GraphQL实现的 # 这个类负责获取一些GraphQL的schema from typing import Dict class KuaiShouGraphQL: graphql_queries: Dict[str, str]= {} def __init__(self): self.graphql_dir = "media_platform/kuaishou/graphql/" self.load_graphql_queries() def load_graphql_queries(self): FILL_FUNC_BODY def ...
2,199
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/kuaishou/login.py
30,31
16,104
begin
KuaishouLogin
32,42
31,42
class KuaishouLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_...
class KuaishouLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_...
utils.logger.info("[KuaishouLogin.begin] Begin login kuaishou ...") if self.login_type == "qrcode": await self.login_by_qrcode() elif self.login_type == "phone": await self.login_by_mobile() elif self.login_type == "cookie": await self.login_by_cookies...
"""Start login xiaohongshu""" utils.logger.info("[KuaishouLogin.begin] Begin login kuaishou ...") if self.login_type == "qrcode": await self.login_by_qrcode() elif self.login_type == "phone": await self.login_by_mobile() elif self.login_type == "cookie": ...
38
1,018
146
1,164
import asyncio import functools import sys from typing import Optional import redis from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, wait_fixed) import config from base.base_crawler import AbstractLogin from tools...
import asyncio import functools import sys from typing import Optional import redis from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, wait_fixed) import config from base.base_crawler import AbstractLogin from tools...
2,200
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/weibo/help.py
9,10
1,26
filter_search_result_card
15,26
10,26
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/24 17:37 # @Desc : from typing import Dict, List def filter_search_result_card(card_list: List[Dict]) -> List[Dict]: FILL_FUNC_BODY
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/24 17:37 # @Desc : from typing import Dict, List def filter_search_result_card(card_list: List[Dict]) -> List[Dict]: """ 过滤微博搜索的结果,只保留card_type为9类型的数据 :param card_list: :return: """ FILL_FUNC_BODY
note_list: List[Dict] = [] for card_item in card_list: if card_item.get("card_type") == 9: note_list.append(card_item) if len(card_item.get("card_group", [])) > 0: card_group = card_item.get("card_group") for card_group_item in card_group: if c...
""" 过滤微博搜索的结果,只保留card_type为9类型的数据 :param card_list: :return: """ note_list: List[Dict] = [] for card_item in card_list: if card_item.get("card_type") == 9: note_list.append(card_item) if len(card_item.get("card_group", [])) > 0: card_group = card_item....
32
141
151
292
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/24 17:37 # @Desc : from typing import Dict, List def filter_search_result_card(card_list: List[Dict]) -> List[Dict]: FILL_FUNC_BODY
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/24 17:37 # @Desc : from typing import Dict, List def filter_search_result_card(card_list: List[Dict]) -> List[Dict]: """ 过滤微博搜索的结果,只保留card_type为9类型的数据 :param card_list: :return: """ FILL_FUNC_BODY
2,201
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/media_platform/weibo/login.py
128,129
19,137
login_by_cookies
WeiboLogin
129,137
129,137
class WeiboLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_typ...
class WeiboLogin(AbstractLogin): def __init__(self, login_type: str, browser_context: BrowserContext, context_page: Page, login_phone: Optional[str] = "", cookie_str: str = "" ): self.login_type = login_typ...
utils.logger.info("[WeiboLogin.login_by_qrcode] Begin login weibo by cookie ...") for key, value in utils.convert_str_cookie_to_dict(self.cookie_str).items(): await self.browser_context.add_cookies([{ 'name': key, 'value': value, 'domain': ".we...
utils.logger.info("[WeiboLogin.login_by_qrcode] Begin login weibo by cookie ...") for key, value in utils.convert_str_cookie_to_dict(self.cookie_str).items(): await self.browser_context.add_cookies([{ 'name': key, 'value': value, 'domain': ".we...
23
1,445
122
1,567
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/23 15:42 # @Desc : 微博登录实现 import asyncio import functools import sys from typing import Optional from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, ...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/23 15:42 # @Desc : 微博登录实现 import asyncio import functools import sys from typing import Optional from playwright.async_api import BrowserContext, Page from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt, ...
2,204
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/providers/jishu_http_proxy.py
77,78
1,88
new_jisu_http_proxy
83,88
78,88
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
return JiSuHttpProxy( key=os.getenv("jisu_key", ""), # 通过环境变量的方式获取极速HTTPIP提取key值 crypto=os.getenv("jisu_crypto", ""), # 通过环境变量的方式获取极速HTTPIP提取加密签名 time_validity_period=30 # 30分钟(最长时效) )
""" 构造极速HTTP实例 Returns: """ return JiSuHttpProxy( key=os.getenv("jisu_key", ""), # 通过环境变量的方式获取极速HTTPIP提取key值 crypto=os.getenv("jisu_crypto", ""), # 通过环境变量的方式获取极速HTTPIP提取加密签名 time_validity_period=30 # 30分钟(最长时效) )
14
1,146
114
1,260
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
2,205
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/providers/jishu_http_proxy.py
36,37
16,77
get_proxies
JiSuHttpProxy
41,77
37,77
class JiSuHttpProxy(ProxyProvider): def __init__(self, key: str, crypto: str, time_validity_period: int): """ 极速HTTP 代理IP实现 :param key: 提取key值 (去官网注册后获取) :param crypto: 加密签名 (去官网注册后获取) """ self.proxy_brand_name = "JISUHTTP" self.api_path = "https://api.jisuhtt...
class JiSuHttpProxy(ProxyProvider): def __init__(self, key: str, crypto: str, time_validity_period: int): """ 极速HTTP 代理IP实现 :param key: 提取key值 (去官网注册后获取) :param crypto: 加密签名 (去官网注册后获取) """ self.proxy_brand_name = "JISUHTTP" self.api_path = "https://api.jisuhtt...
# 优先从缓存中拿 IP ip_cache_list = self.ip_cache.load_all_ip(proxy_brand_name=self.proxy_brand_name) if len(ip_cache_list) >= num: return ip_cache_list[:num] # 如果缓存中的数量不够,从IP代理商获取补上,再存入缓存中 need_get_count = num - len(ip_cache_list) self.params.update({"num": need_g...
""" :param num: :return: """ # 优先从缓存中拿 IP ip_cache_list = self.ip_cache.load_all_ip(proxy_brand_name=self.proxy_brand_name) if len(ip_cache_list) >= num: return ip_cache_list[:num] # 如果缓存中的数量不够,从IP代理商获取补上,再存入缓存中 need_get_count = num -...
100
381
611
992
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:32 # @Desc : 极速HTTP代理提供类实现,官网地址:https://www.jisuhttp.com?pl=zG3Jna import os from typing import Dict, List from urllib.parse import urlencode import httpx from proxy import IpGetError, ProxyProvider, RedisDbIpCache from proxy.types im...
2,206
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/providers/kuaidl_proxy.py
123,124
1,135
new_kuai_daili_proxy
129,135
124,135
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
return KuaiDaiLiProxy( kdl_secret_id=os.getenv("kdl_secret_id", "你的快代理secert_id"), kdl_signature=os.getenv("kdl_signature", "你的快代理签名"), kdl_user_name=os.getenv("kdl_user_name", "你的快代理用户名"), kdl_user_pwd=os.getenv("kdl_user_pwd", "你的快代理密码"), )
""" 构造快代理HTTP实例 Returns: """ return KuaiDaiLiProxy( kdl_secret_id=os.getenv("kdl_secret_id", "你的快代理secert_id"), kdl_signature=os.getenv("kdl_signature", "你的快代理签名"), kdl_user_name=os.getenv("kdl_user_name", "你的快代理用户名"), kdl_user_pwd=os.getenv("kdl_user_pwd", "你的快代理密码"...
11
1,459
132
1,591
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
2,207
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/providers/kuaidl_proxy.py
72,73
48,123
get_proxies
KuaiDaiLiProxy
81,123
73,123
class KuaiDaiLiProxy(ProxyProvider): def __init__(self, kdl_user_name: str, kdl_user_pwd: str, kdl_secret_id: str, kdl_signature: str): """ Args: kdl_user_name: kdl_user_pwd: """ self.kdl_user_name = kdl_user_name self.kdl_user_pwd = kdl_user_pwd ...
class KuaiDaiLiProxy(ProxyProvider): def __init__(self, kdl_user_name: str, kdl_user_pwd: str, kdl_secret_id: str, kdl_signature: str): """ Args: kdl_user_name: kdl_user_pwd: """ self.kdl_user_name = kdl_user_name self.kdl_user_pwd = kdl_user_pwd ...
uri = "/api/getdps/" # 优先从缓存中拿 IP ip_cache_list = self.ip_cache.load_all_ip(proxy_brand_name=self.proxy_brand_name) if len(ip_cache_list) >= num: return ip_cache_list[:num] # 如果缓存中的数量不够,从IP代理商获取补上,再存入缓存中 need_get_count = num - len(ip_cache_list) self...
""" 快代理实现 Args: num: Returns: """ uri = "/api/getdps/" # 优先从缓存中拿 IP ip_cache_list = self.ip_cache.load_all_ip(proxy_brand_name=self.proxy_brand_name) if len(ip_cache_list) >= num: return ip_cache_list[:num] # 如果缓...
122
339
656
995
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/5 09:43 # @Desc : 快代理HTTP实现,官方文档:https://www.kuaidaili.com/?ref=ldwkjqipvz6c import os import re from typing import Dict, List import httpx from pydantic import BaseModel, Field from proxy import IpGetError, IpInfoModel, ProxyProvider, Red...
2,208
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/proxy_ip_pool.py
94,95
1,111
create_ip_pool
101,109
95,109
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
pool = ProxyIpPool(ip_pool_count=ip_pool_count, enable_validate_ip=enable_validate_ip, ip_provider=IpProxyProvider.get(config.IP_PROXY_PROVIDER_NAME) ) await pool.load_proxies() return pool
""" 创建 IP 代理池 :param ip_pool_count: ip池子的数量 :param enable_validate_ip: 是否开启验证IP代理 :return: """ pool = ProxyIpPool(ip_pool_count=ip_pool_count, enable_validate_ip=enable_validate_ip, ip_provider=IpProxyProvider.get(config.IP_PROXY_PROVIDER_NAME) ...
10
1,064
90
1,154
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
2,209
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/proxy/proxy_ip_pool.py
42,43
19,88
_is_valid_proxy
ProxyIpPool
48,63
43,63
class ProxyIpPool: def __init__(self, ip_pool_count: int, enable_validate_ip: bool, ip_provider: ProxyProvider) -> None: """ Args: ip_pool_count: enable_validate_ip: ip_provider: """ self.valid_ip_url = "https://httpbin.org/ip" # 验证 IP 是否有效的地址 ...
class ProxyIpPool: def __init__(self, ip_pool_count: int, enable_validate_ip: bool, ip_provider: ProxyProvider) -> None: """ Args: ip_pool_count: enable_validate_ip: ip_provider: """ self.valid_ip_url = "https://httpbin.org/ip" # 验证 IP 是否有效的地址 ...
utils.logger.info(f"[ProxyIpPool._is_valid_proxy] testing {proxy.ip} is it valid ") try: httpx_proxy = { f"{proxy.protocol}": f"http://{proxy.user}:{proxy.password}@{proxy.ip}:{proxy.port}" } async with httpx.AsyncClient(proxies=httpx_proxy) as client:...
""" 验证代理IP是否有效 :param proxy: :return: """ utils.logger.info(f"[ProxyIpPool._is_valid_proxy] testing {proxy.ip} is it valid ") try: httpx_proxy = { f"{proxy.protocol}": f"http://{proxy.user}:{proxy.password}@{proxy.ip}:{proxy.port}" ...
43
536
208
744
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 13:45 # @Desc : ip代理池实现 import random from typing import Dict, List import httpx from tenacity import retry, stop_after_attempt, wait_fixed import config from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy from tools i...
2,210
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/recv_sms.py
34,36
1,68
receive_sms_notification
51,61
36,61
import re from typing import List import redis import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel import config from tools import utils app = FastAPI() redis_client = redis.Redis(host=config.REDIS_DB_HOST, password=config.REDIS_DB_PWD) class SmsNotification(BaseModel)...
import re from typing import List import redis import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel import config from tools import utils app = FastAPI() redis_client = redis.Redis(host=config.REDIS_DB_HOST, password=config.REDIS_DB_PWD) class SmsNotification(BaseModel)...
utils.logger.info(f"Received SMS notification: {sms.platform}, {sms.current_number}") sms_code = extract_verification_code(sms.sms_content) if sms_code: # Save the verification code in Redis and set the expiration time to 3 minutes. key = f"{sms.platform}_{sms.current_number}" redis_...
""" Receive SMS notification and send it to Redis. Args: sms: { "platform": "xhs", "from_number": "1069421xxx134", "sms_content": "【小红书】您的验证码是: 171959, 3分钟内有效。请勿向他人泄漏。如非本人操作,可忽略本消息。", "timestamp": "1686720601614", ...
36
517
148
665
import re from typing import List import redis import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel import config from tools import utils app = FastAPI() redis_client = redis.Redis(host=config.REDIS_DB_HOST, password=config.REDIS_DB_PWD) class SmsNotification(BaseModel)...
import re from typing import List import redis import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel import config from tools import utils app = FastAPI() redis_client = redis.Redis(host=config.REDIS_DB_HOST, password=config.REDIS_DB_PWD) class SmsNotification(BaseModel)...
2,211
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/bilibili/bilibili_store_sql.py
43,44
1,103
update_content_by_content_id
53,59
44,59
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() effect_row: int = await async_db_conn.update_table("bilibili_video", content_item, "video_id", content_id) return effect_row
""" 更新一条记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...) Args: content_id: content_item: Returns: """ async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() effect_row: int = await async_db_conn.update_table("bilibili_video", content_item, "video_id", content_id) return effect_row ...
14
964
80
1,044
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
2,212
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/douyin/douyin_store_sql.py
59,60
1,103
query_comment_by_comment_id
68,76
60,76
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() sql: str = f"select * from douyin_aweme_comment where comment_id = '{comment_id}'" rows: List[Dict] = await async_db_conn.query(sql) if len(rows) > 0: return rows[0] return dict()
""" 查询一条评论内容 Args: comment_id: Returns: """ async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() sql: str = f"select * from douyin_aweme_comment where comment_id = '{comment_id}'" rows: List[Dict] = await async_db_conn.query(sql) if len(rows) > 0: return rows[0]...
28
947
111
1,058
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
2,213
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/kuaishou/kuaishou_store_sql.py
43,44
1,103
update_content_by_content_id
53,59
44,59
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() effect_row: int = await async_db_conn.update_table("kuaishou_video", content_item, "video_id", content_id) return effect_row
""" 更新一条记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...) Args: content_id: content_item: Returns: """ async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() effect_row: int = await async_db_conn.update_table("kuaishou_video", content_item, "video_id", content_id) return effect_row ...
14
969
81
1,050
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
2,214
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/weibo/weibo_store_image.py
28,29
14,54
make_save_file_name
WeiboStoreImage
37,39
29,39
class WeiboStoreImage(AbstractStoreImage): image_store_path: str = "data/weibo/images" async def store_image(self, image_content_item: Dict): """ store content Args: content_item: Returns: """ await self.save_image(image_content_item.get("pic_id"), ...
class WeiboStoreImage(AbstractStoreImage): image_store_path: str = "data/weibo/images" async def store_image(self, image_content_item: Dict): """ store content Args: content_item: Returns: """ await self.save_image(image_content_item.get("pic_id"), ...
return f"{self.image_store_path}/{picid}.{extension_file_name}"
""" make save file name by store type Args: picid: image id Returns: """ return f"{self.image_store_path}/{picid}.{extension_file_name}"
2
393
28
421
# -*- coding: utf-8 -*- # @Author : Erm # @Time : 2024/4/9 17:35 # @Desc : 微博保存图片类 import pathlib from typing import Dict import aiofiles from base.base_crawler import AbstractStoreImage from tools import utils class WeiboStoreImage(AbstractStoreImage): image_store_path: str = "data/weibo/images" as...
# -*- coding: utf-8 -*- # @Author : Erm # @Time : 2024/4/9 17:35 # @Desc : 微博保存图片类 import pathlib from typing import Dict import aiofiles from base.base_crawler import AbstractStoreImage from tools import utils class WeiboStoreImage(AbstractStoreImage): image_store_path: str = "data/weibo/images" as...
2,215
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/weibo/weibo_store_sql.py
59,60
1,103
query_comment_by_comment_id
68,76
60,76
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() sql: str = f"select * from weibo_note_comment where comment_id = '{comment_id}'" rows: List[Dict] = await async_db_conn.query(sql) if len(rows) > 0: return rows[0] return dict()
""" 查询一条评论内容 Args: comment_id: Returns: """ async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() sql: str = f"select * from weibo_note_comment where comment_id = '{comment_id}'" rows: List[Dict] = await async_db_conn.query(sql) if len(rows) > 0: return rows[0] ...
28
936
110
1,046
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
2,216
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/store/xhs/xhs_store_sql.py
76,77
1,149
add_new_comment
85,90
77,90
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() last_row_id: int = await async_db_conn.item_to_table("xhs_note_comment", comment_item) return last_row_id
""" 新增一条评论记录 Args: comment_item: Returns: """ async_db_conn: AsyncMysqlDB = media_crawler_db_var.get() last_row_id: int = await async_db_conn.item_to_table("xhs_note_comment", comment_item) return last_row_id
12
1,386
76
1,462
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2024/4/6 15:30 # @Desc : sql接口集合 from typing import Dict, List from db import AsyncMysqlDB from var import media_crawler_db_var async def query_content_by_content_id(content_id: str) -> Dict: """ 查询一条内容记录(xhs的帖子 | 抖音的视频 | 微博 | 快手视频 ...)...
2,217
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/tools/easing.py
47,48
1,71
ease_out_elastic
48,57
48,57
#!/usr/bin/env python # -*- coding: utf-8 -*- # copy from https://github.com/aneasystone/selenium-test/blob/master/12-slider-captcha.py # thanks to aneasystone for his great work import math from typing import List, Tuple import numpy as np # https://github.com/gdsmith/jquery.easing/blob/master/jquery.easing.js def ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # copy from https://github.com/aneasystone/selenium-test/blob/master/12-slider-captcha.py # thanks to aneasystone for his great work import math from typing import List, Tuple import numpy as np # https://github.com/gdsmith/jquery.easing/blob/master/jquery.easing.js def ...
if x == 0: return 0 elif x == 1: return 1 else: c4 = (2 * math.pi) / 3 return pow(2, -10 * x) * math.sin((x * 10 - 0.75) * c4) + 1
if x == 0: return 0 elif x == 1: return 1 else: c4 = (2 * math.pi) / 3 return pow(2, -10 * x) * math.sin((x * 10 - 0.75) * c4) + 1
35
587
90
677
#!/usr/bin/env python # -*- coding: utf-8 -*- # copy from https://github.com/aneasystone/selenium-test/blob/master/12-slider-captcha.py # thanks to aneasystone for his great work import math from typing import List, Tuple import numpy as np # https://github.com/gdsmith/jquery.easing/blob/master/jquery.easing.js def ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # copy from https://github.com/aneasystone/selenium-test/blob/master/12-slider-captcha.py # thanks to aneasystone for his great work import math from typing import List, Tuple import numpy as np # https://github.com/gdsmith/jquery.easing/blob/master/jquery.easing.js def ...
2,218
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/tools/time_util.py
87,88
1,107
rfc2822_to_timestamp
88,103
88,103
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 12:52 # @Desc : 时间相关的工具函数 import time from datetime import datetime, timedelta, timezone def get_current_timestamp() -> int: """ 获取当前的时间戳(13 位):1701493264496 :return: """ return int(time.time() * 1000) def get_cur...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 12:52 # @Desc : 时间相关的工具函数 import time from datetime import datetime, timedelta, timezone def get_current_timestamp() -> int: """ 获取当前的时间戳(13 位):1701493264496 :return: """ return int(time.time() * 1000) def get_cur...
# 定义RFC 2822格式 rfc2822_format = "%a %b %d %H:%M:%S %z %Y" # 将RFC 2822时间字符串转换为datetime对象 dt_object = datetime.strptime(rfc2822_time, rfc2822_format) # 将datetime对象转换为UTC时间 dt_utc = dt_object.replace(tzinfo=timezone.utc) # 计算UTC时间对应的Unix时间戳 timestamp = int(dt_utc.timestamp()) return...
# 定义RFC 2822格式 rfc2822_format = "%a %b %d %H:%M:%S %z %Y" # 将RFC 2822时间字符串转换为datetime对象 dt_object = datetime.strptime(rfc2822_time, rfc2822_format) # 将datetime对象转换为UTC时间 dt_utc = dt_object.replace(tzinfo=timezone.utc) # 计算UTC时间对应的Unix时间戳 timestamp = int(dt_utc.timestamp()) return...
30
1,024
185
1,209
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 12:52 # @Desc : 时间相关的工具函数 import time from datetime import datetime, timedelta, timezone def get_current_timestamp() -> int: """ 获取当前的时间戳(13 位):1701493264496 :return: """ return int(time.time() * 1000) def get_cur...
# -*- coding: utf-8 -*- # @Author : relakkes@gmail.com # @Time : 2023/12/2 12:52 # @Desc : 时间相关的工具函数 import time from datetime import datetime, timedelta, timezone def get_current_timestamp() -> int: """ 获取当前的时间戳(13 位):1701493264496 :return: """ return int(time.time() * 1000) def get_cur...
2,219
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler
/home/hieuvd/dung_repo/raw/stars_01/NanmiCoder_MediaCrawler/MediaCrawler/tools/utils.py
8,9
1,21
init_loging_config
9,20
9,20
import logging from .crawler_util import * from .slider_util import * from .time_util import * def init_loging_config(): FILL_FUNC_BODYlogger = init_loging_config()
import logging from .crawler_util import * from .slider_util import * from .time_util import * def init_loging_config(): FILL_FUNC_BODYlogger = init_loging_config()
level = logging.INFO logging.basicConfig( level=level, format="%(asctime)s [%(threadName)s] %(name)s %(levelname)s (%(filename)s:%(lineno)d) - %(message)s", datefmt='%Y-%m-%d %H:%M:%S' ) _logger = logging.getLogger("MediaCrawler") _logger.setLevel(level) return _logger
level = logging.INFO logging.basicConfig( level=level, format="%(asctime)s [%(threadName)s] %(name)s %(levelname)s (%(filename)s:%(lineno)d) - %(message)s", datefmt='%Y-%m-%d %H:%M:%S' ) _logger = logging.getLogger("MediaCrawler") _logger.setLevel(level) return _logger
21
62
142
204
import logging from .crawler_util import * from .slider_util import * from .time_util import * def init_loging_config(): FILL_FUNC_BODYlogger = init_loging_config()
import logging from .crawler_util import * from .slider_util import * from .time_util import * def init_loging_config(): FILL_FUNC_BODYlogger = init_loging_config()
4,559
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2exp_models/audio2exp.py
13,14
6,42
test
Audio2Exp
14,42
14,42
class Audio2Exp(nn.Module): def __init__(self, netG, cfg, device, prepare_training_loss=False): super(Audio2Exp, self).__init__() self.cfg = cfg self.device = device self.netG = netG.to(device) def test(self, batch): FILL_FUNC_BODY
class Audio2Exp(nn.Module): def __init__(self, netG, cfg, device, prepare_training_loss=False): super(Audio2Exp, self).__init__() self.cfg = cfg self.device = device self.netG = netG.to(device) def test(self, batch): FILL_FUNC_BODY
mel_input = batch['indiv_mels'] # bs T 1 80 16 bs = mel_input.shape[0] T = mel_input.shape[1] exp_coeff_pred = [] for i in tqdm(range(0, T, 10),'audio2exp:'): # every 10 frames current_mel_input = mel_input[:,i:i+10] ...
mel_input = batch['indiv_mels'] # bs T 1 80 16 bs = mel_input.shape[0] T = mel_input.shape[1] exp_coeff_pred = [] for i in tqdm(range(0, T, 10),'audio2exp:'): # every 10 frames current_mel_input = mel_input[:,i:i+10] ...
89
97
386
483
from tqdm import tqdm import torch from torch import nn class Audio2Exp(nn.Module): def __init__(self, netG, cfg, device, prepare_training_loss=False): super(Audio2Exp, self).__init__() self.cfg = cfg self.device = device self.netG = netG.to(device) def test(self, batch): FILL...
from tqdm import tqdm import torch from torch import nn class Audio2Exp(nn.Module): def __init__(self, netG, cfg, device, prepare_training_loss=False): super(Audio2Exp, self).__init__() self.cfg = cfg self.device = device self.netG = netG.to(device) def test(self, batch): FILL...
4,560
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2exp_models/networks.py
16,17
5,26
forward
Conv2d
17,26
17,26
class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin, cout, kernel_size, stride, padding), ...
class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin, cout, kernel_size, stride, padding), ...
out = self.conv_block(x) if self.residual: out += x if self.use_act: return self.act(out) else: return out
out = self.conv_block(x) if self.residual: out += x if self.use_act: return self.act(out) else: return out
15
167
63
230
import torch import torch.nn.functional as F from torch import nn class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn....
import torch import torch.nn.functional as F from torch import nn class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn....
4,561
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2exp_models/networks.py
67,68
26,75
forward
SimpleWrapperV2
68,75
68,75
class SimpleWrapperV2(nn.Module): def __init__(self) -> None: super().__init__() self.audio_encoder = nn.Sequential( Conv2d(1, 32, kernel_size=3, stride=1, padding=1), Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True), Conv2d(32, 32, kernel_size=3,...
class SimpleWrapperV2(nn.Module): def __init__(self) -> None: super().__init__() self.audio_encoder = nn.Sequential( Conv2d(1, 32, kernel_size=3, stride=1, padding=1), Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True), Conv2d(32, 32, kernel_size=3,...
x = self.audio_encoder(x).view(x.size(0), -1) ref_reshape = ref.reshape(x.size(0), -1) ratio = ratio.reshape(x.size(0), -1) y = self.mapping1(torch.cat([x, ref_reshape, ratio], dim=1)) out = y.reshape(ref.shape[0], ref.shape[1], -1) #+ ref # resudial return out
x = self.audio_encoder(x).view(x.size(0), -1) ref_reshape = ref.reshape(x.size(0), -1) ratio = ratio.reshape(x.size(0), -1) y = self.mapping1(torch.cat([x, ref_reshape, ratio], dim=1)) out = y.reshape(ref.shape[0], ref.shape[1], -1) #+ ref # resudial return out
29
792
135
927
import torch import torch.nn.functional as F from torch import nn class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn....
import torch import torch.nn.functional as F from torch import nn class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act = True, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn....
4,562
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/audio2pose.py
48,49
7,95
test
Audio2Pose
49,95
49,95
class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super().__init__() self.cfg = cfg self.seq_len = cfg.MODEL.CVAE.SEQ_LEN self.latent_dim = cfg.MODEL.CVAE.LATENT_SIZE self.device = device self.audio_encoder = AudioEncoder(wav2li...
class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super().__init__() self.cfg = cfg self.seq_len = cfg.MODEL.CVAE.SEQ_LEN self.latent_dim = cfg.MODEL.CVAE.LATENT_SIZE self.device = device self.audio_encoder = AudioEncoder(wav2li...
batch = {} ref = x['ref'] #bs 1 70 batch['ref'] = x['ref'][:,0,-6:] batch['class'] = x['class'] bs = ref.shape[0] indiv_mels= x['indiv_mels'] # bs T 1 80 16 indiv_mels_use = indiv_mels[:, 1:] # we regar...
batch = {} ref = x['ref'] #bs 1 70 batch['ref'] = x['ref'][:,0,-6:] batch['class'] = x['class'] bs = ref.shape[0] indiv_mels= x['indiv_mels'] # bs T 1 80 16 indiv_mels_use = indiv_mels[:, 1:] # we regar...
160
627
778
1,405
import torch from torch import nn from src.audio2pose_models.cvae import CVAE from src.audio2pose_models.discriminator import PoseSequenceDiscriminator from src.audio2pose_models.audio_encoder import AudioEncoder class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super...
import torch from torch import nn from src.audio2pose_models.cvae import CVAE from src.audio2pose_models.discriminator import PoseSequenceDiscriminator from src.audio2pose_models.audio_encoder import AudioEncoder class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super...
4,563
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/audio_encoder.py
54,55
21,65
forward
AudioEncoder
55,65
55,65
class AudioEncoder(nn.Module): def __init__(self, wav2lip_checkpoint, device): super(AudioEncoder, self).__init__() self.audio_encoder = nn.Sequential( Conv2d(1, 32, kernel_size=3, stride=1, padding=1), Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True), ...
class AudioEncoder(nn.Module): def __init__(self, wav2lip_checkpoint, device): super(AudioEncoder, self).__init__() self.audio_encoder = nn.Sequential( Conv2d(1, 32, kernel_size=3, stride=1, padding=1), Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True), ...
# audio_sequences = (B, T, 1, 80, 16) B = audio_sequences.size(0) audio_sequences = torch.cat([audio_sequences[:, i] for i in range(audio_sequences.size(1))], dim=0) audio_embedding = self.audio_encoder(audio_sequences) # B, 512, 1, 1 dim = audio_embedding.shape[1] audi...
# audio_sequences = (B, T, 1, 80, 16) B = audio_sequences.size(0) audio_sequences = torch.cat([audio_sequences[:, i] for i in range(audio_sequences.size(1))], dim=0) audio_embedding = self.audio_encoder(audio_sequences) # B, 512, 1, 1 dim = audio_embedding.shape[1] audi...
43
685
195
880
import torch from torch import nn from torch.nn import functional as F class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin,...
import torch from torch import nn from torch.nn import functional as F class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin,...
4,564
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/audio_encoder.py
15,16
5,21
forward
Conv2d
16,21
16,21
class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin, cout, kernel_size, stride, padding), nn.Bat...
class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin, cout, kernel_size, stride, padding), nn.Bat...
out = self.conv_block(x) if self.residual: out += x return self.act(out)
out = self.conv_block(x) if self.residual: out += x return self.act(out)
10
150
40
190
import torch from torch import nn from torch.nn import functional as F class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin,...
import torch from torch import nn from torch.nn import functional as F class Conv2d(nn.Module): def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, *args, **kwargs): super().__init__(*args, **kwargs) self.conv_block = nn.Sequential( nn.Conv2d(cin,...
4,566
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/cvae.py
30,31
13,51
reparameterize
CVAE
31,35
31,35
class CVAE(nn.Module): def __init__(self, cfg): super().__init__() encoder_layer_sizes = cfg.MODEL.CVAE.ENCODER_LAYER_SIZES decoder_layer_sizes = cfg.MODEL.CVAE.DECODER_LAYER_SIZES latent_size = cfg.MODEL.CVAE.LATENT_SIZE num_classes = cfg.DATASET.NUM_CLASSES audio_em...
class CVAE(nn.Module): def __init__(self, cfg): super().__init__() encoder_layer_sizes = cfg.MODEL.CVAE.ENCODER_LAYER_SIZES decoder_layer_sizes = cfg.MODEL.CVAE.DECODER_LAYER_SIZES latent_size = cfg.MODEL.CVAE.LATENT_SIZE num_classes = cfg.DATASET.NUM_CLASSES audio_em...
std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return mu + eps * std
std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return mu + eps * std
14
497
45
542
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
4,567
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/cvae.py
123,124
99,150
forward
DECODER
124,150
124,150
class DECODER(nn.Module): def __init__(self, layer_sizes, latent_size, num_classes, audio_emb_in_size, audio_emb_out_size, seq_len): super().__init__() self.resunet = ResUnet() self.num_classes = num_classes self.seq_len = seq_len self.MLP = nn.Sequential()...
class DECODER(nn.Module): def __init__(self, layer_sizes, latent_size, num_classes, audio_emb_in_size, audio_emb_out_size, seq_len): super().__init__() self.resunet = ResUnet() self.num_classes = num_classes self.seq_len = seq_len self.MLP = nn.Sequential()...
z = batch['z'] #bs latent_size bs = z.shape[0] class_id = batch['class'] ref = batch['ref'] #bs 6 audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size #print('audio_in:...
z = batch['z'] #bs latent_size bs = z.shape[0] class_id = batch['class'] ref = batch['ref'] #bs 6 audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size #print('audio_in:...
93
392
429
821
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
4,568
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/cvae.py
73,74
51,99
forward
ENCODER
74,99
74,99
class ENCODER(nn.Module): def __init__(self, layer_sizes, latent_size, num_classes, audio_emb_in_size, audio_emb_out_size, seq_len): super().__init__() self.resunet = ResUnet() self.num_classes = num_classes self.seq_len = seq_len self.MLP = nn.Sequential()...
class ENCODER(nn.Module): def __init__(self, layer_sizes, latent_size, num_classes, audio_emb_in_size, audio_emb_out_size, seq_len): super().__init__() self.resunet = ResUnet() self.num_classes = num_classes self.seq_len = seq_len self.MLP = nn.Sequential()...
class_id = batch['class'] pose_motion_gt = batch['pose_motion_gt'] #bs seq_len 6 ref = batch['ref'] #bs 6 bs = pose_motion_gt.shape[0] audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size ...
class_id = batch['class'] pose_motion_gt = batch['pose_motion_gt'] #bs seq_len 6 ref = batch['ref'] #bs 6 bs = pose_motion_gt.shape[0] audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size ...
82
380
407
787
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot class CV...
4,569
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/discriminator.py
49,50
5,59
forward
ConvNormRelu
50,59
50,59
class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_size is None: if downsample: kernel_size...
class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_size is None: if downsample: kernel_size...
x = self.conv(x) if isinstance(self.norm, nn.InstanceNorm1d): x = self.norm(x.permute((0, 2, 1))).permute((0, 2, 1)) # normalize on [C] else: x = self.norm(x) x = self.act(x) return x
x = self.conv(x) if isinstance(self.norm, nn.InstanceNorm1d): x = self.norm(x.permute((0, 2, 1))).permute((0, 2, 1)) # normalize on [C] else: x = self.norm(x) x = self.act(x) return x
26
482
110
592
import torch import torch.nn.functional as F from torch import nn class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_s...
import torch import torch.nn.functional as F from torch import nn class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_s...
4,570
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/discriminator.py
72,73
59,77
forward
PoseSequenceDiscriminator
73,77
73,77
class PoseSequenceDiscriminator(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg leaky = self.cfg.MODEL.DISCRIMINATOR.LEAKY_RELU self.seq = nn.Sequential( ConvNormRelu('1d', cfg.MODEL.DISCRIMINATOR.INPUT_CHANNELS, 256, downsample=True, leaky=leaky),...
class PoseSequenceDiscriminator(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg leaky = self.cfg.MODEL.DISCRIMINATOR.LEAKY_RELU self.seq = nn.Sequential( ConvNormRelu('1d', cfg.MODEL.DISCRIMINATOR.INPUT_CHANNELS, 256, downsample=True, leaky=leaky),...
x = x.reshape(x.size(0), x.size(1), -1).transpose(1, 2) x = self.seq(x) x = x.squeeze(1) return x
x = x.reshape(x.size(0), x.size(1), -1).transpose(1, 2) x = self.seq(x) x = x.squeeze(1) return x
14
310
61
371
import torch import torch.nn.functional as F from torch import nn class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_s...
import torch import torch.nn.functional as F from torch import nn class ConvNormRelu(nn.Module): def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): super().__init__() if kernel_s...
4,571
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py
95,96
59,104
_init_weights
ASPP
96,104
96,104
class ASPP(nn.Module): def __init__(self, in_dims, out_dims, rate=[6, 12, 18]): super(ASPP, self).__init__() self.aspp_block1 = nn.Sequential( nn.Conv2d( in_dims, out_dims, 3, stride=1, padding=rate[0], dilation=rate[0] ), nn.ReLU(inplace=True), ...
class ASPP(nn.Module): def __init__(self, in_dims, out_dims, rate=[6, 12, 18]): super(ASPP, self).__init__() self.aspp_block1 = nn.Sequential( nn.Conv2d( in_dims, out_dims, 3, stride=1, padding=rate[0], dilation=rate[0] ), nn.ReLU(inplace=True), ...
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
13
490
92
582
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
4,572
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py
137,138
114,141
forward
AttentionBlock
138,141
138,141
class AttentionBlock(nn.Module): def __init__(self, input_encoder, input_decoder, output_dim): super(AttentionBlock, self).__init__() self.conv_encoder = nn.Sequential( nn.BatchNorm2d(input_encoder), nn.ReLU(), nn.Conv2d(input_encoder, output_dim, 3, padding=1), ...
class AttentionBlock(nn.Module): def __init__(self, input_encoder, input_decoder, output_dim): super(AttentionBlock, self).__init__() self.conv_encoder = nn.Sequential( nn.BatchNorm2d(input_encoder), nn.ReLU(), nn.Conv2d(input_encoder, output_dim, 3, padding=1), ...
out = self.conv_encoder(x1) + self.conv_decoder(x2) out = self.conv_attn(out) return out * x2
out = self.conv_encoder(x1) + self.conv_decoder(x2) out = self.conv_attn(out) return out * x2
12
288
47
335
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
4,573
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py
24,25
5,29
forward
ResidualConv
25,29
25,29
class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( input_dim, output_dim, kernel_size=3,...
class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( input_dim, output_dim, kernel_size=3,...
return self.conv_block(x) + self.conv_skip(x)
return self.conv_block(x) + self.conv_skip(x)
4
264
27
291
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
4,574
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py
52,53
41,59
forward
Squeeze_Excite_Block
53,59
53,59
class Squeeze_Excite_Block(nn.Module): def __init__(self, channel, reduction=16): super(Squeeze_Excite_Block, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True),...
class Squeeze_Excite_Block(nn.Module): def __init__(self, channel, reduction=16): super(Squeeze_Excite_Block, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True),...
b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x)
b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x)
20
167
75
242
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
4,575
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker
/home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py
37,38
29,41
forward
Upsample
38,41
38,41
class Upsample(nn.Module): def __init__(self, input_dim, output_dim, kernel, stride): super(Upsample, self).__init__() self.upsample = nn.ConvTranspose2d( input_dim, output_dim, kernel_size=kernel, stride=stride ) def forward(self, x): FILL_FUNC_BODY
class Upsample(nn.Module): def __init__(self, input_dim, output_dim, kernel, stride): super(Upsample, self).__init__() self.upsample = nn.ConvTranspose2d( input_dim, output_dim, kernel_size=kernel, stride=stride ) def forward(self, x): FILL_FUNC_BODY
return self.upsample(x)
return self.upsample(x)
2
107
15
122
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...
import torch.nn as nn import torch class ResidualConv(nn.Module): def __init__(self, input_dim, output_dim, stride, padding): super(ResidualConv, self).__init__() self.conv_block = nn.Sequential( nn.BatchNorm2d(input_dim), nn.ReLU(), nn.Conv2d( ...