id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
141,000
import sys from typing import List, Tuple, Type from core.constants import PRECISION from core.quality_signals.base import RPSBase from core.data_types import SignalType, ScoreType, TextSlice from core.document import Document from utilities.register.registry_utils import * class RPSBase: r""" Base class for RP si...
r""" Returns a list of signal functions (i.e., RPSBase instances) that are used to extract line signals from a document. Returns: A list of signal function class instances.
141,001
from collections import Counter import math import re import sys from typing import List, Tuple, Type from core.constants import PRECISION from core.data_types import SignalType from core.quality_signals.base import RPSBase from core.document import Document from utilities.register.registry_utils import * The provided...
r""" Returns a list of signal names and their data types
141,002
from collections import Counter import math import re import sys from typing import List, Tuple, Type from core.constants import PRECISION from core.data_types import SignalType from core.quality_signals.base import RPSBase from core.document import Document from utilities.register.registry_utils import * class RPSBas...
r""" Returns a list of signal functions (i.e., RPSBase instances) that are used to extract natural language signals from a document. Returns: A list of signal function class instances.
141,003
import numpy as np import scipy.stats as stats import sys from typing import List, Tuple, Type, Optional from pathlib import Path from core.constants import PRECISION from core.quality_signals.base import RPSBase from core.quality_signals.utils.dsir import hash_feature from core.document import Document from core.data_...
r""" Returns a list of signal names and their data types
141,004
import numpy as np import scipy.stats as stats import sys from typing import List, Tuple, Type, Optional from pathlib import Path from core.constants import PRECISION from core.quality_signals.base import RPSBase from core.quality_signals.utils.dsir import hash_feature from core.document import Document from core.data_...
r""" Returns a list of signal functions (i.e., RPSBase instances) that are used to extract content signals from a document. Returns: A list of signal function class instances.
141,005
import sys from typing import List, Tuple, Type import fasttext from core.constants import PRECISION, CCNET_LABEL from core.quality_signals.base import RPSBase from core.document import Document from core.data_types import SignalType from core.quality_signals.utils.classifiers import \ preprocess_quality_classifier...
r""" Returns a list of signal names and their data types
141,006
import sys from typing import List, Tuple, Type import fasttext from core.constants import PRECISION, CCNET_LABEL from core.quality_signals.base import RPSBase from core.document import Document from core.data_types import SignalType from core.quality_signals.utils.classifiers import \ preprocess_quality_classifier...
r""" Returns a list of signal functions (i.e., RPSBase instances) that are used to extract content signals from a document. Args: wikiref_model: A fasttext model trained on Wikipedia references. palm_model: A fasttext model trained on ccnet vs {books, openwebtext, wikipedia}. wikipedia_model: A fasttext model trained o...
141,007
import re import sys import operator from pathlib import Path from typing import List, Tuple, Type from core.constants import PRECISION from core.quality_signals.base import RPSBase from core.quality_signals.utils.stop_words import get_stop_words from core.document import Document from core.data_types import SignalType...
r""" Returns a list of signal names and their data types
141,008
import re import sys import operator from pathlib import Path from typing import List, Tuple, Type from core.constants import PRECISION from core.quality_signals.base import RPSBase from core.quality_signals.utils.stop_words import get_stop_words from core.document import Document from core.data_types import SignalType...
r""" Returns a list of signal functions (i.e., RPSBase instances) that are used to extract content signals from a document. Args: language: The language of the document. bad_urls_dir: directory containing the UT1 blacklist. bad_words_dir: directory containing the LDNOOBW blacklist. Returns: A list of signal function cl...
141,009
import numpy as np from typing import Tuple def compute_hash(ngram: str, buckets: int): def hash_feature( unigrams: Tuple[str], bigrams: Tuple[str], buckets: int ) -> np.ndarray: counts = np.zeros(buckets, dtype=np.int64) for unigram in unigrams: counts[compute_hash(unigram, buckets=buckets)] ...
null
141,010
from typing import Set stop_words = { "bg": {"а", "автентичен", "аз", "ако", "ала", "бе", "без", "беше", "би", "бивш", "бивша", "бившо", "бил", "била", "били", "било", "благодаря", "близо", "бъдат", "бъде", "бяха", "в", "вас", "ваш", "ваша", "вероятно", "вече", "взема", "ви", "вие",...
null
141,011
from core.document import Document class Document: __slots__ = ( "_raw_content", "_normalized_content", "_raw_lines", "_normalized_lines", "_raw_words", "_normalized_words", "_num_raw_words", "_num_normalized_words", "_domain", "_raw_2grams", "_raw_3grams", "_norm_2grams", "_norm_3g...
r""" Preprocesses a document for quality classification. This function removes all newlines and trailing whitespaces from the document. Args: document: A document. Returns: A string.
141,012
import json from pathlib import Path from typing import Dict, Set def load_bad_urls_index(bad_urls_dir: Path) -> Dict[str, int]: with open(bad_urls_dir / "domain_to_category_id.json", "r") as f: domain_to_category_id = json.load(f) return domain_to_category_id
null
141,013
import json from pathlib import Path from typing import Dict, Set _DEFAULT_LANGS = ("en", "fr", "it", "es", "de") The provided code snippet includes necessary dependencies for implementing the `load_bad_words` function. Write a Python function `def load_bad_words(bad_words_dir: Path, lang: str) -> Set[str]` to solve t...
r""" load the LDNOOBW word list for a given language Source: https://github.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words Args: bad_words_dir (Path): The path to the resources directory where the list is stored lang (str): The language for which to fetch the word list Returns: A set of words
141,014
from nltk.tokenize import WordPunctTokenizer import re from typing import Optional, Tuple, Callable from utilities.text import normalize, form_ngrams from core.data_types import TextSlice from core.quality_signals.utils.dsir import hash_feature def _compute_ngrams(text_seq, n): return tuple(form_ngrams(iter(text_s...
null
141,015
from nltk.tokenize import WordPunctTokenizer import re from typing import Optional, Tuple, Callable from utilities.text import normalize, form_ngrams from core.data_types import TextSlice from core.quality_signals.utils.dsir import hash_feature class TextSlice: text: str start: int end: int def __len_...
This function is adapted from dolma: https://github.com/allenai/dolma Split a string into paragraphs. A paragraph is defined as a sequence of zero or more characters, followed by a newline character, or a sequence of one or more characters, followed by the end of the string.
141,016
import logging from pathlib import Path from typing import Optional from .format import LOG_FMT LOG_FMT = '[%(asctime)s]::(PID %(process)d)::%(levelname)-2s::%(message)s' def configure_logger( logfile: Optional[Path] = None, level: int = logging.DEBUG, stream: bool = True ): root = logging.getLogg...
null
141,017
import logging from logging.handlers import QueueHandler import multiprocessing as mp from pathlib import Path from typing import Optional from .format import LOG_FMT def configure_worker_logger( queue: Optional[mp.Queue] = None, level: int = logging.DEBUG ): root = logging.getLogger() if not root.has...
null
141,018
import logging from logging.handlers import QueueHandler import multiprocessing as mp from pathlib import Path from typing import Optional from .format import LOG_FMT LOG_FMT = '[%(asctime)s]::(PID %(process)d)::%(levelname)-2s::%(message)s' def configure_listener_logger( logfile: Optional[Path] = None, level...
null
141,019
import inspect from typing import Tuple, List, Type from core.quality_signals.base import RPSBase def get_callables_from_module(module: object) -> List[Type[RPSBase]]: r""" Returns a list of signal class references that are defined in the module. Args: module: The module to search for signal classes...
r""" Returns a list of signal names and their data types, defining the schema for signals.
141,020
import re def generate_paragraphs(text: str, remove_empty: bool = True): for match in re.finditer(r"([^\n]*\n|[^\n]+$)", text): text_slice = text[match.start():match.end()] if remove_empty and not text_slice.strip(): continue yield text_slice
null
141,021
def form_ngrams(sequence, n): history = [] # build the first ngram, yielding only when we have a full ngram while n > 1: try: next_item = next(sequence) except StopIteration: # no more data, terminate the generator return history.append(next_item...
null
141,022
import re import string import unicodedata TRANSLATION_TABLE_PUNCTUATION = str.maketrans("", "", string.punctuation) The provided code snippet includes necessary dependencies for implementing the `normalize` function. Write a Python function `def normalize( text: str, remove_punct: bool = True, ...
Normalize the text by lowercasing and removing punctuation.
141,023
import boto3 from botocore import UNSIGNED def init_client( endpoint_url: str, aws_access_key_id: str = None, aws_secret_access_key: str = None, signature_version: str = UNSIGNED ): return boto3.client( service_name='s3', aws_access_key_id=aws_access_key_id, ...
null
141,024
import argparse from collections import defaultdict import itertools import json from pathlib import Path import time import urllib.request import requests import tarfile from typing import Dict, List, Tuple _UT1_BLACKLIST_URL = "http://dsi.ut-capitole.fr" \ "/blacklists/download/blacklists.tar.gz"...
r""" update the URL blacklists from the University of Toulouse: @param artifacts_dir: (Path) The path to the resources directory @param raw_categories: (List[str]) The domain categories
141,025
import argparse from collections import defaultdict import itertools import json from pathlib import Path import time import urllib.request import requests import tarfile from typing import Dict, List, Tuple _LDNOOBW_URL = "https://raw.githubusercontent.com/LDNOOBW/List-of-Dirty-" \ "Naughty-Obscene-and-...
r""" Fetch the LDNOOBW word list Args: artifacts_dir (Path): The path to the resources directory lang (str): The language to fetch the word list for
141,026
import functools import multiprocessing as mp from multiprocessing.pool import Pool import numpy as np from pathlib import Path from tqdm import tqdm from core.document import Document from utilities.io import Reader class Document: __slots__ = ( "_raw_content", "_normalized_content", "_raw_lines", ...
r""" Compute the hash features for a given text
141,027
import logging from logging.handlers import QueueHandler import multiprocessing as mp def worker_logger_configurer(queue: mp.Queue, level=logging.DEBUG): root = logging.getLogger() if not root.hasHandlers(): h = logging.handlers.QueueHandler(queue) root.addHandler(h) root.setLevel(level)
null
141,028
import logging from logging.handlers import QueueHandler import multiprocessing as mp LOG_FMT = '[%(asctime)s]::(PID %(process)d)::%(levelname)-2s::%(message)s' def listener_logger_configurer(logfile, level=logging.DEBUG): root = logging.getLogger() formatter = logging.Formatter(LOG_FMT) # write to log fi...
null
141,029
import random import string TRANSLATION_TABLE = str.maketrans( string.ascii_lowercase + string.ascii_uppercase + "\n", string.ascii_lowercase * 2 + " ", string.punctuation ) The provided code snippet includes necessary dependencies for implementing the `normalize_text` function. Write a Python function `de...
r""" Normalize text by lowercasing and removing punctuation; if max words is larger than 0, then a random but contiguous span of max_words is selected from the text. Args: text: text to normalize max_words: maximum number of words to keep in text Returns: normalized text
141,030
import argparse import os from concurrent.futures import ProcessPoolExecutor, as_completed from collections import defaultdict from datetime import datetime as dt import gc import json import logging import multiprocessing as mp import numpy as np from pathlib import Path import random import re import time from typing...
null
141,031
import argparse import os from concurrent.futures import ProcessPoolExecutor, as_completed from collections import defaultdict from datetime import datetime as dt import gc import json import logging import multiprocessing as mp import numpy as np from pathlib import Path import random import re import time from typing...
null
141,032
import argparse import os from concurrent.futures import ProcessPoolExecutor, as_completed from collections import defaultdict from datetime import datetime as dt import gc import json import logging import multiprocessing as mp import numpy as np from pathlib import Path import random import re import time from typing...
null
141,033
import argparse import logging from datetime import datetime as dt import os from pathlib import Path from artifacts.downloaders import ( WikipediaDownloader, OpenWebTextDownloader, BooksDownloader, CCNetDownloader ) from artifacts.hash_dist import HashDist from artifacts.ft_trainer import FastTextTrain...
null
141,034
from scipy.integrate import quad as integrate import hashlib import numpy as np import struct from typing import Iterable, List from utilities.text import form_ngrams def _false_positive_probability(threshold, b, r): def proba(s): return 1 - (1 - s ** float(r)) ** float(b) a, *_ = integrate(proba, 0.0, ...
r""" Compute the optimal `MinHashLSH` parameter that minimizes the weighted sum of probabilities of false positive and false negative.
141,035
from scipy.integrate import quad as integrate import hashlib import numpy as np import struct from typing import Iterable, List from utilities.text import form_ngrams def sha1_hash32(data: bytes) -> int: """ A 32-bit hash function based on SHA1. Note: This implementation is copied from datasketch to...
r""" Combined with some datasketch code to better parallelize computation. Note: This implementation is adapted from the near-dedupe implementation by the bigcode project. Parameters ---------- words_sequence : str A sequence of (normalized) words for which to generate a signature. ngram_size : int The size of n-grams....
141,036
import datetime from os import path import math import git import random import numpy as np import torch from torch.utils.data import DataLoader, ConcatDataset import torch.distributed as distributed from model.trainer import XMemTrainer from dataset.static_dataset import StaticTransformDataset from dataset.vos_dataset...
null
141,037
import datetime from os import path import math import git import random import numpy as np import torch from torch.utils.data import DataLoader, ConcatDataset import torch.distributed as distributed from model.trainer import XMemTrainer from dataset.static_dataset import StaticTransformDataset from dataset.vos_dataset...
null
141,038
from PySide6.QtCore import Qt from PySide6.QtWidgets import (QBoxLayout, QHBoxLayout, QLabel, QSpinBox, QVBoxLayout, QProgressBar) def create_parameter_box(min_val, max_val, text, step=1, callback=None): layout = QHBoxLayout() dial = QSpinBox() dial.setMaximumHeight(28) dial.setMaximumWidth(150) d...
null
141,039
from PySide6.QtCore import Qt from PySide6.QtWidgets import (QBoxLayout, QHBoxLayout, QLabel, QSpinBox, QVBoxLayout, QProgressBar) def create_gauge(text): layout = QHBoxLayout() gauge = QProgressBar() gauge.setMaximumHeight(28) gauge.setMaximumWidth(200) gauge.setAlignment(Qt.AlignmentFlag.AlignCe...
null
141,040
from PySide6.QtCore import Qt from PySide6.QtWidgets import (QBoxLayout, QHBoxLayout, QLabel, QSpinBox, QVBoxLayout, QProgressBar) def apply_to_all_children_widget(layout, func): # deliberately non-recursive for i in range(layout.count()): func(layout.itemAt(i).widget())
null
141,041
import numpy as np import torch import torch.nn.functional as F from util.palette import davis_palette from dataset.range_transform import im_normalization try: if torch.cuda.is_available(): device = torch.device("cuda") elif torch.backends.mps.is_available(): device = torch.device("mps") el...
null
141,042
import numpy as np import torch import torch.nn.functional as F from util.palette import davis_palette from dataset.range_transform import im_normalization try: if torch.cuda.is_available(): device = torch.device("cuda") elif torch.backends.mps.is_available(): device = torch.device("mps") el...
null
141,043
import numpy as np import torch import torch.nn.functional as F from util.palette import davis_palette from dataset.range_transform import im_normalization try: if torch.cuda.is_available(): device = torch.device("cuda") elif torch.backends.mps.is_available(): device = torch.device("mps") el...
null
141,044
import numpy as np import torch import torch.nn.functional as F from util.palette import davis_palette from dataset.range_transform import im_normalization def overlay_davis(image, mask, alpha=0.5, fade=False): """ Overlay segmentation on top of RGB image. from davis official""" im_overlay = image.copy() co...
null
141,045
import numpy as np import torch import torch.nn.functional as F from util.palette import davis_palette from dataset.range_transform import im_normalization def overlay_davis_torch(image, mask, alpha=0.5, fade=False): """ Overlay segmentation on top of RGB image. from davis official""" # Changes the image in-pla...
null
141,046
import torch import torch.nn.functional as F import numpy as np import cv2 import time from .interactive_utils import color_map, index_numpy_to_one_hot_torch def aggregate_sbg(prob, keep_bg=False, hard=False): device = prob.device k, h, w = prob.shape ex_prob = torch.zeros((k+1, h, w), device=device) e...
null
141,047
import torch import torch.nn.functional as F import numpy as np import cv2 import time from .interactive_utils import color_map, index_numpy_to_one_hot_torch def aggregate_wbg(prob, keep_bg=False, hard=False): k, h, w = prob.shape new_prob = torch.cat([ torch.prod(1-prob, dim=0, keepdim=True), ...
null
141,048
from datetime import timedelta from pathlib import Path import torch import numpy as np from ..model.is_deeplab_model import get_deeplab_model from ..model.is_hrnet_model import get_hrnet_model def get_time_metrics(all_ious, elapsed_time): n_images = len(all_ious) n_clicks = sum(map(len, all_ious)) mean_s...
null
141,049
from datetime import timedelta from pathlib import Path import torch import numpy as np from ..model.is_deeplab_model import get_deeplab_model from ..model.is_hrnet_model import get_hrnet_model def load_hrnet_is_model(state_dict, device, backbone='auto', width=48, ocr_width=256, small=False, cpu...
null
141,050
from datetime import timedelta from pathlib import Path import torch import numpy as np from ..model.is_deeplab_model import get_deeplab_model from ..model.is_hrnet_model import get_hrnet_model def compute_noc_metric(all_ious, iou_thrs, max_clicks=20): def _get_noc(iou_arr, iou_thr): vals = iou_arr >= iou_...
null
141,051
from datetime import timedelta from pathlib import Path import torch import numpy as np from ..model.is_deeplab_model import get_deeplab_model from ..model.is_hrnet_model import get_hrnet_model def find_checkpoint(weights_folder, checkpoint_name): weights_folder = Path(weights_folder) if ':' in checkpoint_name...
null
141,052
from datetime import timedelta from pathlib import Path import torch import numpy as np from ..model.is_deeplab_model import get_deeplab_model from ..model.is_hrnet_model import get_hrnet_model def get_results_table(noc_list, over_max_list, brs_type, dataset_name, mean_spc, elapsed_time, n_clicks...
null
141,053
from time import time import numpy as np import torch from ..inference import utils from ..inference.clicker import Clicker def evaluate_sample(image_nd, instances_mask, predictor, max_iou_thr, pred_thr=0.49, max_clicks=20): clicker = Clicker(gt_mask=instances_mask) pred_mask = np.zeros_like...
null
141,054
import math import torch import numpy as np from ...inference.clicker import Click from .base import BaseTransform def get_offsets(length, crop_size, min_overlap_ratio=0.2): if length == crop_size: return [0] N = (length / crop_size - min_overlap_ratio) / (1 - min_overlap_ratio) N = math.ceil(N) ...
null
141,055
import torch from ..clicker import Click from ...utils.misc import get_bbox_iou, get_bbox_from_mask, expand_bbox, clamp_bbox from .base import BaseTransform def get_bbox_from_mask(mask): rows = np.any(mask, axis=1) cols = np.any(mask, axis=0) rmin, rmax = np.where(rows)[0][[0, -1]] cmin, cmax = np.wher...
null
141,056
import torch from ..clicker import Click from ...utils.misc import get_bbox_iou, get_bbox_from_mask, expand_bbox, clamp_bbox from .base import BaseTransform def get_roi_image_nd(image_nd, object_roi, target_size): rmin, rmax, cmin, cmax = object_roi height = rmax - rmin + 1 width = cmax - cmin + 1 if...
null
141,057
import torch from ..clicker import Click from ...utils.misc import get_bbox_iou, get_bbox_from_mask, expand_bbox, clamp_bbox from .base import BaseTransform def check_object_roi(object_roi, clicks_list): for click in clicks_list: if click.is_positive: if click.coords[0] < object_roi[0] or click...
null
141,058
from contextlib import ExitStack import torch from torch import nn import torch.nn.functional as F from .basic_blocks import SeparableConv2d from .resnet import ResNetBackbone from ...model import ops def _ASPPConv(in_channels, out_channels, atrous_rate, norm_layer): block = nn.Sequential( nn.Conv2d(in_cha...
null
141,059
import torch import torch.nn as nn GLUON_RESNET_TORCH_HUB = 'rwightman/pytorch-pretrained-gluonresnet' class BasicBlockV1b(nn.Module): def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=nn.BatchNorm2d): def forward(self, x): class R...
null
141,060
import torch import torch.nn as nn GLUON_RESNET_TORCH_HUB = 'rwightman/pytorch-pretrained-gluonresnet' class BottleneckV1b(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=nn.BatchNorm2d): super(Bottlen...
null
141,061
import torch import torch.nn as nn GLUON_RESNET_TORCH_HUB = 'rwightman/pytorch-pretrained-gluonresnet' class BottleneckV1b(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=nn.BatchNorm2d): super(Bottlen...
null
141,062
import torch import torch.nn as nn GLUON_RESNET_TORCH_HUB = 'rwightman/pytorch-pretrained-gluonresnet' class BottleneckV1b(nn.Module): def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=nn.BatchNorm2d): def forward(self, x): class R...
null
141,063
import torch from torch import nn as nn import numpy as np from . import initializer as initializer from ..utils.cython import get_dist_maps def select_activation_function(activation): if isinstance(activation, str): if activation.lower() == 'relu': return nn.ReLU elif activation.lower(...
null
141,064
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.cuda.comm as comm from torch.autograd import Function from torch.autograd.function import once_differentiable from ._csrc import _backend def _count_samples(x): count = 1 for i, s in enumer...
null
141,065
from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os.path import torch try: from torch.utils.cpp_extension import load from torch.utils.cpp_extension import CUDA_HOME except ImportError: raise ImportError( "The cpp layer e...
null
141,066
import torch import numpy as np from ..utils import misc def _compute_iou(pred_mask, gt_mask, ignore_mask=None, keep_ignore=False): if ignore_mask is not None: pred_mask = torch.where(ignore_mask, torch.zeros_like(pred_mask), pred_mask) reduction_dims = misc.get_dims_with_exclusion(gt_mask.dim(), 0) ...
null
141,067
from functools import partial import torch import numpy as np def get_unique_labels(mask): return np.nonzero(np.bincount(mask.flatten() + 1))[0] - 1
null
141,068
from functools import partial import torch import numpy as np def get_segments_iou(s1, s2): a, b = s1 c, d = s2 intersection = max(0, min(b, d) - max(a, c) + 1) union = max(1e-6, max(b, d) - min(a, c) + 1) return intersection / union def get_bbox_iou(b1, b2): h_iou = get_segments_iou(b1[:2], b2...
null
141,069
from functools import lru_cache import cv2 import numpy as np def get_palette(num_cls): palette = np.zeros(3 * num_cls, dtype=np.int32) for j in range(0, num_cls): lab = j i = 0 while lab > 0: palette[j*3 + 0] |= (((lab >> 0) & 1) << (7-i)) palette[j*3 + 1] |= (((...
null
141,070
from functools import lru_cache import cv2 import numpy as np def get_palette(num_cls): palette = np.zeros(3 * num_cls, dtype=np.int32) for j in range(0, num_cls): lab = j i = 0 while lab > 0: palette[j*3 + 0] |= (((lab >> 0) & 1) << (7-i)) palette[j*3 + 1] |= (((...
null
141,071
from functools import lru_cache import cv2 import numpy as np def draw_probmap(x): def visualize_proposals(proposals_info, point_color=(255, 0, 0), point_radius=1): proposal_map, colors, candidates = proposals_info proposal_map = draw_probmap(proposal_map) for x, y in candidates: proposal_map = cv...
null
141,072
from functools import lru_cache import cv2 import numpy as np def draw_instance_map(x, palette=None): def blend_mask(image, mask, alpha=0.6): if mask.min() == -1: mask = mask.copy() + 1 imap = draw_instance_map(mask) result = (image * (1 - alpha) + alpha * imap).astype(np.uint8) return result
null
141,073
from functools import lru_cache import cv2 import numpy as np def get_palette(num_cls): palette = np.zeros(3 * num_cls, dtype=np.int32) for j in range(0, num_cls): lab = j i = 0 while lab > 0: palette[j*3 + 0] |= (((lab >> 0) & 1) << (7-i)) palette[j*3 + 1] |= (((...
null
141,074
import torch from torch import nn from torch.nn import functional as F from .utils import _SimpleSegmentationModel class AtrousSeparableConvolution(nn.Module): """ Atrous Separable Convolution """ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dil...
null
141,075
from .utils import IntermediateLayerGetter from ._deeplab import DeepLabHead, DeepLabHeadV3Plus, DeepLabV3 from . import s2m_resnet def _load_model(arch_type, backbone, num_classes, output_stride, pretrained_backbone): if backbone.startswith('resnet'): model = _segm_resnet(arch_type, backbone, num_classes, ...
Constructs a DeepLabV3 model with a ResNet-50 backbone. Args: num_classes (int): number of classes. output_stride (int): output stride for deeplab. pretrained_backbone (bool): If True, use the pretrained backbone.
141,076
from .utils import IntermediateLayerGetter from ._deeplab import DeepLabHead, DeepLabHeadV3Plus, DeepLabV3 from . import s2m_resnet def _load_model(arch_type, backbone, num_classes, output_stride, pretrained_backbone): if backbone.startswith('resnet'): model = _segm_resnet(arch_type, backbone, num_classes, ...
Constructs a DeepLabV3 model with a ResNet-50 backbone. Args: num_classes (int): number of classes. output_stride (int): output stride for deeplab. pretrained_backbone (bool): If True, use the pretrained backbone.
141,079
import torch import torch.nn as nn class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer =...
r"""ResNet-50 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
141,080
import numpy as np def all_to_onehot(masks, labels): if len(masks.shape) == 3: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8) else: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8) for ni, l in enumerate(labels): ...
null
141,081
import numpy as np from PIL import Image import cv2 import thinplate as tps def pick_random_points(h, w, n_samples): y_idx = np.random.choice(np.arange(h), size=n_samples, replace=False) x_idx = np.random.choice(np.arange(w), size=n_samples, replace=False) return y_idx/h, x_idx/w def warp_dual_cv(img, mask,...
Apply a random TPS warp of the input image and mask Uses randomness from numpy
141,082
import torch import random def reseed(seed): random.seed(seed) torch.manual_seed(seed)
null
141,083
import sys import os from os import path from PIL import Image import numpy as np from progressbar import progressbar from multiprocessing import Pool def resize_vid_jpeg(inputs): vid_name, folder_path, out_path = inputs vid_path = path.join(folder_path, vid_name) vid_out_path = path.join(out_path, 'JPEGIma...
null
141,084
import os from os import path from argparse import ArgumentParser import glob from collections import defaultdict import numpy as np import hickle as hkl from PIL import Image, ImagePalette from progressbar import progressbar from multiprocessing import Pool from util import palette from util.palette import davis_palet...
null
141,087
import torch import torch.nn as nn import torch.nn.functional as F def interpolate_groups(g, ratio, mode, align_corners): batch_size, num_objects = g.shape[:2] g = F.interpolate(g.flatten(start_dim=0, end_dim=1), scale_factor=ratio, mode=mode, align_corners=align_corners) g = g.view(batch_s...
null
141,094
import torch.nn.functional as F def compute_tensor_iu(seg, gt): intersection = (seg & gt).float().sum() union = (seg | gt).float().sum() return intersection, union def compute_tensor_iou(seg, gt): intersection, union = compute_tensor_iu(seg, gt) iou = (intersection + 1e-6) / (union + 1e-6) ...
null
141,097
import cv2 import numpy as np import torch from dataset.range_transform import inv_im_trans from collections import defaultdict def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): return x.detach().cpu() def transpose_np(x): return np.transp...
null
141,098
import cv2 import numpy as np import torch from dataset.range_transform import inv_im_trans from collections import defaultdict def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np def detach_to_cpu(x): return x.detach().cpu() def transpose_np(x): return np.transp...
null
141,099
import cv2 import numpy as np import torch from dataset.range_transform import inv_im_trans from collections import defaultdict def detach_to_cpu(x): return x.detach().cpu() def base_transform(im, size): im = tensor_to_np_float(im) if len(im.shape) == 3: im = im.transpose((1, 2, 0)) ...
null
141,100
import cv2 import numpy as np import torch from dataset.range_transform import inv_im_trans from collections import defaultdict key_captions = { 'im': 'Image', 'gt': 'GT', } def get_image_array(images, grid_shape, captions={}): def im_transform(im, size): def mask_transform(mask, size): def pool_pairs(images...
null
141,101
import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def tensor_to_numpy(image): image_np = (image.numpy() * 255).astype('uint8') return image_np
null
141,102
import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def detach_to_cpu(x): return x.detach().cpu()
null
141,103
import os import warnings import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter def fix_width_trunc(x): return ('{:.9s}'.format('{:0.9f}'.format(x)))
null
141,104
from argparse import ArgumentParser def none_or_default(x, default): return x if x is not None else default
null
141,105
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 def on_command_(cmd: Union[str, Tuple[str, ...]], state: dict = None, *ar...
null
141,106
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 def on_endswith_(msg: Union[str, Tuple[str, ...]], state: dict = None, *a...
null
141,107
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 def on_startswith_(msg: Union[str, Tuple[str, ...]], state: dict = None, ...
null
141,108
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 def on_regex_(pattern: str, state: dict = None, *args, **kwargs): if ...
null
141,109
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 def on_keyword_(keywords: Set[str], state: dict = None, *args, **kwargs):...
null
141,110
import re from typing import Union, Tuple, Set from nonebot import on_command, on_regex, on_endswith, on_keyword, on_startswith import nonebot from nonebot.adapters.onebot.v11 import MessageEvent, Bot, log from nonebot.adapters.onebot import v11 The provided code snippet includes necessary dependencies for implementin...
检查消息开头是否存在昵称,去除并赋值 `event.to_me`。 参数: bot: Bot 对象 event: MessageEvent 对象
141,111
import asyncio import contextlib import datetime import os import sys from pathlib import Path from fastapi import APIRouter from fastapi.responses import JSONResponse from nonebot import get_bot, get_app from nonebot.adapters.onebot.v11 import Bot from LittlePaimon.utils import SUPERUSERS from LittlePaimon.utils.files...
null