code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def __init__( self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, ffn_bias=True, proj_bias=True, drop_path_rate=0.0, drop_path_uniform=False, init_values=None, # for layerscale: None or 0 => no layerscale embed_layer=PatchEmbed, act_layer=nn.GELU, block_fn=Block, ffn_layer="mlp", block_chunks=1, ): """ Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True proj_bias (bool): enable bias for proj in attn if True ffn_bias (bool): enable bias for ffn if True drop_path_rate (float): stochastic depth rate drop_path_uniform (bool): apply uniform drop rate across blocks weight_init (str): weight init scheme init_values (float): layer-scale init values embed_layer (nn.Module): patch embedding layer act_layer (nn.Module): MLP activation layer block_fn (nn.Module): transformer block class ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" block_chunks: (int) split block sequence into block_chunks units for FSDP wrap """ super().__init__() norm_layer = partial(nn.LayerNorm, eps=1e-6) self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 1 self.n_blocks = depth self.num_heads = num_heads self.patch_size = patch_size self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) if drop_path_uniform is True: dpr = [drop_path_rate] * depth else: dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule if ffn_layer == "mlp": logger.info("using MLP layer as FFN") ffn_layer = Mlp elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": logger.info("using SwiGLU layer as FFN") ffn_layer = SwiGLUFFNFused elif ffn_layer == "identity": logger.info("using Identity layer as FFN") def f(*args, **kwargs): return nn.Identity() ffn_layer = f else: raise NotImplementedError blocks_list = [ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_bias=proj_bias, ffn_bias=ffn_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, ffn_layer=ffn_layer, init_values=init_values, ) for i in range(depth) ] if block_chunks > 0: self.chunked_blocks = True chunked_blocks = [] chunksize = depth // block_chunks for i in range(0, depth, chunksize): # this is to keep the block index consistent if we chunk the block list chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) else: self.chunked_blocks = False self.blocks = nn.ModuleList(blocks_list) self.norm = norm_layer(embed_dim) self.head = nn.Identity() self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) self.init_weights()
Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True proj_bias (bool): enable bias for proj in attn if True ffn_bias (bool): enable bias for ffn if True drop_path_rate (float): stochastic depth rate drop_path_uniform (bool): apply uniform drop rate across blocks weight_init (str): weight init scheme init_values (float): layer-scale init values embed_layer (nn.Module): patch embedding layer act_layer (nn.Module): MLP activation layer block_fn (nn.Module): transformer block class ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
__init__
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/models/vision_transformer.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/models/vision_transformer.py
Apache-2.0
def pairwise_NNs_inner(self, x): """ Pairwise nearest neighbors for L2-normalized vectors. Uses Torch rather than Faiss to remain on GPU. """ # parwise dot products (= inverse distance) dots = torch.mm(x, x.t()) n = x.shape[0] dots.view(-1)[:: (n + 1)].fill_(-1) # Trick to fill diagonal with -1 # max inner prod -> min distance _, I = torch.max(dots, dim=1) # noqa: E741 return I
Pairwise nearest neighbors for L2-normalized vectors. Uses Torch rather than Faiss to remain on GPU.
pairwise_NNs_inner
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/loss/koleo_loss.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/loss/koleo_loss.py
Apache-2.0
def forward(self, student_output, eps=1e-8): """ Args: student_output (BxD): backbone output of student """ with torch.cuda.amp.autocast(enabled=False): student_output = F.normalize(student_output, eps=eps, p=2, dim=-1) I = self.pairwise_NNs_inner(student_output) # noqa: E741 distances = self.pdist(student_output, student_output[I]) # BxD, BxD -> B loss = -torch.log(distances + eps).mean() return loss
Args: student_output (BxD): backbone output of student
forward
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/loss/koleo_loss.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/loss/koleo_loss.py
Apache-2.0
def forward(self, student_patch_tokens, teacher_patch_tokens, student_masks_flat): """ Cross-entropy between softmax outputs of the teacher and student networks. student_patch_tokens: (B, N, D) tensor teacher_patch_tokens: (B, N, D) tensor student_masks_flat: (B, N) tensor """ t = teacher_patch_tokens s = student_patch_tokens loss = torch.sum(t * F.log_softmax(s / self.student_temp, dim=-1), dim=-1) loss = torch.sum(loss * student_masks_flat.float(), dim=-1) / student_masks_flat.sum(dim=-1).clamp(min=1.0) return -loss.mean()
Cross-entropy between softmax outputs of the teacher and student networks. student_patch_tokens: (B, N, D) tensor teacher_patch_tokens: (B, N, D) tensor student_masks_flat: (B, N) tensor
forward
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/loss/ibot_patch_loss.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/loss/ibot_patch_loss.py
Apache-2.0
def forward(self, student_output_list, teacher_out_softmaxed_centered_list): """ Cross-entropy between softmax outputs of the teacher and student networks. """ # TODO: Use cross_entropy_distribution here total_loss = 0 for s in student_output_list: lsm = F.log_softmax(s / self.student_temp, dim=-1) for t in teacher_out_softmaxed_centered_list: loss = torch.sum(t * lsm, dim=-1) total_loss -= loss.mean() return total_loss
Cross-entropy between softmax outputs of the teacher and student networks.
forward
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/loss/dino_clstoken_loss.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/loss/dino_clstoken_loss.py
Apache-2.0
def get_attn_bias_and_cat(x_list, branges=None): """ this will perform the index select, cat the tensors, and provide the attn_bias from cache """ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) if all_shapes not in attn_bias_cache.keys(): seqlens = [] for b, x in zip(batch_sizes, x_list): for _ in range(b): seqlens.append(x.shape[1]) attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) attn_bias._batch_sizes = batch_sizes attn_bias_cache[all_shapes] = attn_bias if branges is not None: cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) else: tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) cat_tensors = torch.cat(tensors_bs1, dim=1) return attn_bias_cache[all_shapes], cat_tensors
this will perform the index select, cat the tensors, and provide the attn_bias from cache
get_attn_bias_and_cat
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/layers/block.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/layers/block.py
Apache-2.0
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: """ x_list contains a list of tensors to nest together and run """ assert isinstance(self.attn, MemEffAttention) if self.training and self.sample_drop_ratio > 0.0: def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.attn(self.norm1(x), attn_bias=attn_bias) def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.mlp(self.norm2(x)) x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, ) x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, ) return x_list else: def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls2(self.mlp(self.norm2(x))) attn_bias, x = get_attn_bias_and_cat(x_list) x = x + attn_residual_func(x, attn_bias=attn_bias) x = x + ffn_residual_func(x) return attn_bias.split(x)
x_list contains a list of tensors to nest together and run
forward_nested
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/layers/block.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/layers/block.py
Apache-2.0
def is_enabled() -> bool: """ Returns: True if distributed training is enabled """ return dist.is_available() and dist.is_initialized()
Returns: True if distributed training is enabled
is_enabled
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def get_global_size() -> int: """ Returns: The number of processes in the process group """ return dist.get_world_size() if is_enabled() else 1
Returns: The number of processes in the process group
get_global_size
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def get_global_rank() -> int: """ Returns: The rank of the current process within the global process group. """ return dist.get_rank() if is_enabled() else 0
Returns: The rank of the current process within the global process group.
get_global_rank
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def get_local_rank() -> int: """ Returns: The rank of the current process within the local (per-machine) process group. """ if not is_enabled(): return 0 assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE return _LOCAL_RANK
Returns: The rank of the current process within the local (per-machine) process group.
get_local_rank
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def get_local_size() -> int: """ Returns: The size of the per-machine process group, i.e. the number of processes per machine. """ if not is_enabled(): return 1 assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE return _LOCAL_WORLD_SIZE
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
get_local_size
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def is_main_process() -> bool: """ Returns: True if the current process is the main one. """ return get_global_rank() == 0
Returns: True if the current process is the main one.
is_main_process
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def _restrict_print_to_main_process() -> None: """ This function disables printing when not in the main process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop("force", False) if is_main_process() or force: builtin_print(*args, **kwargs) __builtin__.print = print
This function disables printing when not in the main process
_restrict_print_to_main_process
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def enable(*, set_cuda_current_device: bool = True, overwrite: bool = False, allow_nccl_timeout: bool = False): """Enable distributed mode Args: set_cuda_current_device: If True, call torch.cuda.set_device() to set the current PyTorch CUDA device to the one matching the local rank. overwrite: If True, overwrites already set variables. Else fails. """ global _LOCAL_RANK, _LOCAL_WORLD_SIZE if _LOCAL_RANK >= 0 or _LOCAL_WORLD_SIZE >= 0: raise RuntimeError("Distributed mode has already been enabled") torch_env = _TorchDistributedEnvironment() torch_env.export(overwrite=overwrite) if set_cuda_current_device: torch.cuda.set_device(torch_env.local_rank) if allow_nccl_timeout: # This allows to use torch distributed timeout in a NCCL backend key, value = "NCCL_ASYNC_ERROR_HANDLING", "1" if not overwrite: _check_env_variable(key, value) os.environ[key] = value dist.init_process_group(backend="nccl") dist.barrier() # Finalize setup _LOCAL_RANK = torch_env.local_rank _LOCAL_WORLD_SIZE = torch_env.local_world_size _restrict_print_to_main_process()
Enable distributed mode Args: set_cuda_current_device: If True, call torch.cuda.set_device() to set the current PyTorch CUDA device to the one matching the local rank. overwrite: If True, overwrites already set variables. Else fails.
enable
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/distributed/__init__.py
Apache-2.0
def synchronize_between_processes(self): """ Distributed synchronization of the metric Warning: does not synchronize the deque! """ if not distributed.is_enabled(): return t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") torch.distributed.barrier() torch.distributed.all_reduce(t) t = t.tolist() self.count = int(t[0]) self.total = t[1]
Distributed synchronization of the metric Warning: does not synchronize the deque!
synchronize_between_processes
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/logging/helpers.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/logging/helpers.py
Apache-2.0
def _configure_logger( name: Optional[str] = None, *, level: int = logging.DEBUG, output: Optional[str] = None, ): """ Configure a logger. Adapted from Detectron2. Args: name: The name of the logger to configure. level: The logging level to use. output: A file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. Returns: The configured logger. """ logger = logging.getLogger(name) logger.setLevel(level) logger.propagate = False # Loosely match Google glog format: # [IWEF]yyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg # but use a shorter timestamp and include the logger name: # [IWEF]yyyymmdd hh:mm:ss logger threadid file:line] msg fmt_prefix = "%(levelname).1s%(asctime)s %(process)s %(name)s %(filename)s:%(lineno)s] " fmt_message = "%(message)s" fmt = fmt_prefix + fmt_message datefmt = "%Y%m%d %H:%M:%S" formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) # stdout logging for main worker only if distributed.is_main_process(): handler = logging.StreamHandler(stream=sys.stdout) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) logger.addHandler(handler) # file logging for all workers if output: if os.path.splitext(output)[-1] in (".txt", ".log"): filename = output else: filename = os.path.join(output, "logs", "log.txt") if not distributed.is_main_process(): global_rank = distributed.get_global_rank() filename = filename + ".rank{}".format(global_rank) os.makedirs(os.path.dirname(filename), exist_ok=True) handler = logging.StreamHandler(open(filename, "a")) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) logger.addHandler(handler) return logger
Configure a logger. Adapted from Detectron2. Args: name: The name of the logger to configure. level: The logging level to use. output: A file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. Returns: The configured logger.
_configure_logger
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/logging/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/logging/__init__.py
Apache-2.0
def setup_logging( output: Optional[str] = None, *, name: Optional[str] = None, level: int = logging.DEBUG, capture_warnings: bool = True, ) -> None: """ Setup logging. Args: output: A file name or a directory to save log files. If None, log files will not be saved. If output ends with ".txt" or ".log", it is assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name: The name of the logger to configure, by default the root logger. level: The logging level to use. capture_warnings: Whether warnings should be captured as logs. """ logging.captureWarnings(capture_warnings) _configure_logger(name, level=level, output=output)
Setup logging. Args: output: A file name or a directory to save log files. If None, log files will not be saved. If output ends with ".txt" or ".log", it is assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name: The name of the logger to configure, by default the root logger. level: The logging level to use. capture_warnings: Whether warnings should be captured as logs.
setup_logging
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/logging/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/logging/__init__.py
Apache-2.0
def _generate_randperm_indices(*, size: int, generator: torch.Generator): """Generate the indices of a random permutation.""" dtype = _get_torch_dtype(size) # This is actually matching PyTorch's CPU implementation, see: https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/TensorFactories.cpp#L900-L921 perm = torch.arange(size, dtype=dtype) for i in range(size): j = torch.randint(i, size, size=(1,), generator=generator).item() # Always swap even if no-op value = perm[j].item() perm[j] = perm[i].item() perm[i] = value yield value
Generate the indices of a random permutation.
_generate_randperm_indices
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/data/samplers.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/data/samplers.py
Apache-2.0
def __call__(self, pic): """ Args: pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor. Returns: Tensor: Converted image. """ if isinstance(pic, torch.Tensor): return pic return super().__call__(pic)
Args: pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor. Returns: Tensor: Converted image.
__call__
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/data/transforms.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/data/transforms.py
Apache-2.0
def make_dataset( *, dataset_str: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ): """ Creates a dataset with the specified parameters. Args: dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN). transform: A transform to apply to images. target_transform: A transform to apply to targets. Returns: The created dataset. """ logger.info(f'using dataset: "{dataset_str}"') class_, kwargs = _parse_dataset_str(dataset_str) dataset = class_(transform=transform, target_transform=target_transform, **kwargs) logger.info(f"# of dataset samples: {len(dataset):,d}") # Aggregated datasets do not expose (yet) these attributes, so add them. if not hasattr(dataset, "transform"): setattr(dataset, "transform", transform) if not hasattr(dataset, "target_transform"): setattr(dataset, "target_transform", target_transform) return dataset
Creates a dataset with the specified parameters. Args: dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN). transform: A transform to apply to images. target_transform: A transform to apply to targets. Returns: The created dataset.
make_dataset
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/data/loaders.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/data/loaders.py
Apache-2.0
def make_data_loader( *, dataset, batch_size: int, num_workers: int, shuffle: bool = True, seed: int = 0, sampler_type: Optional[SamplerType] = SamplerType.INFINITE, sampler_size: int = -1, sampler_advance: int = 0, drop_last: bool = True, persistent_workers: bool = False, collate_fn: Optional[Callable[[List[T]], Any]] = None, ): """ Creates a data loader with the specified parameters. Args: dataset: A dataset (third party, LaViDa or WebDataset). batch_size: The size of batches to generate. num_workers: The number of workers to use. shuffle: Whether to shuffle samples. seed: The random seed to use. sampler_type: Which sampler to use: EPOCH, INFINITE, SHARDED_INFINITE, SHARDED_INFINITE_NEW, DISTRIBUTED or None. sampler_size: The number of images per epoch (when applicable) or -1 for the entire dataset. sampler_advance: How many samples to skip (when applicable). drop_last: Whether the last non-full batch of data should be dropped. persistent_workers: maintain the workers Dataset instances alive after a dataset has been consumed once. collate_fn: Function that performs batch collation """ sampler = _make_sampler( dataset=dataset, type=sampler_type, shuffle=shuffle, seed=seed, size=sampler_size, advance=sampler_advance, ) logger.info("using PyTorch data loader") data_loader = torch.utils.data.DataLoader( dataset, sampler=sampler, batch_size=batch_size, num_workers=num_workers, pin_memory=True, drop_last=drop_last, persistent_workers=persistent_workers, collate_fn=collate_fn, ) try: logger.info(f"# of batches: {len(data_loader):,d}") except TypeError: # data loader has no length logger.info("infinite data loader") return data_loader
Creates a data loader with the specified parameters. Args: dataset: A dataset (third party, LaViDa or WebDataset). batch_size: The size of batches to generate. num_workers: The number of workers to use. shuffle: Whether to shuffle samples. seed: The random seed to use. sampler_type: Which sampler to use: EPOCH, INFINITE, SHARDED_INFINITE, SHARDED_INFINITE_NEW, DISTRIBUTED or None. sampler_size: The number of images per epoch (when applicable) or -1 for the entire dataset. sampler_advance: How many samples to skip (when applicable). drop_last: Whether the last non-full batch of data should be dropped. persistent_workers: maintain the workers Dataset instances alive after a dataset has been consumed once. collate_fn: Function that performs batch collation
make_data_loader
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/data/loaders.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/data/loaders.py
Apache-2.0
def fix_random_seeds(seed=31): """ Fix random seeds. """ torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed)
Fix random seeds.
fix_random_seeds
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/utils/utils.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/utils/utils.py
Apache-2.0
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg_from_args(args) os.makedirs(args.output_dir, exist_ok=True) default_setup(args) apply_scaling_rules_to_cfg(cfg) write_config(cfg, args.output_dir) return cfg
Create configs and perform basic setups.
setup
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/utils/config.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/utils/config.py
Apache-2.0
def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12, force_is_backbone=False, chunked_blocks=False): """ Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. lr_decay_rate (float): base lr decay rate. num_layers (int): number of ViT blocks. Returns: lr decay rate for the given parameter. """ layer_id = num_layers + 1 if name.startswith("backbone") or force_is_backbone: if ".pos_embed" in name or ".patch_embed" in name or ".mask_token" in name or ".cls_token" in name: layer_id = 0 elif force_is_backbone and ( "pos_embed" in name or "patch_embed" in name or "mask_token" in name or "cls_token" in name ): layer_id = 0 elif ".blocks." in name and ".residual." not in name: layer_id = int(name[name.find(".blocks.") :].split(".")[2]) + 1 elif chunked_blocks and "blocks." in name and "residual." not in name: layer_id = int(name[name.find("blocks.") :].split(".")[2]) + 1 elif "blocks." in name and "residual." not in name: layer_id = int(name[name.find("blocks.") :].split(".")[1]) + 1 return lr_decay_rate ** (num_layers + 1 - layer_id)
Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. lr_decay_rate (float): base lr decay rate. num_layers (int): number of ViT blocks. Returns: lr decay rate for the given parameter.
get_vit_lr_decay_rate
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/utils/param_groups.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/utils/param_groups.py
Apache-2.0
def save(self, name: str, **kwargs: Any) -> None: """ Dump model and checkpointables to a file. Args: name (str): name of the file. kwargs (dict): extra arbitrary data to save. """ if not self.save_dir or not self.save_to_disk: return data = {} with FSDP.state_dict_type(self.model, StateDictType.LOCAL_STATE_DICT): data["model"] = self.model.state_dict() # data["model"] = self.model.state_dict() for key, obj in self.checkpointables.items(): data[key] = obj.state_dict() data.update(kwargs) basename = f"{name}.{rankstr()}.pth" save_file = os.path.join(self.save_dir, basename) assert os.path.basename(save_file) == basename, basename self.logger.info("Saving checkpoint to {}".format(save_file)) with self.path_manager.open(save_file, "wb") as f: torch.save(data, f) self.tag_last_checkpoint(basename)
Dump model and checkpointables to a file. Args: name (str): name of the file. kwargs (dict): extra arbitrary data to save.
save
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
Apache-2.0
def has_checkpoint(self) -> bool: """ Returns: bool: whether a checkpoint exists in the target directory. """ save_file = os.path.join(self.save_dir, f"last_checkpoint.{rankstr()}") return self.path_manager.exists(save_file)
Returns: bool: whether a checkpoint exists in the target directory.
has_checkpoint
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
Apache-2.0
def get_checkpoint_file(self) -> str: """ Returns: str: The latest checkpoint file in target directory. """ save_file = os.path.join(self.save_dir, f"last_checkpoint.{rankstr()}") try: with self.path_manager.open(save_file, "r") as f: last_saved = f.read().strip() except IOError: # if file doesn't exist, maybe because it has just been # deleted by a separate process return "" # pyre-fixme[6]: For 2nd param expected `Union[PathLike[str], str]` but got # `Union[bytes, str]`. return os.path.join(self.save_dir, last_saved)
Returns: str: The latest checkpoint file in target directory.
get_checkpoint_file
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
Apache-2.0
def tag_last_checkpoint(self, last_filename_basename: str) -> None: """ Tag the last checkpoint. Args: last_filename_basename (str): the basename of the last filename. """ if distributed.is_enabled(): torch.distributed.barrier() save_file = os.path.join(self.save_dir, f"last_checkpoint.{rankstr()}") with self.path_manager.open(save_file, "w") as f: f.write(last_filename_basename) # pyre-ignore
Tag the last checkpoint. Args: last_filename_basename (str): the basename of the last filename.
tag_last_checkpoint
python
LiheYoung/Depth-Anything
torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
https://github.com/LiheYoung/Depth-Anything/blob/master/torchhub/facebookresearch_dinov2_main/dinov2/fsdp/__init__.py
Apache-2.0
def _position(): """Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor. """ coord = _display.screen().root.query_pointer()._data return coord["root_x"], coord["root_y"]
Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor.
_position
python
asweigart/pyautogui
pyautogui/_pyautogui_x11.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_x11.py
BSD-3-Clause
def _keyDown(key): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are listed in pyautogui.KEY_NAMES. Returns: None """ if key not in keyboardMapping or keyboardMapping[key] is None: return if type(key) == int: fake_input(_display, X.KeyPress, key) _display.sync() return needsShift = pyautogui.isShiftCharacter(key) if needsShift: fake_input(_display, X.KeyPress, keyboardMapping['shift']) fake_input(_display, X.KeyPress, keyboardMapping[key]) if needsShift: fake_input(_display, X.KeyRelease, keyboardMapping['shift']) _display.sync()
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are listed in pyautogui.KEY_NAMES. Returns: None
_keyDown
python
asweigart/pyautogui
pyautogui/_pyautogui_x11.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_x11.py
BSD-3-Clause
def _keyUp(key): """Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in pyautogui.KEY_NAMES. Returns: None """ """ Release a given character key. Also works with character keycodes as integers, but not keysyms. """ if key not in keyboardMapping or keyboardMapping[key] is None: return if type(key) == int: keycode = key else: keycode = keyboardMapping[key] fake_input(_display, X.KeyRelease, keycode) _display.sync()
Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in pyautogui.KEY_NAMES. Returns: None
_keyUp
python
asweigart/pyautogui
pyautogui/_pyautogui_x11.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_x11.py
BSD-3-Clause
def _specialKeyEvent(key, upDown): """ Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac """ assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'" key_code = special_key_translate_table[key] ev = AppKit.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( Quartz.NSSystemDefined, # type (0,0), # location 0xa00 if upDown == 'down' else 0xb00, # flags 0, # timestamp 0, # window 0, # ctx 8, # subtype (key_code << 16) | ((0xa if upDown == 'down' else 0xb) << 8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.CGEvent())
Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
_specialKeyEvent
python
asweigart/pyautogui
pyautogui/_pyautogui_osx.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_osx.py
BSD-3-Clause
def _position(): """Returns the current xy coordinates of the mouse cursor as a two-integer tuple by calling the GetCursorPos() win32 function. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor. """ cursor = ctypes.wintypes.POINT() ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor)) return (cursor.x, cursor.y)
Returns the current xy coordinates of the mouse cursor as a two-integer tuple by calling the GetCursorPos() win32 function. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor.
_position
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _size(): """Returns the width and height of the screen as a two-integer tuple. Returns: (width, height) tuple of the screen size, in pixels. """ return (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
Returns the width and height of the screen as a two-integer tuple. Returns: (width, height) tuple of the screen size, in pixels.
_size
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _moveTo(x, y): """Send the mouse move event to Windows by calling SetCursorPos() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None """ ctypes.windll.user32.SetCursorPos(x, y)
Send the mouse move event to Windows by calling SetCursorPos() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
_moveTo
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _mouseDown(x, y, button): """Send the mouse down event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None """ if button not in (LEFT, MIDDLE, RIGHT): raise ValueError('button arg to _click() must be one of "left", "middle", or "right", not %s' % button) if button == LEFT: EV = MOUSEEVENTF_LEFTDOWN elif button == MIDDLE: EV = MOUSEEVENTF_MIDDLEDOWN elif button == RIGHT: EV = MOUSEEVENTF_RIGHTDOWN try: _sendMouseEvent(EV, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass
Send the mouse down event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None
_mouseDown
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _mouseUp(x, y, button): """Send the mouse up event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None """ if button not in (LEFT, MIDDLE, RIGHT): raise ValueError('button arg to _click() must be one of "left", "middle", or "right", not %s' % button) if button == LEFT: EV = MOUSEEVENTF_LEFTUP elif button == MIDDLE: EV = MOUSEEVENTF_MIDDLEUP elif button == RIGHT: EV = MOUSEEVENTF_RIGHTUP try: _sendMouseEvent(EV, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass
Send the mouse up event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None
_mouseUp
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _click(x, y, button): """Send the mouse click event to Windows by calling the mouse_event() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None """ if button not in (LEFT, MIDDLE, RIGHT): raise ValueError('button arg to _click() must be one of "left", "middle", or "right", not %s' % button) if button == LEFT: EV = MOUSEEVENTF_LEFTCLICK elif button == MIDDLE: EV = MOUSEEVENTF_MIDDLECLICK elif button ==RIGHT: EV = MOUSEEVENTF_RIGHTCLICK try: _sendMouseEvent(EV, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass
Send the mouse click event to Windows by calling the mouse_event() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
_click
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _sendMouseEvent(ev, x, y, dwData=0): """The helper function that actually makes the call to the mouse_event() win32 function. Args: ev (int): The win32 code for the mouse event. Use one of the MOUSEEVENTF_* constants for this argument. x (int): The x position of the mouse event. y (int): The y position of the mouse event. dwData (int): The argument for mouse_event()'s dwData parameter. So far this is only used by mouse scrolling. Returns: None """ assert x != None and y != None, 'x and y cannot be set to None' # TODO: ARG! For some reason, SendInput isn't working for mouse events. I'm switching to using the older mouse_event win32 function. #mouseStruct = MOUSEINPUT() #mouseStruct.dx = x #mouseStruct.dy = y #mouseStruct.mouseData = ev #mouseStruct.time = 0 #mouseStruct.dwExtraInfo = ctypes.pointer(ctypes.c_ulong(0)) # according to https://stackoverflow.com/questions/13564851/generate-keyboard-events I can just set this. I don't really care about this value. #inputStruct = INPUT() #inputStruct.mi = mouseStruct #inputStruct.type = INPUT_MOUSE #ctypes.windll.user32.SendInput(1, ctypes.pointer(inputStruct), ctypes.sizeof(inputStruct)) # TODO Note: We need to handle additional buttons, which I believe is documented here: # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-mouse_event width, height = _size() convertedX = 65536 * x // width + 1 convertedY = 65536 * y // height + 1 ctypes.windll.user32.mouse_event(ev, ctypes.c_long(convertedX), ctypes.c_long(convertedY), dwData, 0)
The helper function that actually makes the call to the mouse_event() win32 function. Args: ev (int): The win32 code for the mouse event. Use one of the MOUSEEVENTF_* constants for this argument. x (int): The x position of the mouse event. y (int): The y position of the mouse event. dwData (int): The argument for mouse_event()'s dwData parameter. So far this is only used by mouse scrolling. Returns: None
_sendMouseEvent
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _scroll(clicks, x=None, y=None): """Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None """ startx, starty = _position() width, height = _size() if x is None: x = startx else: if x < 0: x = 0 elif x >= width: x = width - 1 if y is None: y = starty else: if y < 0: y = 0 elif y >= height: y = height - 1 try: _sendMouseEvent(MOUSEEVENTF_WHEEL, x, y, dwData=clicks) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass
Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
_scroll
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _hscroll(clicks, x, y): """Send the mouse horizontal scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving right, a negative value is moving left. x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None """ return _scroll(clicks, x, y)
Send the mouse horizontal scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving right, a negative value is moving left. x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
_hscroll
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _vscroll(clicks, x, y): """A wrapper for _scroll(), which does vertical scrolling. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None """ return _scroll(clicks, x, y)
A wrapper for _scroll(), which does vertical scrolling. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
_vscroll
python
asweigart/pyautogui
pyautogui/_pyautogui_win.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_win.py
BSD-3-Clause
def _couldNotImportPyTweening(*unused_args, **unused_kwargs): """ This function raises ``PyAutoGUIException``. It's used for the PyTweening function names if the PyTweening module failed to be imported. """ raise PyAutoGUIException( "PyAutoGUI was unable to import pytweening. Please install this module to enable the function you tried to call." )
This function raises ``PyAutoGUIException``. It's used for the PyTweening function names if the PyTweening module failed to be imported.
_couldNotImportPyTweening
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _couldNotImportPyMsgBox(*unused_args, **unused_kwargs): """ This function raises ``PyAutoGUIException``. It's used for the PyMsgBox function names if the PyMsgbox module failed to be imported. """ raise PyAutoGUIException( "PyAutoGUI was unable to import pymsgbox. Please install this module to enable the function you tried to call." )
This function raises ``PyAutoGUIException``. It's used for the PyMsgBox function names if the PyMsgbox module failed to be imported.
_couldNotImportPyMsgBox
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def raisePyAutoGUIImageNotFoundException(wrappedFunction): """ A decorator that wraps PyScreeze locate*() functions so that the PyAutoGUI user sees them raise PyAutoGUI's ImageNotFoundException rather than PyScreeze's ImageNotFoundException. This is because PyScreeze should be invisible to PyAutoGUI users. """ @functools.wraps(wrappedFunction) def wrapper(*args, **kwargs): try: return wrappedFunction(*args, **kwargs) except pyscreeze.ImageNotFoundException: raise ImageNotFoundException # Raise PyAutoGUI's ImageNotFoundException. return wrapper
A decorator that wraps PyScreeze locate*() functions so that the PyAutoGUI user sees them raise PyAutoGUI's ImageNotFoundException rather than PyScreeze's ImageNotFoundException. This is because PyScreeze should be invisible to PyAutoGUI users.
raisePyAutoGUIImageNotFoundException
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _couldNotImportPyScreeze(*unused_args, **unsed_kwargs): """ This function raises ``PyAutoGUIException``. It's used for the PyScreeze function names if the PyScreeze module failed to be imported. """ raise PyAutoGUIException( "PyAutoGUI was unable to import pyscreeze. (This is likely because you're running a version of Python that Pillow (which pyscreeze depends on) doesn't support currently.) Please install this module to enable the function you tried to call." )
This function raises ``PyAutoGUIException``. It's used for the PyScreeze function names if the PyScreeze module failed to be imported.
_couldNotImportPyScreeze
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def mouseInfo(): """ Launches the MouseInfo app. This application provides mouse coordinate information which can be useful when planning GUI automation tasks. This function blocks until the application is closed. """ mouseinfo.MouseInfoWindow()
Launches the MouseInfo app. This application provides mouse coordinate information which can be useful when planning GUI automation tasks. This function blocks until the application is closed.
mouseInfo
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def mouseInfo(): """ This function raises PyAutoGUIException. It's used for the MouseInfo function names if the MouseInfo module failed to be imported. """ raise PyAutoGUIException( "PyAutoGUI was unable to import mouseinfo. Please install this module to enable the function you tried to call." )
This function raises PyAutoGUIException. It's used for the MouseInfo function names if the MouseInfo module failed to be imported.
mouseInfo
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def useImageNotFoundException(value=None): """ When called with no arguments, PyAutoGUI will raise ImageNotFoundException when the PyScreeze locate*() functions can't find the image it was told to locate. The default behavior is to return None. Call this function with no arguments (or with True as the argument) to have exceptions raised, which is a better practice. You can also disable raising exceptions by passing False for the argument. """ if value is None: value = True # TODO - this will cause a NameError if PyScreeze couldn't be imported: try: pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION = value except NameError: raise PyAutoGUIException("useImageNotFoundException() ws called but pyscreeze isn't installed.")
When called with no arguments, PyAutoGUI will raise ImageNotFoundException when the PyScreeze locate*() functions can't find the image it was told to locate. The default behavior is to return None. Call this function with no arguments (or with True as the argument) to have exceptions raised, which is a better practice. You can also disable raising exceptions by passing False for the argument.
useImageNotFoundException
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _couldNotImportPyGetWindow(*unused_args, **unused_kwargs): """ This function raises PyAutoGUIException. It's used for the PyGetWindow function names if the PyGetWindow module failed to be imported. """ raise PyAutoGUIException( "PyAutoGUI was unable to import pygetwindow. Please install this module to enable the function you tried to call." )
This function raises PyAutoGUIException. It's used for the PyGetWindow function names if the PyGetWindow module failed to be imported.
_couldNotImportPyGetWindow
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def isShiftCharacter(character): """ Returns True if the ``character`` is a keyboard key that would require the shift key to be held down, such as uppercase letters or the symbols on the keyboard's number row. """ # NOTE TODO - This will be different for non-qwerty keyboards. return character.isupper() or character in set('~!@#$%^&*()_+{}|:"<>?')
Returns True if the ``character`` is a keyboard key that would require the shift key to be held down, such as uppercase letters or the symbols on the keyboard's number row.
isShiftCharacter
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _genericPyAutoGUIChecks(wrappedFunction): """ A decorator that calls failSafeCheck() before the decorated function and _handlePause() after it. """ @functools.wraps(wrappedFunction) def wrapper(*args, **kwargs): failSafeCheck() returnVal = wrappedFunction(*args, **kwargs) _handlePause(kwargs.get("_pause", True)) return returnVal return wrapper
A decorator that calls failSafeCheck() before the decorated function and _handlePause() after it.
_genericPyAutoGUIChecks
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def getPointOnLine(x1, y1, x2, y2, n): """ Returns an (x, y) tuple of the point that has progressed a proportion ``n`` along the line defined by the two ``x1``, ``y1`` and ``x2``, ``y2`` coordinates. This function was copied from pytweening module, so that it can be called even if PyTweening is not installed. """ x = ((x2 - x1) * n) + x1 y = ((y2 - y1) * n) + y1 return (x, y)
Returns an (x, y) tuple of the point that has progressed a proportion ``n`` along the line defined by the two ``x1``, ``y1`` and ``x2``, ``y2`` coordinates. This function was copied from pytweening module, so that it can be called even if PyTweening is not installed.
getPointOnLine
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def linear(n): """ Returns ``n``, where ``n`` is the float argument between ``0.0`` and ``1.0``. This function is for the default linear tween for mouse moving functions. This function was copied from PyTweening module, so that it can be called even if PyTweening is not installed. """ # We use this function instead of pytweening.linear for the default tween function just in case pytweening couldn't be imported. if not 0.0 <= n <= 1.0: raise PyAutoGUIException("Argument must be between 0.0 and 1.0.") return n
Returns ``n``, where ``n`` is the float argument between ``0.0`` and ``1.0``. This function is for the default linear tween for mouse moving functions. This function was copied from PyTweening module, so that it can be called even if PyTweening is not installed.
linear
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _handlePause(_pause): """ A helper function for performing a pause at the end of a PyAutoGUI function based on some settings. If ``_pause`` is ``True``, then sleep for ``PAUSE`` seconds (the global pause setting). """ if _pause: assert isinstance(PAUSE, int) or isinstance(PAUSE, float) time.sleep(PAUSE)
A helper function for performing a pause at the end of a PyAutoGUI function based on some settings. If ``_pause`` is ``True``, then sleep for ``PAUSE`` seconds (the global pause setting).
_handlePause
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _normalizeXYArgs(firstArg, secondArg): """ Returns a ``Point`` object based on ``firstArg`` and ``secondArg``, which are the first two arguments passed to several PyAutoGUI functions. If ``firstArg`` and ``secondArg`` are both ``None``, returns the current mouse cursor position. ``firstArg`` and ``secondArg`` can be integers, a sequence of integers, or a string representing an image filename to find on the screen (and return the center coordinates of). """ if firstArg is None and secondArg is None: return position() elif firstArg is None and secondArg is not None: return Point(int(position()[0]), int(secondArg)) elif secondArg is None and firstArg is not None and not isinstance(firstArg, Sequence): return Point(int(firstArg), int(position()[1])) elif isinstance(firstArg, str): # If x is a string, we assume it's an image filename to locate on the screen: try: location = locateOnScreen(firstArg) # The following code only runs if pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION is not set to True, meaning that # locateOnScreen() returns None if the image can't be found. if location is not None: return center(location) else: return None except pyscreeze.ImageNotFoundException: raise ImageNotFoundException return center(locateOnScreen(firstArg)) elif isinstance(firstArg, Sequence): if len(firstArg) == 2: # firstArg is a two-integer tuple: (x, y) if secondArg is None: return Point(int(firstArg[0]), int(firstArg[1])) else: raise PyAutoGUIException( "When passing a sequence for firstArg, secondArg must not be passed (received {0}).".format( repr(secondArg) ) ) elif len(firstArg) == 4: # firstArg is a four-integer tuple, (left, top, width, height), we should return the center point if secondArg is None: return center(firstArg) else: raise PyAutoGUIException( "When passing a sequence for firstArg, secondArg must not be passed and default to None (received {0}).".format( repr(secondArg) ) ) else: raise PyAutoGUIException( "The supplied sequence must have exactly 2 or exactly 4 elements ({0} were received).".format( len(firstArg) ) ) else: return Point(int(firstArg), int(secondArg)) # firstArg and secondArg are just x and y number values
Returns a ``Point`` object based on ``firstArg`` and ``secondArg``, which are the first two arguments passed to several PyAutoGUI functions. If ``firstArg`` and ``secondArg`` are both ``None``, returns the current mouse cursor position. ``firstArg`` and ``secondArg`` can be integers, a sequence of integers, or a string representing an image filename to find on the screen (and return the center coordinates of).
_normalizeXYArgs
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _logScreenshot(logScreenshot, funcName, funcArgs, folder="."): """ A helper function that creates a screenshot to act as a logging mechanism. When a PyAutoGUI function is called, this function is also called to capture the state of the screen when that function was called. If ``logScreenshot`` is ``False`` (or None and the ``LOG_SCREENSHOTS`` constant is ``False``), no screenshot is taken. The ``funcName`` argument is a string of the calling function's name. It's used in the screenshot's filename. The ``funcArgs`` argument is a string describing the arguments passed to the calling function. It's limited to twelve characters to keep it short. The ``folder`` argument is the folder to place the screenshot file in, and defaults to the current working directory. """ if not logScreenshot: return # Don't take a screenshot. if logScreenshot is None and LOG_SCREENSHOTS is False: return # Don't take a screenshot. # Ensure that the "specifics" string isn't too long for the filename: if len(funcArgs) > 12: funcArgs = funcArgs[:12] + "..." now = datetime.datetime.now() filename = "%s-%s-%s_%s-%s-%s-%s_%s_%s.png" % ( now.year, str(now.month).rjust(2, "0"), str(now.day).rjust(2, "0"), now.hour, now.minute, now.second, str(now.microsecond)[:3], funcName, funcArgs, ) filepath = os.path.join(folder, filename) # Delete the oldest screenshot if we've reached the maximum: if (LOG_SCREENSHOTS_LIMIT is not None) and (len(G_LOG_SCREENSHOTS_FILENAMES) >= LOG_SCREENSHOTS_LIMIT): os.unlink(os.path.join(folder, G_LOG_SCREENSHOTS_FILENAMES[0])) del G_LOG_SCREENSHOTS_FILENAMES[0] screenshot(filepath) G_LOG_SCREENSHOTS_FILENAMES.append(filename)
A helper function that creates a screenshot to act as a logging mechanism. When a PyAutoGUI function is called, this function is also called to capture the state of the screen when that function was called. If ``logScreenshot`` is ``False`` (or None and the ``LOG_SCREENSHOTS`` constant is ``False``), no screenshot is taken. The ``funcName`` argument is a string of the calling function's name. It's used in the screenshot's filename. The ``funcArgs`` argument is a string describing the arguments passed to the calling function. It's limited to twelve characters to keep it short. The ``folder`` argument is the folder to place the screenshot file in, and defaults to the current working directory.
_logScreenshot
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def position(x=None, y=None): """ Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Args: x (int, None, optional) - If not None, this argument overrides the x in the return value. y (int, None, optional) - If not None, this argument overrides the y in the return value. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor. NOTE: The position() function doesn't check for failsafe. """ posx, posy = platformModule._position() posx = int(posx) posy = int(posy) if x is not None: # If set, the x parameter overrides the return value. posx = int(x) if y is not None: # If set, the y parameter overrides the return value. posy = int(y) return Point(posx, posy)
Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Args: x (int, None, optional) - If not None, this argument overrides the x in the return value. y (int, None, optional) - If not None, this argument overrides the y in the return value. Returns: (x, y) tuple of the current xy coordinates of the mouse cursor. NOTE: The position() function doesn't check for failsafe.
position
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def onScreen(x, y=None): """Returns whether the given xy coordinates are on the primary screen or not. Note that this function doesn't work for secondary screens. Args: Either the arguments are two separate values, first arg for x and second for y, or there is a single argument of a sequence with two values, the first x and the second y. Example: onScreen(x, y) or onScreen([x, y]) Returns: bool: True if the xy coordinates are on the screen at its current resolution, otherwise False. """ x, y = _normalizeXYArgs(x, y) x = int(x) y = int(y) width, height = platformModule._size() return 0 <= x < width and 0 <= y < height
Returns whether the given xy coordinates are on the primary screen or not. Note that this function doesn't work for secondary screens. Args: Either the arguments are two separate values, first arg for x and second for y, or there is a single argument of a sequence with two values, the first x and the second y. Example: onScreen(x, y) or onScreen([x, y]) Returns: bool: True if the xy coordinates are on the screen at its current resolution, otherwise False.
onScreen
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _normalizeButton(button): """ The left, middle, and right mouse buttons are button numbers 1, 2, and 3 respectively. This is the numbering that Xlib on Linux uses (while Windows and macOS don't care about numbers; they just use "left" and "right"). This function takes one of ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, or ``7`` for the button argument and returns either ``LEFT``, ``MIDDLE``, ``RIGHT``, ``4``, ``5``, ``6``, or ``7``. The ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, and ``3`` values are never returned. The ``'left'`` and ``'right'`` mouse buttons will always refer to the physical left and right buttons on the mouse. The same applies for buttons 1 and 3. However, if ``button`` is ``'primary'`` or ``'secondary'``, then we must check if the mouse buttons have been "swapped" (for left-handed users) by the operating system's mouse settings. If the buttons are swapped, the primary button is the right mouse button and the secondary button is the left mouse button. If not swapped, the primary and secondary buttons are the left and right buttons, respectively. NOTE: Swap detection has not been implemented yet. """ # TODO - The swap detection hasn't been done yet. For Windows, see https://stackoverflow.com/questions/45627956/check-if-mouse-buttons-are-swapped-or-not-in-c # TODO - We should check the OS settings to see if it's a left-hand setup, where button 1 would be "right". # Check that `button` has a valid value: button = button.lower() if platform.system() == "Linux": # Check for valid button arg on Linux: if button not in (LEFT, MIDDLE, RIGHT, PRIMARY, SECONDARY, 1, 2, 3, 4, 5, 6, 7): raise PyAutoGUIException( "button argument must be one of ('left', 'middle', 'right', 'primary', 'secondary', 1, 2, 3, 4, 5, 6, 7)" ) else: # Check for valid button arg on Windows and macOS: if button not in (LEFT, MIDDLE, RIGHT, PRIMARY, SECONDARY, 1, 2, 3): raise PyAutoGUIException( "button argument must be one of ('left', 'middle', 'right', 'primary', 'secondary', 1, 2, 3)" ) # TODO - Check if the primary/secondary mouse buttons have been swapped: if button in (PRIMARY, SECONDARY): swapped = platformModule._mouse_is_swapped() if swapped: if button == PRIMARY: return RIGHT elif button == SECONDARY: return LEFT else: if button == PRIMARY: return LEFT elif button == SECONDARY: return RIGHT # Return a mouse button integer value, not a string like 'left': return {LEFT: LEFT, MIDDLE: MIDDLE, RIGHT: RIGHT, 1: LEFT, 2: MIDDLE, 3: RIGHT, 4: 4, 5: 5, 6: 6, 7: 7}[button]
The left, middle, and right mouse buttons are button numbers 1, 2, and 3 respectively. This is the numbering that Xlib on Linux uses (while Windows and macOS don't care about numbers; they just use "left" and "right"). This function takes one of ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, or ``7`` for the button argument and returns either ``LEFT``, ``MIDDLE``, ``RIGHT``, ``4``, ``5``, ``6``, or ``7``. The ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, and ``3`` values are never returned. The ``'left'`` and ``'right'`` mouse buttons will always refer to the physical left and right buttons on the mouse. The same applies for buttons 1 and 3. However, if ``button`` is ``'primary'`` or ``'secondary'``, then we must check if the mouse buttons have been "swapped" (for left-handed users) by the operating system's mouse settings. If the buttons are swapped, the primary button is the right mouse button and the secondary button is the left mouse button. If not swapped, the primary and secondary buttons are the left and right buttons, respectively. NOTE: Swap detection has not been implemented yet.
_normalizeButton
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def mouseDown(x=None, y=None, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs pressing a mouse button down (but not up). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the mouse down happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the mouse down happens. None by default. button (str, int, optional): The mouse button pressed down. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3 """ button = _normalizeButton(button) x, y = _normalizeXYArgs(x, y) _mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None) _logScreenshot(logScreenshot, "mouseDown", "%s,%s" % (x, y), folder=".") platformModule._mouseDown(x, y, button)
Performs pressing a mouse button down (but not up). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the mouse down happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the mouse down happens. None by default. button (str, int, optional): The mouse button pressed down. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3
mouseDown
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def mouseUp(x=None, y=None, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs releasing a mouse button up (but not down beforehand). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the mouse up happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the mouse up happens. None by default. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3 """ button = _normalizeButton(button) x, y = _normalizeXYArgs(x, y) _mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None) _logScreenshot(logScreenshot, "mouseUp", "%s,%s" % (x, y), folder=".") platformModule._mouseUp(x, y, button)
Performs releasing a mouse button up (but not down beforehand). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the mouse up happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the mouse up happens. None by default. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3
mouseUp
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def click( x=None, y=None, clicks=1, interval=0.0, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True ): """ Performs pressing a mouse button down and then immediately releasing it. Returns ``None``. When no arguments are passed, the primary mouse button is clicked at the mouse cursor's current location. If integers for ``x`` and ``y`` are passed, the click will happen at that XY coordinate. If ``x`` is a string, the string is an image filename that PyAutoGUI will attempt to locate on the screen and click the center of. If ``x`` is a sequence of two coordinates, those coordinates will be used for the XY coordinate to click on. The ``clicks`` argument is an int of how many clicks to make, and defaults to ``1``. The ``interval`` argument is an int or float of how many seconds to wait in between each click, if ``clicks`` is greater than ``1``. It defaults to ``0.0`` for no pause in between clicks. The ``button`` argument is one of the constants ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, or ``SECONDARY``. It defaults to ``PRIMARY`` (which is the left mouse button, unless the operating system has been set for left-handed users.) If ``x`` and ``y`` are specified, and the click is not happening at the mouse cursor's current location, then the ``duration`` argument is an int or float of how many seconds it should take to move the mouse to the XY coordinates. It defaults to ``0`` for an instant move. If ``x`` and ``y`` are specified and ``duration`` is not ``0``, the ``tween`` argument is a tweening function that specifies the movement pattern of the mouse cursor as it moves to the XY coordinates. The default is a simple linear tween. See the PyTweening module documentation for more details. The ``pause`` parameter is deprecated. Call the ``pyautogui.sleep()`` function to implement a pause. Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3 """ # TODO: I'm leaving buttons 4, 5, 6, and 7 undocumented for now. I need to understand how they work. button = _normalizeButton(button) x, y = _normalizeXYArgs(x, y) # Move the mouse cursor to the x, y coordinate: _mouseMoveDrag("move", x, y, 0, 0, duration, tween) _logScreenshot(logScreenshot, "click", "%s,%s,%s,%s" % (button, clicks, x, y), folder=".") if sys.platform == 'darwin': for i in range(clicks): failSafeCheck() if button in (LEFT, MIDDLE, RIGHT): platformModule._multiClick(x, y, button, 1, interval) else: for i in range(clicks): failSafeCheck() if button in (LEFT, MIDDLE, RIGHT): platformModule._click(x, y, button) time.sleep(interval)
Performs pressing a mouse button down and then immediately releasing it. Returns ``None``. When no arguments are passed, the primary mouse button is clicked at the mouse cursor's current location. If integers for ``x`` and ``y`` are passed, the click will happen at that XY coordinate. If ``x`` is a string, the string is an image filename that PyAutoGUI will attempt to locate on the screen and click the center of. If ``x`` is a sequence of two coordinates, those coordinates will be used for the XY coordinate to click on. The ``clicks`` argument is an int of how many clicks to make, and defaults to ``1``. The ``interval`` argument is an int or float of how many seconds to wait in between each click, if ``clicks`` is greater than ``1``. It defaults to ``0.0`` for no pause in between clicks. The ``button`` argument is one of the constants ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, or ``SECONDARY``. It defaults to ``PRIMARY`` (which is the left mouse button, unless the operating system has been set for left-handed users.) If ``x`` and ``y`` are specified, and the click is not happening at the mouse cursor's current location, then the ``duration`` argument is an int or float of how many seconds it should take to move the mouse to the XY coordinates. It defaults to ``0`` for an instant move. If ``x`` and ``y`` are specified and ``duration`` is not ``0``, the ``tween`` argument is a tweening function that specifies the movement pattern of the mouse cursor as it moves to the XY coordinates. The default is a simple linear tween. See the PyTweening module documentation for more details. The ``pause`` parameter is deprecated. Call the ``pyautogui.sleep()`` function to implement a pause. Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3
click
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def leftClick(x=None, y=None, interval=0.0, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs a left mouse button click. This is a wrapper function for click('left', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. Returns: None """ # TODO - Do we need the decorator for this function? Should click() handle this? (Also applies to other alias functions.) click(x, y, 1, interval, LEFT, duration, tween, logScreenshot, _pause=_pause)
Performs a left mouse button click. This is a wrapper function for click('left', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. Returns: None
leftClick
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def rightClick(x=None, y=None, interval=0.0, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs a right mouse button click. This is a wrapper function for click('right', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. Returns: None """ click(x, y, 1, interval, RIGHT, duration, tween, logScreenshot, _pause=_pause)
Performs a right mouse button click. This is a wrapper function for click('right', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. Returns: None
rightClick
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def middleClick(x=None, y=None, interval=0.0, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs a middle mouse button click. This is a wrapper function for click('middle', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None """ click(x, y, 1, interval, MIDDLE, duration, tween, logScreenshot, _pause=_pause)
Performs a middle mouse button click. This is a wrapper function for click('middle', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None
middleClick
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def doubleClick(x=None, y=None, interval=0.0, button=LEFT, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs a double click. This is a wrapper function for click('left', x, y, 2, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3, 4, 5, 6, or 7 """ # Multiple clicks work different in OSX if sys.platform == "darwin": x, y = _normalizeXYArgs(x, y) _mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None) x, y = platformModule._position() platformModule._multiClick(x, y, button, 2) _logScreenshot(logScreenshot, 'click', '%s,%s,%s,2' % (x, y, button), folder='.') else: # Click for Windows or Linux: click(x, y, 2, interval, button, duration, tween, logScreenshot, _pause=False)
Performs a double click. This is a wrapper function for click('left', x, y, 2, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3, 4, 5, 6, or 7
doubleClick
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def tripleClick(x=None, y=None, interval=0.0, button=LEFT, duration=0.0, tween=linear, logScreenshot=None, _pause=True): """Performs a triple click. This is a wrapper function for click('left', x, y, 3, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3, 4, 5, 6, or 7 """ # Multiple clicks work different in OSX if sys.platform == "darwin": x, y = _normalizeXYArgs(x, y) _mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None) x, y = platformModule._position() _logScreenshot(logScreenshot, "click", "%s,%s,%s,3" % (x, y, button), folder=".") platformModule._multiClick(x, y, button, 3) else: # Click for Windows or Linux: click(x, y, 3, interval, button, duration, tween, logScreenshot, _pause=False)
Performs a triple click. This is a wrapper function for click('left', x, y, 3, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. interval (float, optional): The number of seconds in between each click, if the number of clicks is greater than 1. 0.0 by default, for no pause in between clicks. button (str, int, optional): The mouse button released. TODO Returns: None Raises: PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3, 4, 5, 6, or 7
tripleClick
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def scroll(clicks, x=None, y=None, logScreenshot=None, _pause=True): """Performs a scroll of the mouse scroll wheel. Whether this is a vertical or horizontal scroll depends on the underlying operating system. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None """ if type(x) in (tuple, list): x, y = x[0], x[1] x, y = position(x, y) _logScreenshot(logScreenshot, "scroll", "%s,%s,%s" % (clicks, x, y), folder=".") platformModule._scroll(clicks, x, y)
Performs a scroll of the mouse scroll wheel. Whether this is a vertical or horizontal scroll depends on the underlying operating system. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None
scroll
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def hscroll(clicks, x=None, y=None, logScreenshot=None, _pause=True): """Performs an explicitly horizontal scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None """ if type(x) in (tuple, list): x, y = x[0], x[1] x, y = position(x, y) _logScreenshot(logScreenshot, "hscroll", "%s,%s,%s" % (clicks, x, y), folder=".") platformModule._hscroll(clicks, x, y)
Performs an explicitly horizontal scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None
hscroll
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def vscroll(clicks, x=None, y=None, logScreenshot=None, _pause=True): """Performs an explicitly vertical scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None """ if type(x) in (tuple, list): x, y = x[0], x[1] x, y = position(x, y) _logScreenshot(logScreenshot, "vscroll", "%s,%s,%s" % (clicks, x, y), folder=".") platformModule._vscroll(clicks, x, y)
Performs an explicitly vertical scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: clicks (int, float): The amount of scrolling to perform. x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. y (int, float, None, optional): The y position on the screen where the click happens. None by default. Returns: None
vscroll
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def moveTo(x=None, y=None, duration=0.0, tween=linear, logScreenshot=False, _pause=True): """Moves the mouse cursor to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. Returns: None """ x, y = _normalizeXYArgs(x, y) _logScreenshot(logScreenshot, "moveTo", "%s,%s" % (x, y), folder=".") _mouseMoveDrag("move", x, y, 0, 0, duration, tween)
Moves the mouse cursor to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): The x position on the screen where the click happens. None by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): The y position on the screen where the click happens. None by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. Returns: None
moveTo
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def moveRel(xOffset=None, yOffset=None, duration=0.0, tween=linear, logScreenshot=False, _pause=True): """Moves the mouse cursor to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for x and y. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. Returns: None """ xOffset, yOffset = _normalizeXYArgs(xOffset, yOffset) _logScreenshot(logScreenshot, "moveRel", "%s,%s" % (xOffset, yOffset), folder=".") _mouseMoveDrag("move", None, None, xOffset, yOffset, duration, tween)
Moves the mouse cursor to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for x and y. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. Returns: None
moveRel
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def dragTo( x=None, y=None, duration=0.0, tween=linear, button=PRIMARY, logScreenshot=None, _pause=True, mouseDownUp=True ): """Performs a mouse drag (mouse movement while a button is held down) to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO mouseDownUp (True, False): When true, the mouseUp/Down actions are not performed. Which allows dragging over multiple (small) actions. 'True' by default. Returns: None """ x, y = _normalizeXYArgs(x, y) _logScreenshot(logScreenshot, "dragTo", "%s,%s" % (x, y), folder=".") if mouseDownUp: mouseDown(button=button, logScreenshot=False, _pause=False) _mouseMoveDrag("drag", x, y, 0, 0, duration, tween, button) if mouseDownUp: mouseUp(button=button, logScreenshot=False, _pause=False)
Performs a mouse drag (mouse movement while a button is held down) to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for x and y. If x is a str, it's considered a filename of an image to find on the screen with locateOnScreen() and click the center of. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO mouseDownUp (True, False): When true, the mouseUp/Down actions are not performed. Which allows dragging over multiple (small) actions. 'True' by default. Returns: None
dragTo
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def dragRel( xOffset=0, yOffset=0, duration=0.0, tween=linear, button=PRIMARY, logScreenshot=None, _pause=True, mouseDownUp=True ): """Performs a mouse drag (mouse movement while a button is held down) to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for xOffset and yOffset. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO mouseDownUp (True, False): When true, the mouseUp/Down actions are not performed. Which allows dragging over multiple (small) actions. 'True' by default. Returns: None """ if xOffset is None: xOffset = 0 if yOffset is None: yOffset = 0 if type(xOffset) in (tuple, list): xOffset, yOffset = xOffset[0], xOffset[1] if xOffset == 0 and yOffset == 0: return # no-op case mousex, mousey = platformModule._position() _logScreenshot(logScreenshot, "dragRel", "%s,%s" % (xOffset, yOffset), folder=".") if mouseDownUp: mouseDown(button=button, logScreenshot=False, _pause=False) _mouseMoveDrag("drag", mousex, mousey, xOffset, yOffset, duration, tween, button) if mouseDownUp: mouseUp(button=button, logScreenshot=False, _pause=False)
Performs a mouse drag (mouse movement while a button is held down) to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, float, None, tuple, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. If tuple, this is used for xOffset and yOffset. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO mouseDownUp (True, False): When true, the mouseUp/Down actions are not performed. Which allows dragging over multiple (small) actions. 'True' by default. Returns: None
dragRel
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _mouseMoveDrag(moveOrDrag, x, y, xOffset, yOffset, duration, tween=linear, button=None): """Handles the actual move or drag event, since different platforms implement them differently. On Windows & Linux, a drag is a normal mouse move while a mouse button is held down. On OS X, a distinct "drag" event must be used instead. The code for moving and dragging the mouse is similar, so this function handles both. Users should call the moveTo() or dragTo() functions instead of calling _mouseMoveDrag(). Args: moveOrDrag (str): Either 'move' or 'drag', for the type of action this is. x (int, float, None, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. xOffset (int, float, None, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. yOffset (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO Returns: None """ # The move and drag code is similar, but OS X requires a special drag event instead of just a move event when dragging. # See https://stackoverflow.com/a/2696107/1893164 assert moveOrDrag in ("move", "drag"), "moveOrDrag must be in ('move', 'drag'), not %s" % (moveOrDrag) if sys.platform != "darwin": moveOrDrag = "move" # Only OS X needs the drag event specifically. xOffset = int(xOffset) if xOffset is not None else 0 yOffset = int(yOffset) if yOffset is not None else 0 if x is None and y is None and xOffset == 0 and yOffset == 0: return # Special case for no mouse movement at all. startx, starty = position() x = int(x) if x is not None else startx y = int(y) if y is not None else starty # x, y, xOffset, yOffset are now int. x += xOffset y += yOffset width, height = size() # Make sure x and y are within the screen bounds. # x = max(0, min(x, width - 1)) # y = max(0, min(y, height - 1)) # If the duration is small enough, just move the cursor there instantly. steps = [(x, y)] if duration > MINIMUM_DURATION: # Non-instant moving/dragging involves tweening: num_steps = max(width, height) sleep_amount = duration / num_steps if sleep_amount < MINIMUM_SLEEP: num_steps = int(duration / MINIMUM_SLEEP) sleep_amount = duration / num_steps steps = [getPointOnLine(startx, starty, x, y, tween(n / num_steps)) for n in range(num_steps)] # Making sure the last position is the actual destination. steps.append((x, y)) for tweenX, tweenY in steps: if len(steps) > 1: # A single step does not require tweening. time.sleep(sleep_amount) tweenX = int(round(tweenX)) tweenY = int(round(tweenY)) # Do a fail-safe check to see if the user moved the mouse to a fail-safe position, but not if the mouse cursor # moved there as a result of this function. (Just because tweenX and tweenY aren't in a fail-safe position # doesn't mean the user couldn't have moved the mouse cursor to a fail-safe position.) if (tweenX, tweenY) not in FAILSAFE_POINTS: failSafeCheck() if moveOrDrag == "move": platformModule._moveTo(tweenX, tweenY) elif moveOrDrag == "drag": platformModule._dragTo(tweenX, tweenY, button) else: raise NotImplementedError("Unknown value of moveOrDrag: {0}".format(moveOrDrag)) if (tweenX, tweenY) not in FAILSAFE_POINTS: failSafeCheck()
Handles the actual move or drag event, since different platforms implement them differently. On Windows & Linux, a drag is a normal mouse move while a mouse button is held down. On OS X, a distinct "drag" event must be used instead. The code for moving and dragging the mouse is similar, so this function handles both. Users should call the moveTo() or dragTo() functions instead of calling _mouseMoveDrag(). Args: moveOrDrag (str): Either 'move' or 'drag', for the type of action this is. x (int, float, None, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. y (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. xOffset (int, float, None, optional): How far left (for negative values) or right (for positive values) to move the cursor. 0 by default. yOffset (int, float, None, optional): How far up (for negative values) or down (for positive values) to move the cursor. 0 by default. duration (float, optional): The amount of time it takes to move the mouse cursor to the new xy coordinates. If 0, then the mouse cursor is moved instantaneously. 0.0 by default. tween (func, optional): The tweening function used if the duration is not 0. A linear tween is used by default. button (str, int, optional): The mouse button released. TODO Returns: None
_mouseMoveDrag
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def isValidKey(key): """Returns a Boolean value if the given key is a valid value to pass to PyAutoGUI's keyboard-related functions for the current platform. This function is here because passing an invalid value to the PyAutoGUI keyboard functions currently is a no-op that does not raise an exception. Some keys are only valid on some platforms. For example, while 'esc' is valid for the Escape key on all platforms, 'browserback' is only used on Windows operating systems. Args: key (str): The key value. Returns: bool: True if key is a valid value, False if not. """ return platformModule.keyboardMapping.get(key, None) is not None
Returns a Boolean value if the given key is a valid value to pass to PyAutoGUI's keyboard-related functions for the current platform. This function is here because passing an invalid value to the PyAutoGUI keyboard functions currently is a no-op that does not raise an exception. Some keys are only valid on some platforms. For example, while 'esc' is valid for the Escape key on all platforms, 'browserback' is only used on Windows operating systems. Args: key (str): The key value. Returns: bool: True if key is a valid value, False if not.
isValidKey
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def keyDown(key, logScreenshot=None, _pause=True): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are listed in KEYBOARD_KEYS. Returns: None """ if len(key) > 1: key = key.lower() _logScreenshot(logScreenshot, "keyDown", key, folder=".") platformModule._keyDown(key)
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are listed in KEYBOARD_KEYS. Returns: None
keyDown
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def keyUp(key, logScreenshot=None, _pause=True): """Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None """ if len(key) > 1: key = key.lower() _logScreenshot(logScreenshot, "keyUp", key, folder=".") platformModule._keyUp(key)
Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None
keyUp
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def press(keys, presses=1, interval=0.0, logScreenshot=None, _pause=True): """Performs a keyboard key press down, followed by a release. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. presses (integer, optional): The number of press repetitions. 1 by default, for just one press. interval (float, optional): How many seconds between each press. 0.0 by default, for no pause between presses. pause (float, optional): How many seconds in the end of function process. None by default, for no pause in the end of function process. Returns: None """ if type(keys) == str: if len(keys) > 1: keys = keys.lower() keys = [keys] # If keys is 'enter', convert it to ['enter']. else: lowerKeys = [] for s in keys: if len(s) > 1: lowerKeys.append(s.lower()) else: lowerKeys.append(s) keys = lowerKeys interval = float(interval) _logScreenshot(logScreenshot, "press", ",".join(keys), folder=".") for i in range(presses): for k in keys: failSafeCheck() platformModule._keyDown(k) platformModule._keyUp(k) time.sleep(interval)
Performs a keyboard key press down, followed by a release. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. presses (integer, optional): The number of press repetitions. 1 by default, for just one press. interval (float, optional): How many seconds between each press. 0.0 by default, for no pause between presses. pause (float, optional): How many seconds in the end of function process. None by default, for no pause in the end of function process. Returns: None
press
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def hold(keys, logScreenshot=None, _pause=True): """Context manager that performs a keyboard key press down upon entry, followed by a release upon exit. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. pause (float, optional): How many seconds in the end of function process. None by default, for no pause in the end of function process. Returns: None """ if type(keys) == str: if len(keys) > 1: keys = keys.lower() keys = [keys] # If keys is 'enter', convert it to ['enter']. else: lowerKeys = [] for s in keys: if len(s) > 1: lowerKeys.append(s.lower()) else: lowerKeys.append(s) keys = lowerKeys _logScreenshot(logScreenshot, "press", ",".join(keys), folder=".") for k in keys: failSafeCheck() platformModule._keyDown(k) try: yield finally: for k in keys: failSafeCheck() platformModule._keyUp(k)
Context manager that performs a keyboard key press down upon entry, followed by a release upon exit. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. pause (float, optional): How many seconds in the end of function process. None by default, for no pause in the end of function process. Returns: None
hold
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def typewrite(message, interval=0.0, logScreenshot=None, _pause=True): """Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of keyboard presses and does not hold down keys, it cannot be used to perform keyboard shortcuts. Use the hotkey() function for that. Args: message (str, list): If a string, then the characters to be pressed. If a list, then the key names of the keys to press in order. The valid names are listed in KEYBOARD_KEYS. interval (float, optional): The number of seconds in between each press. 0.0 by default, for no pause in between presses. Returns: None """ interval = float(interval) # TODO - this should be taken out. _logScreenshot(logScreenshot, "write", message, folder=".") for c in message: if len(c) > 1: c = c.lower() press(c, _pause=False) time.sleep(interval) failSafeCheck()
Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of keyboard presses and does not hold down keys, it cannot be used to perform keyboard shortcuts. Use the hotkey() function for that. Args: message (str, list): If a string, then the characters to be pressed. If a list, then the key names of the keys to press in order. The valid names are listed in KEYBOARD_KEYS. interval (float, optional): The number of seconds in between each press. 0.0 by default, for no pause in between presses. Returns: None
typewrite
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def hotkey(*args, **kwargs): """Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: key(s) (str): The series of keys to press, in order. This can also be a list of key strings to press. interval (float, optional): The number of seconds in between each press. 0.0 by default, for no pause in between presses. Returns: None """ interval = float(kwargs.get("interval", 0.0)) # TODO - this should be taken out. if len(args) and isinstance(args[0], Sequence) and not isinstance(args[0], str): # Let the user pass a list of strings args = tuple(args[0]) _logScreenshot(kwargs.get("logScreenshot"), "hotkey", ",".join(args), folder=".") for c in args: if len(c) > 1: c = c.lower() platformModule._keyDown(c) time.sleep(interval) for c in reversed(args): if len(c) > 1: c = c.lower() platformModule._keyUp(c) time.sleep(interval)
Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: key(s) (str): The series of keys to press, in order. This can also be a list of key strings to press. interval (float, optional): The number of seconds in between each press. 0.0 by default, for no pause in between presses. Returns: None
hotkey
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def displayMousePosition(xOffset=0, yOffset=0): """This function is meant to be run from the command line. It will automatically display the location and RGB of the mouse cursor.""" try: runningIDLE = sys.stdin.__module__.startswith("idlelib") except AttributeError: runningIDLE = False print("Press Ctrl-C to quit.") if xOffset != 0 or yOffset != 0: print("xOffset: %s yOffset: %s" % (xOffset, yOffset)) try: while True: # Get and print the mouse coordinates. x, y = position() positionStr = "X: " + str(x - xOffset).rjust(4) + " Y: " + str(y - yOffset).rjust(4) if not onScreen(x - xOffset, y - yOffset) or sys.platform == "darwin": # Pixel color can only be found for the primary monitor, and also not on mac due to the screenshot having the mouse cursor in the way. pixelColor = ("NaN", "NaN", "NaN") else: pixelColor = pyscreeze.screenshot().getpixel( (x, y) ) # NOTE: On Windows & Linux, getpixel() returns a 3-integer tuple, but on macOS it returns a 4-integer tuple. positionStr += " RGB: (" + str(pixelColor[0]).rjust(3) positionStr += ", " + str(pixelColor[1]).rjust(3) positionStr += ", " + str(pixelColor[2]).rjust(3) + ")" sys.stdout.write(positionStr) if not runningIDLE: # If this is a terminal, than we can erase the text by printing \b backspaces. sys.stdout.write("\b" * len(positionStr)) else: # If this isn't a terminal (i.e. IDLE) then we can only append more text. Print a newline instead and pause a second (so we don't send too much output). sys.stdout.write("\n") time.sleep(1) sys.stdout.flush() except KeyboardInterrupt: sys.stdout.write("\n") sys.stdout.flush()
This function is meant to be run from the command line. It will automatically display the location and RGB of the mouse cursor.
displayMousePosition
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _getNumberToken(commandStr): """Gets the number token at the start of commandStr. Given '5hello' returns '5' Given ' 5hello' returns ' 5' Given '-42hello' returns '-42' Given '+42hello' returns '+42' Given '3.14hello' returns '3.14' Raises an exception if it can't tokenize a number. """ pattern = re.compile(r"^(\s*(\+|\-)?\d+(\.\d+)?)") mo = pattern.search(commandStr) if mo is None: raise PyAutoGUIException("Invalid command at index 0: a number was expected") return mo.group(1)
Gets the number token at the start of commandStr. Given '5hello' returns '5' Given ' 5hello' returns ' 5' Given '-42hello' returns '-42' Given '+42hello' returns '+42' Given '3.14hello' returns '3.14' Raises an exception if it can't tokenize a number.
_getNumberToken
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _getQuotedStringToken(commandStr): """Gets the quoted string token at the start of commandStr. The quoted string must use single quotes. Given "'hello'world" returns "'hello'" Given " 'hello'world" returns " 'hello'" Raises an exception if it can't tokenize a quoted string. """ pattern = re.compile(r"^((\s*)('(.*?)'))") mo = pattern.search(commandStr) if mo is None: raise PyAutoGUIException("Invalid command at index 0: a quoted string was expected") return mo.group(1)
Gets the quoted string token at the start of commandStr. The quoted string must use single quotes. Given "'hello'world" returns "'hello'" Given " 'hello'world" returns " 'hello'" Raises an exception if it can't tokenize a quoted string.
_getQuotedStringToken
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _getParensCommandStrToken(commandStr): """Gets the command string token at the start of commandStr. It will also be enclosed with parentheses. Given "(ccc)world" returns "(ccc)" Given " (ccc)world" returns " (ccc)" Given "(ccf10(r))world" returns "(ccf10(r))" Raises an exception if it can't tokenize a quoted string. """ # Check to make sure at least one open parenthesis exists: pattern = re.compile(r"^\s*\(") mo = pattern.search(commandStr) if mo is None: raise PyAutoGUIException("Invalid command at index 0: No open parenthesis found.") # Check to make sure the parentheses are balanced: i = 0 openParensCount = 0 while i < len(commandStr): if commandStr[i] == "(": openParensCount += 1 elif commandStr[i] == ")": openParensCount -= 1 if openParensCount == 0: i += 1 # Remember to increment i past the ) before breaking. break elif openParensCount == -1: raise PyAutoGUIException("Invalid command at index 0: No open parenthesis for this close parenthesis.") i += 1 if openParensCount > 0: raise PyAutoGUIException("Invalid command at index 0: Not enough close parentheses.") return commandStr[0:i]
Gets the command string token at the start of commandStr. It will also be enclosed with parentheses. Given "(ccc)world" returns "(ccc)" Given " (ccc)world" returns " (ccc)" Given "(ccf10(r))world" returns "(ccf10(r))" Raises an exception if it can't tokenize a quoted string.
_getParensCommandStrToken
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _getCommaToken(commandStr): """Gets the comma token at the start of commandStr. Given ',' returns ',' Given ' ,', returns ' ,' Raises an exception if a comma isn't found. """ pattern = re.compile(r"^((\s*),)") mo = pattern.search(commandStr) if mo is None: raise PyAutoGUIException("Invalid command at index 0: a comma was expected") return mo.group(1)
Gets the comma token at the start of commandStr. Given ',' returns ',' Given ' ,', returns ' ,' Raises an exception if a comma isn't found.
_getCommaToken
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def _tokenizeCommandStr(commandStr): """Tokenizes commandStr into a list of commands and their arguments for the run() function. Returns the list.""" commandPattern = re.compile(r"^(su|sd|ss|c|l|m|r|g|d|k|w|h|f|s|a|p)") # Tokenize the command string. commandList = [] i = 0 # Points to the current index in commandStr that is being tokenized. while i < len(commandStr): if commandStr[i] in (" ", "\t", "\n", "\r"): # Skip over whitespace: i += 1 continue mo = commandPattern.match(commandStr[i:]) if mo is None: raise PyAutoGUIException("Invalid command at index %s: %s is not a valid command" % (i, commandStr[i])) individualCommand = mo.group(1) commandList.append(individualCommand) i += len(individualCommand) # Handle the no argument commands (c, l, m, r, su, sd, ss): if individualCommand in ("c", "l", "m", "r", "su", "sd", "ss"): pass # This just exists so these commands are covered by one of these cases. # Handle the arguments of the mouse (g)o and mouse (d)rag commands: elif individualCommand in ("g", "d"): try: x = _getNumberToken(commandStr[i:]) i += len(x) # Increment past the x number. comma = _getCommaToken(commandStr[i:]) i += len(comma) # Increment past the comma (and any whitespace). y = _getNumberToken(commandStr[i:]) i += len(y) # Increment past the y number. except PyAutoGUIException as excObj: # Exception message starts with something like "Invalid command at index 0:" # Change the index number and reraise it. indexPart, colon, message = str(excObj).partition(":") indexNum = indexPart[len("Invalid command at index ") :] newIndexNum = int(indexNum) + i raise PyAutoGUIException("Invalid command at index %s:%s" % (newIndexNum, message)) # Make sure either both x and y have +/- or neither of them do: if x.lstrip()[0].isdecimal() and not y.lstrip()[0].isdecimal(): raise PyAutoGUIException("Invalid command at index %s: Y has a +/- but X does not." % (i - len(y))) if not x.lstrip()[0].isdecimal() and y.lstrip()[0].isdecimal(): raise PyAutoGUIException( "Invalid command at index %s: Y does not have a +/- but X does." % (i - len(y)) ) # Get rid of any whitespace at the front: commandList.append(x.lstrip()) commandList.append(y.lstrip()) # Handle the arguments of the (s)leep and (p)ause commands: elif individualCommand in ("s", "p"): try: num = _getNumberToken(commandStr[i:]) i += len(num) # Increment past the number. # TODO - raise an exception if a + or - is in the number. except PyAutoGUIException as excObj: # Exception message starts with something like "Invalid command at index 0:" # Change the index number and reraise it. indexPart, colon, message = str(excObj).partition(":") indexNum = indexPart[len("Invalid command at index ") :] newIndexNum = int(indexNum) + i raise PyAutoGUIException("Invalid command at index %s:%s" % (newIndexNum, message)) # Get rid of any whitespace at the front: commandList.append(num.lstrip()) # Handle the arguments of the (k)ey press, (w)rite, (h)otkeys, and (a)lert commands: elif individualCommand in ("k", "w", "h", "a"): try: quotedString = _getQuotedStringToken(commandStr[i:]) i += len(quotedString) # Increment past the quoted string. except PyAutoGUIException as excObj: # Exception message starts with something like "Invalid command at index 0:" # Change the index number and reraise it. indexPart, colon, message = str(excObj).partition(":") indexNum = indexPart[len("Invalid command at index ") :] newIndexNum = int(indexNum) + i raise PyAutoGUIException("Invalid command at index %s:%s" % (newIndexNum, message)) # Get rid of any whitespace at the front and the quotes: commandList.append(quotedString[1:-1].lstrip()) # Handle the arguments of the (f)or loop command: elif individualCommand == "f": try: numberOfLoops = _getNumberToken(commandStr[i:]) i += len(numberOfLoops) # Increment past the number of loops. subCommandStr = _getParensCommandStrToken(commandStr[i:]) i += len(subCommandStr) # Increment past the sub-command string. except PyAutoGUIException as excObj: # Exception message starts with something like "Invalid command at index 0:" # Change the index number and reraise it. indexPart, colon, message = str(excObj).partition(":") indexNum = indexPart[len("Invalid command at index ") :] newIndexNum = int(indexNum) + i raise PyAutoGUIException("Invalid command at index %s:%s" % (newIndexNum, message)) # Get rid of any whitespace at the front: commandList.append(numberOfLoops.lstrip()) # Get rid of any whitespace at the front and the quotes: subCommandStr = subCommandStr.lstrip()[1:-1] # Recursively call this function and append the list it returns: commandList.append(_tokenizeCommandStr(subCommandStr)) return commandList
Tokenizes commandStr into a list of commands and their arguments for the run() function. Returns the list.
_tokenizeCommandStr
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def run(commandStr, _ssCount=None): """Run a series of PyAutoGUI function calls according to a mini-language made for this function. The `commandStr` is composed of character commands that represent PyAutoGUI function calls. For example, `run('ccg-20,+0c')` clicks the mouse twice, then makes the mouse cursor go 20 pixels to the left, then click again. Whitespace between commands and arguments is ignored. Command characters must be lowercase. Quotes must be single quotes. For example, the previous call could also be written as `run('c c g -20, +0 c')`. The character commands and their equivalents are here: `c` => `click(button=PRIMARY)` `l` => `click(button=LEFT)` `m` => `click(button=MIDDLE)` `r` => `click(button=RIGHT)` `su` => `scroll(1) # scroll up` `sd` => `scroll(-1) # scroll down` `ss` => `screenshot('screenshot1.png') # filename number increases on its own` `gX,Y` => `moveTo(X, Y)` `g+X,-Y` => `move(X, Y) # The + or - prefix is the difference between move() and moveTo()` `dX,Y` => `dragTo(X, Y)` `d+X,-Y` => `drag(X, Y) # The + or - prefix is the difference between drag() and dragTo()` `k'key'` => `press('key')` `w'text'` => `write('text')` `h'key,key,key'` => `hotkey(*'key,key,key'.replace(' ', '').split(','))` `a'hello'` => `alert('hello')` `sN` => `sleep(N) # N can be an int or float` `pN` => `PAUSE = N # N can be an int or float` `fN(commands)` => for i in range(N): run(commands) Note that any changes to `PAUSE` with the `p` command will be undone when this function returns. The original `PAUSE` setting will be reset. TODO - This function is under development. """ # run("ccc") straight forward # run("susu") if 's' then peek at the next character global PAUSE if _ssCount is None: _ssCount = [ 0 ] # Setting this to a mutable list so that the callers can read the changed value. TODO improve this comment commandList = _tokenizeCommandStr(commandStr) # Carry out each command. originalPAUSE = PAUSE _runCommandList(commandList, _ssCount) PAUSE = originalPAUSE
Run a series of PyAutoGUI function calls according to a mini-language made for this function. The `commandStr` is composed of character commands that represent PyAutoGUI function calls. For example, `run('ccg-20,+0c')` clicks the mouse twice, then makes the mouse cursor go 20 pixels to the left, then click again. Whitespace between commands and arguments is ignored. Command characters must be lowercase. Quotes must be single quotes. For example, the previous call could also be written as `run('c c g -20, +0 c')`. The character commands and their equivalents are here: `c` => `click(button=PRIMARY)` `l` => `click(button=LEFT)` `m` => `click(button=MIDDLE)` `r` => `click(button=RIGHT)` `su` => `scroll(1) # scroll up` `sd` => `scroll(-1) # scroll down` `ss` => `screenshot('screenshot1.png') # filename number increases on its own` `gX,Y` => `moveTo(X, Y)` `g+X,-Y` => `move(X, Y) # The + or - prefix is the difference between move() and moveTo()` `dX,Y` => `dragTo(X, Y)` `d+X,-Y` => `drag(X, Y) # The + or - prefix is the difference between drag() and dragTo()` `k'key'` => `press('key')` `w'text'` => `write('text')` `h'key,key,key'` => `hotkey(*'key,key,key'.replace(' ', '').split(','))` `a'hello'` => `alert('hello')` `sN` => `sleep(N) # N can be an int or float` `pN` => `PAUSE = N # N can be an int or float` `fN(commands)` => for i in range(N): run(commands) Note that any changes to `PAUSE` with the `p` command will be undone when this function returns. The original `PAUSE` setting will be reset. TODO - This function is under development.
run
python
asweigart/pyautogui
pyautogui/__init__.py
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py
BSD-3-Clause
def get_args(): """Parses all of the arguments above """ args, unparsed = parser.parse_known_args() if args.num_gpu > 0: setattr(args, 'cuda', True) else: setattr(args, 'cuda', False) if len(unparsed) > 1: print("Unparsed args: {}".format(unparsed)) return args, unparsed
Parses all of the arguments above
get_args
python
tarun005/FLAVR
config.py
https://github.com/tarun005/FLAVR/blob/master/config.py
Apache-2.0
def save_checkpoint(state, directory, is_best, exp_name, filename='checkpoint.pth'): """Saves checkpoint to disk""" if not os.path.exists(directory): os.makedirs(directory) filename = os.path.join(directory , filename) torch.save(state, filename) if is_best: shutil.copyfile(filename, os.path.join(directory , 'model_best.pth'))
Saves checkpoint to disk
save_checkpoint
python
tarun005/FLAVR
myutils.py
https://github.com/tarun005/FLAVR/blob/master/myutils.py
Apache-2.0
def __init__(self, block, conv_makers, layers, stem, zero_init_residual=False): """Generic resnet video generator. Args: block (nn.Module): resnet building block conv_makers (list(functions)): generator function for each layer layers (List[int]): number of blocks per layer stem (nn.Module, optional): Resnet stem, if None, defaults to conv-bn-relu. Defaults to None. """ super(VideoResNet, self).__init__() self.inplanes = 64 self.stem = stem() self.layer1 = self._make_layer(block, conv_makers[0], 64, layers[0], stride=1 ) self.layer2 = self._make_layer(block, conv_makers[1], 128, layers[1], stride=2 , temporal_stride=1) self.layer3 = self._make_layer(block, conv_makers[2], 256, layers[2], stride=2 , temporal_stride=1) self.layer4 = self._make_layer(block, conv_makers[3], 512, layers[3], stride=1, temporal_stride=1) # init weights self._initialize_weights() if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0)
Generic resnet video generator. Args: block (nn.Module): resnet building block conv_makers (list(functions)): generator function for each layer layers (List[int]): number of blocks per layer stem (nn.Module, optional): Resnet stem, if None, defaults to conv-bn-relu. Defaults to None.
__init__
python
tarun005/FLAVR
model/resnet_3D.py
https://github.com/tarun005/FLAVR/blob/master/model/resnet_3D.py
Apache-2.0
def unet_18(pretrained=False, bn=False, progress=True, **kwargs): """ Construct 18 layer Unet3D model as in https://arxiv.org/abs/1711.11248 Args: pretrained (bool): If True, returns a model pre-trained on Kinetics-400 progress (bool): If True, displays a progress bar of the download to stderr Returns: nn.Module: R3D-18 encoder """ global batchnorm if bn: batchnorm = nn.BatchNorm3d else: batchnorm = identity return _video_resnet('r3d_18', pretrained, progress, block=BasicBlock, conv_makers=[Conv3DSimple] * 4, layers=[2, 2, 2, 2], stem=BasicStem, **kwargs)
Construct 18 layer Unet3D model as in https://arxiv.org/abs/1711.11248 Args: pretrained (bool): If True, returns a model pre-trained on Kinetics-400 progress (bool): If True, displays a progress bar of the download to stderr Returns: nn.Module: R3D-18 encoder
unet_18
python
tarun005/FLAVR
model/resnet_3D.py
https://github.com/tarun005/FLAVR/blob/master/model/resnet_3D.py
Apache-2.0
def unet_34(pretrained=False, bn=False, progress=True, **kwargs): """ Construct 34 layer Unet3D model as in https://arxiv.org/abs/1711.11248 Args: pretrained (bool): If True, returns a model pre-trained on Kinetics-400 progress (bool): If True, displays a progress bar of the download to stderr Returns: nn.Module: R3D-18 encoder """ global batchnorm # bn = False if bn: batchnorm = nn.BatchNorm3d else: batchnorm = identity return _video_resnet('r3d_34', pretrained, progress, block=BasicBlock, conv_makers=[Conv3DSimple] * 4, layers=[3, 4, 6, 3], stem=BasicStem, **kwargs)
Construct 34 layer Unet3D model as in https://arxiv.org/abs/1711.11248 Args: pretrained (bool): If True, returns a model pre-trained on Kinetics-400 progress (bool): If True, displays a progress bar of the download to stderr Returns: nn.Module: R3D-18 encoder
unet_34
python
tarun005/FLAVR
model/resnet_3D.py
https://github.com/tarun005/FLAVR/blob/master/model/resnet_3D.py
Apache-2.0
def __init__(self, data_root, is_training , input_frames="1357"): """ Creates a Vimeo Septuplet object. Inputs. data_root: Root path for the Vimeo dataset containing the sep tuples. is_training: Train/Test. input_frames: Which frames to input for frame interpolation network. """ self.data_root = data_root self.image_root = os.path.join(self.data_root, 'sequences') self.training = is_training self.inputs = input_frames test_fn = os.path.join(self.data_root, 'sep_testlist.txt') with open(test_fn, 'r') as f: self.testlist = f.read().splitlines() if self.training: train_fn = os.path.join(self.data_root, 'sep_trainlist.txt') with open(train_fn, 'r') as f: self.trainlist = f.read().splitlines() self.transforms = transforms.Compose([ transforms.RandomCrop(256), transforms.RandomHorizontalFlip(0.5), transforms.RandomVerticalFlip(0.5), transforms.ColorJitter(0.05, 0.05, 0.05, 0.05), transforms.ToTensor() ]) else: self.transforms = transforms.Compose([ transforms.ToTensor() ])
Creates a Vimeo Septuplet object. Inputs. data_root: Root path for the Vimeo dataset containing the sep tuples. is_training: Train/Test. input_frames: Which frames to input for frame interpolation network.
__init__
python
tarun005/FLAVR
dataset/vimeo90k_septuplet.py
https://github.com/tarun005/FLAVR/blob/master/dataset/vimeo90k_septuplet.py
Apache-2.0
def crop(clip, i, j, h, w): """ Args: clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) """ assert len(clip.size()) == 4, "clip should be a 4D tensor" return clip[..., i : i + h, j : j + w]
Args: clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
crop
python
tarun005/FLAVR
dataset/transforms.py
https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py
Apache-2.0
def temporal_center_crop(clip, clip_len): """ Args: clip (torch.tensor): Video clip to be cropped along the temporal axis. Size is (C, T, H, W) """ assert len(clip.size()) == 4, "clip should be a 4D tensor" assert clip.size(1) >= clip_len, "clip is shorter than the proposed lenght" middle = int(clip.size(1) // 2) start = middle - clip_len // 2 return clip[:, start : start + clip_len, ...]
Args: clip (torch.tensor): Video clip to be cropped along the temporal axis. Size is (C, T, H, W)
temporal_center_crop
python
tarun005/FLAVR
dataset/transforms.py
https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py
Apache-2.0
def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"): """ Do spatial cropping and resizing to the video clip Args: clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) i (int): i in (i,j) i.e coordinates of the upper left corner. j (int): j in (i,j) i.e coordinates of the upper left corner. h (int): Height of the cropped region. w (int): Width of the cropped region. size (tuple(int, int)): height and width of resized clip Returns: clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W) """ assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor" clip = crop(clip, i, j, h, w) clip = resize(clip, size, interpolation_mode) return clip
Do spatial cropping and resizing to the video clip Args: clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) i (int): i in (i,j) i.e coordinates of the upper left corner. j (int): j in (i,j) i.e coordinates of the upper left corner. h (int): Height of the cropped region. w (int): Width of the cropped region. size (tuple(int, int)): height and width of resized clip Returns: clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W)
resized_crop
python
tarun005/FLAVR
dataset/transforms.py
https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py
Apache-2.0