id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
31,493 | import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from model_utils import DropPath, _ntuple
The provided code snippet includes necessary dependencies for implementing the `windows_reverse` function. Write a Python function `def windows_reverse(windows, window_size, H, W)` to solv... | Window reverse Args: windows: (n_windows * B, window_size, window_size, C) window_size: (int) window size H: (int) height of image W: (int) width of image Returns: x: (B, H, W, C) |
31,494 | import sys
import os
import time
import logging
import argparse
import random
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from coco import build_coco
from coco import get_dataloader
from coco_eval import CocoEvaluator
from swin_det import bu... | null |
31,496 | import os
import copy
import numpy as np
from PIL import Image
import paddle
from pycocotools.coco import COCO
from pycocotools import mask as coco_mask
import transforms as T
from utils import nested_tensor_from_tensor_list
class CocoDetection(paddle.io.Dataset):
""" COCO Detection dataset
This class gets imag... | Return CocoDetection dataset according to image_set: ['train', 'val'] |
31,497 | import os
import copy
import numpy as np
from PIL import Image
import paddle
from pycocotools.coco import COCO
from pycocotools import mask as coco_mask
import transforms as T
from utils import nested_tensor_from_tensor_list
def collate_fn(batch):
"""Collate function for batching samples
Samples varies in sizes... | return dataloader on train/val set for single/multi gpu Arguments: dataset: paddle.io.Dataset, coco dataset batch_size: int, num of samples in one batch mode: str, ['train', 'val'], dataset to use multi_gpu: bool, if True, DistributedBatchSampler is used for DDP |
31,504 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 8
_C.DATA.BATCH_SIZE_EVAL = 1
_C.DATA.WEIGHT_PATH = "./weights/mask_rcnn_swin_small_patch4_window7.pdparams"
_C.DATA.VAL_DATA_PATH = "/dataset/coco/"
_C.DATA.DATASET = 'coco'
_C.DATA.IMAGE_SIZE = 640... | Return a clone config |
31,516 | import sys
import os
import time
import logging
import argparse
import random
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from coco import build_coco
from coco import get_dataloader
from coco_eval import CocoEvaluator
from swin_det import bu... | Training for one epoch Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, det model base_ds: coco api instance optimizer: optimizer epoch: int, current epoch total_epoch: int, total num of epoch, for logging debug_steps: int, num of iters to log info accum_iter: int, num of iters for accumulat... |
31,517 | import sys
import os
import time
import logging
import argparse
import random
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from coco import build_coco
from coco import get_dataloader
from coco_eval import CocoEvaluator
from swin_det import bu... | Validation for whole dataset Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a ViT model criterion: criterion postprocessors: postprocessor for generating bboxes base_ds: COCO instance total_epoch: int, total num of epoch, for logging debug_steps: int, num of iters to log info Returns: val_... |
31,519 | import copy
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from droppath import DropPath
class VisualTransformer(nn.Layer):
"""ViT transformer
ViT Transformer, classifier is a single Linear layer for finetune,
For training from scratch, two layer mlp sho... | build vit model from config |
31,520 | import math
import numpy as np
import paddle
import paddle.nn as nn
from paddle.optimizer.lr import LRScheduler
The provided code snippet includes necessary dependencies for implementing the `get_exclude_from_weight_decay_fn` function. Write a Python function `def get_exclude_from_weight_decay_fn(exclude_list=[])` to ... | Set params with no weight decay during the training For certain params, e.g., positional encoding in ViT, weight decay may not needed during the learning, this method is used to find these params. Args: exclude_list: a list of params names which need to exclude from weight decay. Returns: exclude_from_weight_decay_fn: ... |
31,521 | import argparse
import numpy as np
import paddle
import torch
from transformer import *
from config import *
print(config)
def print_model_named_params(model):
print('----------------------------------')
for name, param in model.named_parameters():
print(name, param.shape)
print('------------------... | null |
31,522 | import argparse
import numpy as np
import paddle
import torch
from transformer import *
from config import *
print(config)
def print_model_named_buffers(model):
print('----------------------------------')
for name, param in model.named_buffers():
print(name, param.shape)
print('--------------------... | null |
31,523 | import argparse
import numpy as np
import paddle
import torch
from transformer import *
from config import *
print(config)
def torch_to_paddle_mapping():
mapping = [
('patch_embed.proj', 'patch_embedding.patch_embedding'),
('cls_token', 'patch_embedding.cls_token'),
('pos_embed', 'patch_embe... | null |
31,524 | import sys
import os
import time
import logging
import argparse
import random
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from datasets import get_dataloader
from datasets import get_dataset
import utils
from utils import Average... | return argumeents, this will overwrite the config after loading yaml file |
31,525 | import sys
import os
import time
import logging
import argparse
import random
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from datasets import get_dataloader
from datasets import get_dataset
import utils
from utils import Average... | null |
31,526 | import os
import math
import random
import PIL
import paddle
import paddle.nn as nn
from paddle.io import Dataset, DataLoader, DistributedBatchSampler
from paddle.vision import transforms, datasets, image_load
class ImageNet2012Dataset(Dataset):
"""Build ImageNet2012 dataset
This class gets train/val imagenet d... | Get dataset from config and mode (train/val) Returns the related dataset object according to configs and mode(train/val) Args: config: configs contains dataset related settings. see config.py for details Returns: dataset: dataset object |
31,527 | import os
import math
import random
import PIL
import paddle
import paddle.nn as nn
from paddle.io import Dataset, DataLoader, DistributedBatchSampler
from paddle.vision import transforms, datasets, image_load
The provided code snippet includes necessary dependencies for implementing the `get_dataloader` function. Wri... | Get dataloader with config, dataset, mode as input, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object mode: train/val multi_process: if True, use DistributedBatchSampler to support multi-processing Returns: data... |
31,528 | import os
from yacs.config import CfgNode as CN
import yaml
def _update_config_from_file(config, cfg_file):
config.defrost()
with open(cfg_file, 'r') as infile:
yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader)
for cfg in yaml_cfg.setdefault('BASE', ['']):
if cfg:
_update_conf... | Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config |
31,529 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 16
_C.DATA.BATCH_SIZE_EVAL = 8
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.SMALL_CROP_IMAGE_SIZE = 96
_C.DATA.CROP_PCT = 0.875
_C.DATA.N... | Return a clone of config or load from yaml file |
31,531 | import sys
import os
import time
import logging
import argparse
import random
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from datasets import get_dataloader
from datasets import get_dataset
import utils
from utils import Average... | set logging file and format Args: filename: str, full path of the logger file to write logger_name: str, the logger name, e.g., 'master_logger', 'local_logger' Return: logger: python logger |
31,532 | import sys
import os
import time
import logging
import argparse
import random
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.distributed as dist
from datasets import get_dataloader
from datasets import get_dataset
import utils
from utils import Average... | Training for one epoch Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a ViT model criterion: nn.criterion epoch: int, current epoch total_epochs: int, total num of epochs total_batch: int, total num of batches for one epoch debug_steps: int, num of iters to log info, default: 100 accum_ite... |
31,537 | import paddle
The provided code snippet includes necessary dependencies for implementing the `interpolate_position_embedding` function. Write a Python function `def interpolate_position_embedding(model, state_dict)` to solve the following problem:
interpolate pos embed from model state for new model, This version is f... | interpolate pos embed from model state for new model, This version is for Swin transformer |
31,538 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
31,539 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
31,540 | import os
import math
import numpy as np
import random
import glob
import PIL
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from random_erasing import RandomErasing
from config import... | null |
31,541 | import os
import math
import numpy as np
import random
import glob
import PIL
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from random_erasing import RandomErasing
from config import... | Get dataloader from dataset, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object is_train: bool, when False, shuffle is off and BATCH_SIZE_EVAL is used, default: True use_dist_sampler: if True, DistributedBatchSam... |
31,542 | import os
from yacs.config import CfgNode as CN
import yaml
def _update_config_from_file(config, cfg_file):
"""Load cfg file (.yaml) and update config object
Args:
config: config object
cfg_file: config file (.yaml)
Return:
None
"""
config.defrost()
with open(cfg_file, 'r... | Update config by ArgumentParser Configs that are often used can be updated from arguments Args: args: ArgumentParser contains options Return: config: updated config |
31,543 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.ANNO_FOLDER = './anno'
_C.DATA.DATA_FOLDER = './data'
_C.DATA.DATA_LIST_VAL = None
_C.DATA.DATA_LIST_TRAIN = None
_C.DATA.DATASET = 'ABAW'
_C.DATA.CL... | Return a clone of config and optionally overwrite it from yaml file |
31,546 | import paddle
import paddle.nn as nn
from droppath import DropPath
class SwinTransformer(nn.Layer):
"""SwinTransformer class
Attributes:
num_classes: int, num of image classes
num_stages: int, num of stages contains patch merging and Swin blocks
depths: list of int, num of Swin blocks in... | build swin model from config |
31,550 | import numpy as np
import paddle
import paddle.nn as nn
import paddle.distributed as dist
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
class MyDataset(Dataset):
def __init__(self):
super().__init__()
self.data = np.arange(32).astype('fl... | null |
31,551 | import numpy as np
import paddle
import paddle.nn as nn
import paddle.distributed as dist
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
def get_dataloader(dataset, batch_size):
def build_model():
def main_worker(*args):
dataset = args[0]
dataloader... | null |
31,552 | import paddle
import paddle.nn as nn
from mask import generate_mask
def windows_partition(x, window_size):
B, H, W, C = x.shape
# B, H/ws, ws, W/ws, ws, C
x = x.reshape([B, H//window_size, window_size, W//window_size, window_size, C])
# B, H/ws, W/ws, ws, ws, c
x = x.transpose([0, 1, 3, 2, 4, 5])
... | null |
31,553 | import paddle
import paddle.nn as nn
from mask import generate_mask
def windows_reverse(windows, window_size, H, W):
# windows: [B*num_windows, ws*ws, C]
B = int(windows.shape[0] // ( H / window_size * W / window_size))
x = windows.reshape([B, H//window_size, W//window_size, window_size, window_size, -1])
... | null |
31,554 | import paddle
from PIL import Image
paddle.set_device('cpu')
def windows_partition(x, window_size):
""" partite windows into window_size x window_size
Args:
x: Tensor, shape=[b, h, w, c]
window_size: int, window size
Returns:
x: Tensor, shape=[num_windows*b, window_size, window_size,... | null |
31,557 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from resnet import ResNet18
from transformer import Transformer
class PositionEmbedding(nn.Layer):
def __init__(self, embed_dim):
def forward(self, x):
class DETR(nn.Layer):
def __init__(self, backbone, pos_embed, transformer, num_clas... | null |
31,558 | import paddle
import paddle.nn as nn
def windows_partition(x, window_size):
B, H, W, C = x.shape
x = x.reshape([B, H//window_size, window_size, W//window_size, window_size, C])
x = x.transpose([0, 1, 3, 2, 4, 5]) #[B, h//ws, w//ws, ws, ws, c]
x = x.reshape([-1, window_size, window_size, C]) # [B * num_... | null |
31,559 | import paddle
import paddle.nn as nn
def windows_reverse(windows, window_size, H, W):
# windows: [B*num_windows, ws*ws, c]
B = int(windows.shape[0] // (H / window_size * W / window_size))
x = windows.reshape([B, H // window_size, W // window_size, window_size, window_size, -1])
x = x.transpose([0, 1, 3... | null |
31,560 | from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.vision import datasets
from paddle.vision import transforms
def get_transforms(mode='train'):
if mode == 'train':
data_transforms = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomH... | null |
31,561 | from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.vision import datasets
from paddle.vision import transforms
def get_dataloader(dataset, batch_size=128, mode='train'):
dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=2, shuffle=(mode == 'train'))
return dataloader | null |
31,562 | import paddle
import paddle.nn as nn
from resnet18 import ResNet18
from dataset import get_dataset
from dataset import get_dataloader
from utils import AverageMeter
class AverageMeter():
""" Meter for monitoring losses"""
def __init__(self):
self.avg = 0
self.sum = 0
self.cnt = 0
... | null |
31,563 | import paddle
import paddle.nn as nn
from resnet18 import ResNet18
from dataset import get_dataset
from dataset import get_dataloader
from utils import AverageMeter
class AverageMeter():
def __init__(self):
def reset(self):
def update(self, val, n=1):
def validate(model, dataloader, critertion):
pr... | null |
31,564 | import argparse
from config import get_config
from config import update_config
def get_arguments():
parser = argparse.ArgumentParser('ViT')
parser.add_argument('-cfg', type=str, default=None)
parser.add_argument('-dataset', type=str, default=None)
parser.add_argument('-batch_size', type=int, default=No... | null |
31,565 | from yacs.config import CfgNode as CN
import yaml
def update_config(config, args):
if args.cfg:
_update_config_form_file(config, args.cfg)
if args.dataset:
config.DATA.DATASET = args.dataset
if args.batch_size:
config.DATA.BATCH_SIZE = args.batch_size
return config | null |
31,566 | from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.DATA = CN()
_C.DATA.DATASET = 'Cifar10'
_C.DATA.BATCH_SIZE = 128
_C.MODEL = CN()
_C.MODEL.NUM_CLASSES = 1000
_C.MODEL.TRANS = CN()
_C.MODEL.TRANS.EMBED_DIM = 96
_C.MODEL.TRANS.DEPTHS = [2, 2, 6, 2]
_C.MODEL.TRANS.QKV_BIAS = False
def _update_config_from_fi... | null |
31,567 | import numpy as np
from PIL import Image
import paddle
import paddle.vision.transforms as T
def crop(image, region):
# region: [i, j, h, w]
cropped_image = T.crop(image, *region)
return cropped_image | null |
31,568 | import configparser
import hashlib
import logging
import glob
import os
import sys
from qobuz_dl.bundle import Bundle
from qobuz_dl.color import GREEN, RED, YELLOW
from qobuz_dl.commands import qobuz_dl_args
from qobuz_dl.core import QobuzDL
from qobuz_dl.downloader import DEFAULT_FOLDER, DEFAULT_TRACK
logging.basicCon... | null |
31,569 | import configparser
import hashlib
import logging
import glob
import os
import sys
from qobuz_dl.bundle import Bundle
from qobuz_dl.color import GREEN, RED, YELLOW
from qobuz_dl.commands import qobuz_dl_args
from qobuz_dl.core import QobuzDL
from qobuz_dl.downloader import DEFAULT_FOLDER, DEFAULT_TRACK
if os.name == "n... | null |
31,570 | import re
import string
import os
import logging
import time
from mutagen.mp3 import EasyMP3
from mutagen.flac import FLAC
EXTENSIONS = (".mp3", ".flac")
def make_m3u(pl_directory):
track_list = ["#EXTM3U"]
rel_folder = os.path.basename(os.path.normpath(pl_directory))
pl_name = rel_folder + ".m3u"
for ... | null |
31,571 | import re
import string
import os
import logging
import time
from mutagen.mp3 import EasyMP3
from mutagen.flac import FLAC
logger = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `smart_discography_filter` function. Write a Python function `def smart_discogra... | When downloading some artists' discography, many random and spam-like albums can get downloaded. This helps filter those out to just get the good stuff. This function removes: * albums by other artists, which may contain a feature from the requested artist * duplicate albums in different qualities * (optionally) remove... |
31,572 | import re
import string
import os
import logging
import time
from mutagen.mp3 import EasyMP3
from mutagen.flac import FLAC
def format_duration(duration):
return time.strftime("%H:%M:%S", time.gmtime(duration)) | null |
31,573 | import re
import string
import os
import logging
import time
from mutagen.mp3 import EasyMP3
from mutagen.flac import FLAC
def create_and_return_dir(directory):
fix = os.path.normpath(directory)
os.makedirs(fix, exist_ok=True)
return fix | null |
31,574 | import re
import string
import os
import logging
import time
from mutagen.mp3 import EasyMP3
from mutagen.flac import FLAC
The provided code snippet includes necessary dependencies for implementing the `get_url_info` function. Write a Python function `def get_url_info(url)` to solve the following problem:
Returns the ... | Returns the type of the url and the id. Compatible with urls of the form: https://www.qobuz.com/us-en/{type}/{name}/{id} https://open.qobuz.com/{type}/{id} https://play.qobuz.com/{type}/{id} /us-en/{type}/-/{id} |
31,575 | import logging
import sqlite3
from qobuz_dl.color import YELLOW, RED
logger = logging.getLogger(__name__)
YELLOW = Fore.YELLOW
def create_db(db_path):
with sqlite3.connect(db_path) as conn:
try:
conn.execute("CREATE TABLE downloads (id TEXT UNIQUE NOT NULL);")
logger.info(f"{YELLOW... | null |
31,576 | import logging
import sqlite3
from qobuz_dl.color import YELLOW, RED
logger = logging.getLogger(__name__)
RED = Fore.RED
def handle_download_id(db_path, item_id, add_id=False):
if not db_path:
return
with sqlite3.connect(db_path) as conn:
# If add_if is False return a string to know if the ID... | null |
31,577 | import re
import os
import logging
from mutagen.flac import FLAC, Picture
import mutagen.id3 as id3
from mutagen.id3 import ID3NoHeaderError
def _get_title(track_dict):
title = track_dict["title"]
version = track_dict.get("version")
if version:
title = f"{title} ({version})"
# for classical work... | Tag a FLAC file :param str filename: FLAC file path :param str root_dir: Root dir used to get the cover art :param str final_name: Final name of the FLAC file (complete path) :param dict d: Track dictionary from Qobuz_client :param dict album: Album dictionary from Qobuz_client :param bool istrack :param bool em_image:... |
31,578 | import re
import os
import logging
from mutagen.flac import FLAC, Picture
import mutagen.id3 as id3
from mutagen.id3 import ID3NoHeaderError
ID3_LEGEND = {
"album": id3.TALB,
"albumartist": id3.TPE2,
"artist": id3.TPE1,
"comment": id3.COMM,
"composer": id3.TCOM,
"copyright": id3.TCOP,
"date"... | Tag an mp3 file :param str filename: mp3 temporary file path :param str root_dir: Root dir used to get the cover art :param str final_name: Final name of the mp3 file (complete path) :param dict d: Track dictionary from Qobuz_client :param bool istrack :param bool em_image: Embed cover art into file |
31,579 | import logging
import os
from typing import Tuple
import requests
from pathvalidate import sanitize_filename, sanitize_filepath
from tqdm import tqdm
import qobuz_dl.metadata as metadata
from qobuz_dl.color import OFF, GREEN, RED, YELLOW, CYAN
from qobuz_dl.exceptions import NonStreamable
The provided code snippet inc... | f'[{item["bit_depth"]}/{item["sampling_rate"]}] |
31,580 | import logging
import os
from typing import Tuple
import requests
from pathvalidate import sanitize_filename, sanitize_filepath
from tqdm import tqdm
import qobuz_dl.metadata as metadata
from qobuz_dl.color import OFF, GREEN, RED, YELLOW, CYAN
from qobuz_dl.exceptions import NonStreamable
def _get_title(item_dict):
... | null |
31,581 | import logging
import os
from typing import Tuple
import requests
from pathvalidate import sanitize_filename, sanitize_filepath
from tqdm import tqdm
import qobuz_dl.metadata as metadata
from qobuz_dl.color import OFF, GREEN, RED, YELLOW, CYAN
from qobuz_dl.exceptions import NonStreamable
logger = logging.getLogger(__n... | null |
31,582 | import logging
import os
from typing import Tuple
import requests
from pathvalidate import sanitize_filename, sanitize_filepath
from tqdm import tqdm
import qobuz_dl.metadata as metadata
from qobuz_dl.color import OFF, GREEN, RED, YELLOW, CYAN
from qobuz_dl.exceptions import NonStreamable
DEFAULT_FORMATS = {
"MP3":... | Cleans up the format strings, avoids errors with MP3 files. |
31,583 | import logging
import os
from typing import Tuple
import requests
from pathvalidate import sanitize_filename, sanitize_filepath
from tqdm import tqdm
import qobuz_dl.metadata as metadata
from qobuz_dl.color import OFF, GREEN, RED, YELLOW, CYAN
from qobuz_dl.exceptions import NonStreamable
The provided code snippet inc... | A replacement for chained `get()` statements on dicts: >>> d = {'foo': {'bar': 'baz'}} >>> _safe_get(d, 'baz') None >>> _safe_get(d, 'foo', 'bar') 'baz' |
31,584 | from setuptools import setup, find_packages
def read_file(fname):
with open(fname, "r") as f:
return f.read() | null |
31,585 | from torch.nn import Conv2d, Module, Sequential, InstanceNorm2d, ReLU, ConvTranspose2d
from nn.init_function import create_init_function
def create_init_function(method: str = 'none'):
def init(module: Module):
if method == 'none':
return module
elif method == 'he':
kaiming_... | null |
31,586 | from torch.nn import Conv2d, Module, Sequential, InstanceNorm2d, ReLU, ConvTranspose2d
from nn.init_function import create_init_function
def Conv7(in_channels: int, out_channels: int, initialization_method='he') -> Module:
init = create_init_function(initialization_method)
return init(Conv2d(in_channels, out_ch... | null |
31,587 | from torch.nn import Conv2d, Module, Sequential, InstanceNorm2d, ReLU, ConvTranspose2d
from nn.init_function import create_init_function
def create_init_function(method: str = 'none'):
def init(module: Module):
if method == 'none':
return module
elif method == 'he':
kaiming_... | null |
31,588 | from torch.nn import Conv2d, Module, Sequential, InstanceNorm2d, ReLU, ConvTranspose2d
from nn.init_function import create_init_function
def create_init_function(method: str = 'none'):
def init(module: Module):
if method == 'none':
return module
elif method == 'he':
kaiming_... | null |
31,589 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def is_power2(x):
return x != 0 and ((x & (x - 1)) == 0) | null |
31,590 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def torch_save(content, file_name):
os.makedirs(os.path.dirname(file_name), exist_ok=True)
with open(file_name, 'wb') as f:
torch.save(content, f)
def save_rng_state(file_name):
rng_state = torch.get_rng_state()
torch... | null |
31,591 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def torch_load(file_name, **kwargs):
with open(file_name, 'rb') as f:
return torch.load(f, **kwargs)
def load_rng_state(file_name):
rng_state = torch_load(file_name)
torch.set_rng_state(rng_state) | null |
31,592 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def optimizer_to_device(optim, device):
for state in optim.state.values():
for k, v in state.items():
if isinstance(v, torch.Tensor):
state[k] = v.to(device) | null |
31,593 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def linear_to_srgb(x):
x = numpy.clip(x, 0.0, 1.0)
return numpy.where(x <= 0.003130804953560372, x * 12.92, 1.055 * (x ** (1.0 / 2.4)) - 0.055)
def rgba_to_numpy_image_greenscreen(torch_image: Tensor):
height = torch_image.shape[... | null |
31,594 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def linear_to_srgb(x):
x = numpy.clip(x, 0.0, 1.0)
return numpy.where(x <= 0.003130804953560372, x * 12.92, 1.055 * (x ** (1.0 / 2.4)) - 0.055)
def rgba_to_numpy_image(torch_image: Tensor):
height = torch_image.shape[1]
width... | null |
31,595 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def srgb_to_linear(x):
def extract_pytorch_image_from_filelike(file):
pil_image = PIL.Image.open(file)
numpy_image = numpy.asarray(pil_image) / 255.0
h, w, c = numpy_image.shape
image = numpy_image.reshape(h, w, c)
image[... | null |
31,596 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def srgb_to_linear(x):
def extract_numpy_image_from_filelike(file):
pil_image = PIL.Image.open(file)
image_size = pil_image.width
image = (numpy.asarray(pil_image) / 255.0).reshape(image_size, image_size, 4)
image[:, :, 0:3] ... | null |
31,597 | import os
import PIL.Image
import numpy
import torch
from torch import Tensor
def create_parent_dir(file_name):
os.makedirs(os.path.dirname(file_name), exist_ok=True) | null |
31,598 | import math
LEFT_EYE_HORIZ_POINTS = [36, 39]
LEFT_EYE_TOP_POINTS = [37, 38]
LEFT_EYE_BOTTOM_POINTS = [41, 40]
def compute_eye_normalized_ratio(face_landmarks, eye_horiz_points, eye_bottom_points, eye_top_points, min_ratio,
max_ratio):
left_eye_horiz_diff = face_landmarks.part(eye_ho... | null |
31,599 | import math
RIGHT_EYE_HORIZ_POINTS = [42, 45]
RIGHT_EYE_TOP_POINTS = [43, 44]
RIGHT_EYE_BOTTOM_POINTS = [47, 46]
def compute_eye_normalized_ratio(face_landmarks, eye_horiz_points, eye_bottom_points, eye_top_points, min_ratio,
max_ratio):
left_eye_horiz_diff = face_landmarks.part(eye... | null |
31,600 | import math
MOUTH_TOP_POINTS = [61, 62, 63]
MOUTH_BOTTOM_POINTS = [67, 66, 65]
MOUTH_HORIZ_POINTS = [60, 64]
def compute_mouth_normalized_ratio(face_landmarks, min_mouth_ratio, max_mouth_ratio):
mouth_top_point = (face_landmarks.part(MOUTH_TOP_POINTS[0])
+ face_landmarks.part(MOUTH_TOP_POINT... | null |
31,601 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,602 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,603 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,604 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,605 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,606 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,607 | import argparse
import io
from typing import List
import pypdfium2
import streamlit as st
from surya.detection import batch_text_detection
from surya.layout import batch_layout_detection
from surya.model.detection.segformer import load_model, load_processor
from surya.model.recognition.model import load_model as load_r... | null |
31,608 | import argparse
import subprocess
import os
def run_app():
parser = argparse.ArgumentParser(description="Run the streamlit OCR app")
parser.add_argument("--math", action="store_true", help="Use math model for detection", default=False)
args = parser.parse_args()
cur_dir = os.path.dirname(os.path.abspa... | null |
31,609 | from collections import defaultdict
from typing import List
from tqdm import tqdm
import torch
from PIL import Image
from surya.detection import batch_text_detection
from surya.input.processing import slice_polys_from_image, slice_bboxes_from_image
from surya.postprocessing.text import truncate_repetitions, sort_text_l... | null |
31,610 |
def is_arabic(lang_code):
return lang_code in ["ar", "fa", "ps", "ug", "ur"] | null |
31,611 | import math
import copy
def rescale_point(point, processor_size, image_size):
# Point is in x, y format
page_width, page_height = processor_size
img_width, img_height = image_size
width_scaler = img_width / page_width
height_scaler = img_height / page_height
new_point = copy.deepcopy(point)
... | null |
31,612 | from typing import List
import cv2
import numpy as np
from PIL import Image, ImageDraw
from surya.postprocessing.util import get_line_angle, rescale_bbox
from surya.schema import ColumnLine
class ColumnLine(Bbox):
vertical: bool
horizontal: bool
def draw_lines_on_image(line_info: List[ColumnLine], img):
d... | null |
31,613 | import re
from ftfy import fix_text
def extract_latex_with_positions(text):
pattern = r'(\$\$.*?\$\$|\$.*?\$)'
matches = []
for match in re.finditer(pattern, text, re.DOTALL):
matches.append((match.group(), match.start(), match.end()))
return matches
def slice_latex(text):
# Extract LaTeX b... | null |
31,614 | import re
from ftfy import fix_text
def strip_fences(text):
while text.startswith("$"):
text = text[1:]
while text.endswith("$"):
text = text[:-1]
return text | null |
31,615 | from typing import List, Tuple
import numpy as np
import cv2
import math
from PIL import ImageDraw, ImageFont
from surya.postprocessing.fonts import get_font_path
from surya.postprocessing.util import rescale_bbox
from surya.schema import PolygonBox
from surya.settings import settings
def draw_bboxes_on_image(bboxes, ... | null |
31,616 | from typing import List
from surya.languages import LANGUAGE_TO_CODE, CODE_TO_LANGUAGE
def get_unique_langs(langs: List[List[str]]):
uniques = []
for lang_list in langs:
for lang in lang_list:
if lang not in uniques:
uniques.append(lang)
return uniques | null |
31,617 | from surya.input.processing import open_pdf, get_page_images
import os
import filetype
from PIL import Image
import json
def load_pdf(pdf_path, max_pages=None, start_page=None):
doc = open_pdf(pdf_path)
last_page = len(doc)
if start_page:
assert start_page < last_page and start_page >= 0, f"Start pa... | null |
31,618 | from surya.input.processing import open_pdf, get_page_images
import os
import filetype
from PIL import Image
import json
def load_pdf(pdf_path, max_pages=None, start_page=None):
def load_image(image_path):
def load_from_folder(folder_path, max_pages=None, start_page=None):
image_paths = [os.path.join(folder_path, ... | null |
31,619 | from surya.input.processing import open_pdf, get_page_images
import os
import filetype
from PIL import Image
import json
def load_lang_file(lang_path, names):
with open(lang_path, "r") as f:
lang_dict = json.load(f)
return [lang_dict[name].copy() for name in names] | null |
31,620 | import fitz as pymupdf
from surya.postprocessing.util import rescale_bbox
def rescale_bbox(bbox, processor_size, image_size):
page_width, page_height = processor_size
img_width, img_height = image_size
width_scaler = img_width / page_width
height_scaler = img_height / page_height
new_bbox = copy.... | null |
31,621 | def merge_boxes(box1, box2):
return (min(box1[0], box2[0]), min(box1[1], box2[1]), max(box1[2], box2[2]), max(box1[3], box2[3]))
def join_lines(bboxes, max_gap=5):
to_merge = {}
for i, box1 in bboxes:
for z, box2 in bboxes[i + 1:]:
j = i + z + 1
if box1 == box2:
... | null |
31,622 | from typing import List, Optional
import numpy as np
import pytesseract
from pytesseract import Output
from tqdm import tqdm
from surya.input.processing import slice_bboxes_from_image
from surya.settings import settings
import os
from concurrent.futures import ProcessPoolExecutor
from surya.detection import get_batch_s... | null |
31,623 | from typing import List, Optional
import numpy as np
import pytesseract
from pytesseract import Output
from tqdm import tqdm
from surya.input.processing import slice_bboxes_from_image
from surya.settings import settings
import os
from concurrent.futures import ProcessPoolExecutor
from surya.detection import get_batch_s... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.