repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
MockingBird | models/vocoder/wavernn/gen_wavernn.py | .py | from models.vocoder.wavernn.models.fatchord_version import WaveRNN
from models.vocoder.wavernn.audio import *
def gen_testset(model: WaveRNN, test_set, samples, batched, target, overlap, save_path):
k = model.get_step() // 1000
for i, (m, x) in enumerate(test_set, 1):
if i > samples:
br... | 32 | 1,015 |
MockingBird | models/vocoder/wavernn/train.py | .py | from models.vocoder.wavernn.models.fatchord_version import WaveRNN
from models.vocoder.vocoder_dataset import VocoderDataset, collate_vocoder
from models.vocoder.distribution import discretized_mix_logistic_loss
from models.vocoder.display import stream, simple_table
from models.vocoder.wavernn.gen_wavernn import gen_t... | 128 | 4,706 |
MockingBird | models/vocoder/wavernn/audio.py | .py | import math
import numpy as np
import librosa
import models.vocoder.wavernn.hparams as hp
from scipy.signal import lfilter
import soundfile as sf
def label_2_float(x, bits) :
return 2 * x / (2**bits - 1.) - 1.
def float_2_label(x, bits) :
assert abs(x).max() <= 1.0
x = (x + 1.) * (2**bits - 1) / 2
r... | 109 | 2,239 |
MockingBird | models/vocoder/wavernn/hparams.py | .py | from models.synthesizer.hparams import hparams as _syn_hp
# Audio settings------------------------------------------------------------------------
# Match the values of the synthesizer
sample_rate = _syn_hp.sample_rate
n_fft = _syn_hp.n_fft
num_mels = _syn_hp.num_mels
hop_length = _syn_hp.hop_size
win_length = _syn_h... | 45 | 1,829 |
MockingBird | models/vocoder/wavernn/models/deepmind_version.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.display import *
from utils.dsp import *
class WaveRNN(nn.Module) :
def __init__(self, hidden_size=896, quantisation=256) :
super(WaveRNN, self).__init__()
self.hidden_size = hidden_size
self.split_size ... | 170 | 7,030 |
MockingBird | models/vocoder/wavernn/models/fatchord_version.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.vocoder.distribution import sample_from_discretized_mix_logistic
from models.vocoder.display import *
from models.vocoder.wavernn.audio import *
class ResBlock(nn.Module):
def __init__(self, dims):
super().__init__()
se... | 435 | 15,328 |
MockingBird | models/vocoder/hifigan/inference.py | .py | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import json
import torch
from utils.util import AttrDict
from models.vocoder.hifigan.models import Generator
generator = None # type: Generator
output_sample_rate = None
_device = None
def load_checkpoint(filepat... | 75 | 1,983 |
MockingBird | models/vocoder/hifigan/utils.py | .py | import glob
import os
import matplotlib
import torch
from torch.nn.utils import weight_norm
matplotlib.use("Agg")
import matplotlib.pylab as plt
def plot_spectrogram(spectrogram):
fig, ax = plt.subplots(figsize=(10, 2))
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
interpolation... | 51 | 1,220 |
MockingBird | models/vocoder/hifigan/models.py | .py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from utils.util import init_weights, get_padding
LRELU_SLOPE = 0.1
class ResBlock1(torch.nn.Module):
def __i... | 286 | 10,807 |
MockingBird | models/vocoder/hifigan/train.py | .py | import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import itertools
import os
import time
import argparse
import json
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DistributedSampler, DataLoader
import torch.multip... | 255 | 12,014 |
MockingBird | models/vocoder/hifigan/meldataset.py | .py | import math
import os
import random
import torch
import torch.utils.data
import numpy as np
from librosa.util import normalize
from scipy.io.wavfile import read
from utils.audio_utils import mel_spectrogram
MAX_WAV_VALUE = 32768.0
def load_wav(full_path):
sampling_rate, data = read(full_path)
return data, sa... | 139 | 5,410 |
MockingBird | models/vocoder/hifigan/env.py | .py | import os
import shutil
def build_env(config, config_name, path):
t_path = os.path.join(path, config_name)
if config != t_path:
os.makedirs(path, exist_ok=True)
shutil.copyfile(config, os.path.join(path, config_name))
| 9 | 243 |
MockingBird | models/vocoder/fregan/inference.py | .py | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import json
import torch
from utils.util import AttrDict
from models.vocoder.fregan.generator import FreGAN
generator = None # type: FreGAN
output_sample_rate = None
_device = None
def load_checkpoint(filepath, device... | 75 | 1,963 |
MockingBird | models/vocoder/fregan/stft_loss.py | .py | # -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# MIT License (https://opensource.org/licenses/MIT)
"""STFT-based Loss modules."""
import torch
import torch.nn.functional as F
def stft(x, fft_size, hop_size, win_length, window):
"""Perform STFT and convert to magnitude spectrogram.
Args:
x... | 136 | 4,948 |
MockingBird | models/vocoder/fregan/utils.py | .py | import glob
import os
import matplotlib
import torch
from torch.nn.utils import weight_norm
matplotlib.use("Agg")
import matplotlib.pylab as plt
import shutil
def build_env(config, config_name, path):
t_path = os.path.join(path, config_name)
if config != t_path:
os.makedirs(path, exist_ok=True)
... | 56 | 1,359 |
MockingBird | models/vocoder/fregan/train.py | .py | import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import itertools
import os
import time
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DistributedSampler, DataLoader
from torch.distributed import init_process_gro... | 247 | 11,406 |
MockingBird | models/vocoder/fregan/modules.py | .py | import torch
import torch.nn.functional as F
class KernelPredictor(torch.nn.Module):
''' Kernel predictor for the location-variable convolutions
'''
def __init__(self,
cond_channels,
conv_in_channels,
conv_out_channels,
conv_layers,
... | 202 | 9,014 |
MockingBird | models/vocoder/fregan/generator.py | .py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from utils.util import init_weights, get_padding
LRELU_SLOPE = 0.1
class ResBlock1(torch.nn.Module):
def __i... | 210 | 8,166 |
MockingBird | models/vocoder/fregan/meldataset.py | .py | import math
import os
import random
import torch
import torch.utils.data
import numpy as np
from librosa.util import normalize
from scipy.io.wavfile import read
from utils.audio_utils import mel_spectrogram
MAX_WAV_VALUE = 32768.0
def load_wav(full_path):
sampling_rate, data = read(full_path)
return data, sa... | 120 | 5,016 |
MockingBird | models/vocoder/fregan/discriminator.py | .py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, spectral_norm
from models.vocoder.fregan.utils import get_padding
from models.vocoder.fregan.stft_loss import stft
from models.vocoder.fregan.dwt import DWT_1D
LRELU_... | 303 | 11,190 |
MockingBird | models/vocoder/fregan/dwt.py | .py | # Copyright (c) 2019, Adobe Inc. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
# 4.0 International Public License. To view a copy of this license, visit
# https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.
# DWT code borrow from https://github.... | 77 | 3,382 |
MockingBird | models/ppg2mel/preprocess.py | .py |
import os
import torch
import numpy as np
from tqdm import tqdm
from pathlib import Path
import soundfile
import resampy
from models.ppg_extractor import load_model
import encoder.inference as Encoder
from models.encoder.audio import preprocess_wav
from models.encoder import audio
from utils.f0_utils import compute_f... | 114 | 4,591 |
MockingBird | models/ppg2mel/rnn_decoder_mol.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .utils.mol_attention import MOLAttention
from .utils.basic_layers import Linear
from .utils.vc_utils import get_mask_from_lengths
class DecoderPrenet(nn.Module):
def __init__(self, in_dim, sizes):
super().__init__()... | 375 | 14,653 |
MockingBird | models/ppg2mel/train.py | .py | import sys
import torch
import argparse
import numpy as np
from utils.hparams import HpsYaml
from models.ppg2mel.train.train_linglf02mel_seq2seq_oneshotvc import Solver
# For reproducibility, comment these may speed up training
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def main(... | 63 | 2,579 |
MockingBird | models/ppg2mel/__init__.py | .py | #!/usr/bin/env python3
# Copyright 2020 Songxiang Liu
# Apache 2.0
from typing import List
import torch
import torch.nn.functional as F
import numpy as np
from .utils.abs_model import AbsMelDecoder
from .rnn_decoder_mol import Decoder
from .utils.cnn_postnet import Postnet
from .utils.vc_utils import get_mask_from... | 210 | 7,944 |
MockingBird | models/ppg2mel/train/option.py | .py | # Default parameters which will be imported by solver
default_hparas = {
'GRAD_CLIP': 5.0, # Grad. clip threshold
'PROGRESS_STEP': 100, # Std. output refresh freq.
# Decode steps for objective validation (step = ratio*input_txt_len)
'DEV_STEP_RATIO': 1.2,
# Number of examples (alignmen... | 11 | 449 |
MockingBird | models/ppg2mel/train/optim.py | .py | import torch
import numpy as np
class Optimizer():
def __init__(self, parameters, optimizer, lr, eps, lr_scheduler,
**kwargs):
# Setup torch optimizer
self.opt_type = optimizer
self.init_lr = lr
self.sch_type = lr_scheduler
opt = getattr(torch.optim, optim... | 46 | 1,438 |
MockingBird | models/ppg2mel/train/train_linglf02mel_seq2seq_oneshotvc.py | .py | import os, sys
# sys.path.append('/home/shaunxliu/projects/nnsp')
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import torch
from torch.utils.data import DataLoader
import numpy as np
from .solver import BaseSolver
from utils.data_load import OneshotVc... | 289 | 11,410 |
MockingBird | models/ppg2mel/train/solver.py | .py | import os
import sys
import abc
import math
import yaml
import torch
from torch.utils.tensorboard import SummaryWriter
from .option import default_hparas
from utils.util import human_format, Timer
class BaseSolver():
'''
Prototype Solver for all kinds of tasks
Arguments
config - yaml-styled conf... | 217 | 8,418 |
MockingBird | models/ppg2mel/train/loss.py | .py | from typing import Dict
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..utils.nets_utils import make_pad_mask
class MaskedMSELoss(nn.Module):
def __init__(self, frames_per_step):
super().__init__()
self.frames_per_step = frames_per_step
... | 51 | 2,029 |
MockingBird | models/ppg2mel/utils/basic_layers.py | .py | import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Function
def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
"""
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(pe... | 80 | 2,444 |
MockingBird | models/ppg2mel/utils/nets_utils.py | .py | # -*- coding: utf-8 -*-
"""Network related utility tools."""
import logging
from typing import Dict
import numpy as np
import torch
def to_device(m, x):
"""Send tensor into the device of the module.
Args:
m (torch.nn.Module): Torch module.
x (Tensor): Torch tensor.
Returns:
Te... | 452 | 15,567 |
MockingBird | models/ppg2mel/utils/abs_model.py | .py | from abc import ABC
from abc import abstractmethod
import torch
class AbsMelDecoder(torch.nn.Module, ABC):
"""The abstract PPG-based voice conversion class
This "model" is one of mediator objects for "Task" class.
"""
@abstractmethod
def forward(
self,
bottle_neck_features: torc... | 24 | 610 |
MockingBird | models/ppg2mel/utils/vc_utils.py | .py | import torch
def gcd(a, b):
"""Greatest common divisor."""
a, b = (a, b) if a >=b else (b, a)
if a%b == 0:
return b
else :
return gcd(b, a%b)
def lcm(a, b):
"""Least common multiple"""
return a * b // gcd(a, b)
def get_mask_from_lengths(lengths, max_len=None):
if... | 23 | 517 |
MockingBird | models/ppg2mel/utils/cnn_postnet.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .basic_layers import Linear, Conv1d
class Postnet(nn.Module):
"""Postnet
- Five 1-d convolution with 512 channels and kernel size 5
"""
def __init__(self, num_mels=80,
num_layers=5,
hidden_dim... | 53 | 1,836 |
MockingBird | models/ppg2mel/utils/mol_attention.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
class MOLAttention(nn.Module):
""" Discretized Mixture of Logistic (MOL) attention.
C.f. Section 5 of "MelNet: A Generative Model for Audio in the Frequency Domain" and
GMMv2b model in "Location-relative attention mechanisms for robus... | 124 | 4,366 |
MockingBird | models/ppg_extractor/nets_utils.py | .py | # -*- coding: utf-8 -*-
"""Network related utility tools."""
import logging
from typing import Dict
import numpy as np
import torch
def to_device(m, x):
"""Send tensor into the device of the module.
Args:
m (torch.nn.Module): Torch module.
x (Tensor): Torch tensor.
Returns:
Te... | 466 | 15,900 |
MockingBird | models/ppg_extractor/e2e_asr_common.py | .py | #!/usr/bin/env python3
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Common functions for ASR."""
import argparse
import editdistance
import json
import logging
import numpy as np
import six
import sys
from itertools import groupby
def e... | 399 | 13,859 |
MockingBird | models/ppg_extractor/frontend.py | .py | import copy
from typing import Tuple
import numpy as np
import torch
from torch_complex.tensor import ComplexTensor
from .log_mel import LogMel
from .stft import Stft
class DefaultFrontend(torch.nn.Module):
"""Conventional frontend structure for ASR
Stft -> WPE -> MVDR-Beamformer -> Power-spec -> Mel-Fbank ... | 116 | 4,064 |
MockingBird | models/ppg_extractor/__init__.py | .py | import argparse
import torch
from pathlib import Path
import yaml
from .frontend import DefaultFrontend
from .utterance_mvn import UtteranceMVN
from .encoder.conformer_encoder import ConformerEncoder
_model = None # type: PPGModel
_device = None
class PPGModel(torch.nn.Module):
def __init__(
self,
... | 103 | 3,093 |
MockingBird | models/ppg_extractor/utterance_mvn.py | .py | from typing import Tuple
import torch
from .nets_utils import make_pad_mask
class UtteranceMVN(torch.nn.Module):
def __init__(
self, norm_means: bool = True, norm_vars: bool = False, eps: float = 1.0e-20,
):
super().__init__()
self.norm_means = norm_means
self.norm_vars = nor... | 83 | 2,140 |
MockingBird | models/ppg_extractor/encoders.py | .py | import logging
import six
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
from .e2e_asr_common import get_vgg2l_odim
from .nets_utils import make_pad_mask, to_device
class RNNP(torch.nn.Module):
... | 299 | 13,237 |
MockingBird | models/ppg_extractor/stft.py | .py | from typing import Optional
from typing import Tuple
from typing import Union
import torch
from .nets_utils import make_pad_mask
class Stft(torch.nn.Module):
def __init__(
self,
n_fft: int = 512,
win_length: Union[int, None] = 512,
hop_length: int = 128,
center: bool = Tr... | 119 | 3,939 |
MockingBird | models/ppg_extractor/log_mel.py | .py | import librosa
import numpy as np
import torch
from typing import Tuple
from .nets_utils import make_pad_mask
class LogMel(torch.nn.Module):
"""Convert STFT to fbank feats
The arguments is same as librosa.filters.mel
Args:
fs: number > 0 [scalar] sampling rate of the incoming signal
n_f... | 74 | 2,446 |
MockingBird | models/ppg_extractor/encoder/swish.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Johns Hopkins University (Shinji Watanabe)
# Northwestern Polytechnical University (Pengcheng Guo)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Swish() activation function for Conformer."""
import torch
class Swish(tor... | 19 | 483 |
MockingBird | models/ppg_extractor/encoder/conformer_encoder.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder definition."""
import logging
import torch
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import... | 263 | 10,087 |
MockingBird | models/ppg_extractor/encoder/attention.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Multi-Head Attention layer definition."""
import math
import numpy
import torch
from torch import nn
class MultiHeadedAttention(nn.Module):
"""Multi-Head Attention laye... | 184 | 7,103 |
MockingBird | models/ppg_extractor/encoder/convolution.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Johns Hopkins University (Shinji Watanabe)
# Northwestern Polytechnical University (Pengcheng Guo)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""ConvolutionModule definition."""
from torch import nn
class ConvolutionMod... | 75 | 2,108 |
MockingBird | models/ppg_extractor/encoder/multi_layer_conv.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Layer modules for FFT block in FastSpeech (Feed-forward Transformer)."""
import torch
class MultiLayeredConv1d(torch.nn.Module):
"""Multi-layered conv1d for Transformer ... | 106 | 3,148 |
MockingBird | models/ppg_extractor/encoder/encoder.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder definition."""
import logging
import torch
from espnet.nets.pytorch_backend.conformer.convolution import ConvolutionModule
from espnet.nets.pytorch_backend.conformer.... | 218 | 8,765 |
MockingBird | models/ppg_extractor/encoder/positionwise_feed_forward.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Positionwise feed forward layer definition."""
import torch
class PositionwiseFeedForward(torch.nn.Module):
"""Positionwise feed forward layer.
:param int idim: inp... | 32 | 969 |
MockingBird | models/ppg_extractor/encoder/layer_norm.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Layer normalization module."""
import torch
class LayerNorm(torch.nn.LayerNorm):
"""Layer normalization module.
:param int nout: output dim size
:param int dim:... | 34 | 874 |
MockingBird | models/ppg_extractor/encoder/encoder_layer.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder self-attention layer definition."""
import torch
from torch import nn
from .layer_norm import LayerNorm
class EncoderLayer(nn.Module):
... | 153 | 5,297 |
MockingBird | models/ppg_extractor/encoder/embedding.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Positonal Encoding Module."""
import math
import torch
def _pre_hook(
state_dict,
prefix,
local_metadata,
strict,
missing_keys,
unexpected_keys,
... | 167 | 4,847 |
MockingBird | models/ppg_extractor/encoder/subsampling.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Subsampling layer definition."""
import logging
import torch
from espnet.nets.pytorch_backend.transformer.embedding import PositionalEncoding
class Conv2dSubsampling(torch.n... | 219 | 7,216 |
MockingBird | models/ppg_extractor/encoder/repeat.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Repeat the same layer definition."""
import torch
class MultiSequential(torch.nn.Sequential):
"""Multi-input multi-output torch.nn.Sequential."""
def forward(self, ... | 31 | 676 |
MockingBird | models/ppg_extractor/encoder/vgg.py | .py | """VGG2L definition for transformer-transducer."""
import torch
class VGG2L(torch.nn.Module):
"""VGG2L module for transformer-transducer encoder."""
def __init__(self, idim, odim):
"""Construct a VGG2L object.
Args:
idim (int): dimension of inputs
odim (int): dimensi... | 78 | 2,111 |
MockingBird | archived_untest_files/demo_cli.py | .py | from models.encoder.params_model import model_embedding_size as speaker_embedding_size
from utils.argutils import print_args
from utils.modelutils import check_model_paths
from models.synthesizer.inference import Synthesizer
from models.encoder import inference as encoder
from models.vocoder import inference as vocoder... | 226 | 10,836 |
maigret | wizard.py | .py | import asyncio
import logging
import maigret
TOP_SITES_COUNT = 300
TIMEOUT = 10
MAX_CONNECTIONS = 50
def main():
logger = logging.getLogger('maigret')
logger.setLevel(logging.WARNING)
loop = asyncio.get_event_loop()
db = maigret.MaigretDatabase().load_from_file('./maigret/resources/data.json')
... | 69 | 1,791 |
maigret | docs/source/conf.py | .py | # Configuration file for the Sphinx documentation builder.
import os
# -- Project information
project = 'Maigret'
copyright = '2025, soxoj'
author = 'soxoj'
release = '0.6.4'
version = '0.6'
# -- Internationalization
#
# Default to English. Translation projects on Read the Docs set the
# ``READTHEDOCS_LANGUAGE`` e... | 51 | 1,170 |
maigret | tests/test_executors.py | .py | """Maigret checking logic test functions"""
import pytest
import asyncio
import logging
import time
from typing import List, Tuple, Callable
from maigret.executors import AsyncioQueueGeneratorExecutor
logger = logging.getLogger(__name__)
async def func(n):
await asyncio.sleep(0.1 * (n % 3))
return n
async... | 91 | 3,554 |
maigret | tests/test_report.py | .py | """Maigret reports test functions"""
import copy
import json
import os
import subprocess
import sys
import textwrap
import zipfile
import pytest
from io import StringIO
from xml.etree import ElementTree
import xmind # type: ignore[import-untyped]
from jinja2 import Template
from markupsafe import escape
from maigre... | 1,170 | 39,692 |
maigret | tests/test_settings.py | .py | import unittest
from unittest.mock import patch, mock_open
from maigret.settings import Settings
class TestSettings(unittest.TestCase):
@patch('json.load')
@patch('builtins.open', new_callable=mock_open)
def test_settings_cascade_and_override(self, mock_file, mock_json_load):
file1_data = {"timeo... | 54 | 1,884 |
maigret | tests/test_workflows.py | .py | """Guards for the release-publishing GitHub Actions workflow.
Regression tests for #2959. The PyInstaller development build used to publish
itself with ``makeLatest: true`` under a tag named after the branch it was built
from, which caused three separate problems:
1. the Windows dev build held the repository's "Lates... | 97 | 3,644 |
maigret | tests/test_standalone_wrapper.py | .py | """Unit tests for the PyInstaller Windows wrapper.
The wrapper at ``pyinstaller/maigret_standalone.py`` lives outside the
``maigret`` package, so we load it by path.
"""
import importlib.util
import os
import sys
from unittest import mock
import pytest
WRAPPER_PATH = os.path.join(
os.path.dirname(os.path.dirnam... | 150 | 6,061 |
maigret | tests/test_errors.py | .py | import pytest
from maigret.checking import _is_dns_error
from maigret.errors import notify_about_errors, CheckError, solution_of, threshold_for, THRESHOLD
from maigret.result import MaigretCheckResult, MaigretCheckStatus
def test_notify_about_errors():
results = {
'site1': {
'status': MaigretC... | 337 | 13,599 |
maigret | tests/test_twitter.py | .py | """Tests for the Twitter / X site entry and GraphQL probe."""
import re
import pytest
import requests
from maigret.sites import MaigretSite
def _twitter_site(site: MaigretSite) -> None:
assert site.name == "Twitter"
assert site.disabled is False
assert site.check_type == "message"
assert site.url_p... | 64 | 2,168 |
maigret | tests/test_cloudflare_webgate.py | .py | """Tests for the Cloudflare webgate config + checker."""
import json
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from maigret.checking import (
CloudflareWebgateChecker,
build_cloudflare_bypass_config,
)
def _settings(payload):
return SimpleNamespace(cloudflare_bypass... | 304 | 11,858 |
maigret | tests/test_extractors.py | .py | """
Unit tests for username extraction helpers.
"""
from maigret.utils import extract_usernames
from maigret.maigret import extract_ids_from_page
from unittest.mock import Mock, patch
def test_extract_username():
logger = Mock()
result = extract_usernames(
{"profile_username": "emily"},
log... | 119 | 2,816 |
maigret | tests/test_keyword_filtering.py | .py | from unittest.mock import Mock
from maigret.errors import CheckError
from maigret.notify import QueryNotifyPrint
from maigret.result import MaigretCheckStatus, MaigretCheckResult, KeywordMatchStatus
from maigret.sites import MaigretSite
from maigret.checking import process_site_result
def test_keyword_match_status_e... | 191 | 7,382 |
maigret | tests/test_sanitize_username.py | .py | import pytest
from maigret.web.app import sanitize_username_for_path
@pytest.mark.parametrize(
"input_username, expected",
[
("../../tmp/x", "_.._tmp_x"),
("..", "_"),
("....", "_"),
("foo/bar", "foo_bar"),
("\0foo", "_foo"),
("normaluser123", "normaluser123"),... | 29 | 793 |
maigret | tests/test_country_tags.py | .py | """Country-tag hygiene tests for maigret/resources/data.json.
Country tags are 2-letter codes (see maigret.utils.is_country_tag). These tests
keep them honest: every one must be an officially assigned ISO 3166-1 alpha-2
code, the reserved 'uk'/'eu' must not sneak in (use 'gb' / a real country), and
a handful of domain... | 68 | 2,918 |
maigret | tests/test_web.py | .py | """Smoke tests for the Flask web interface in maigret.web.app.
The goal is to catch breakage in the basic user flow (render index, kick off
search, redirect to results) without making real network calls. Heavy maigret
internals are mocked; the report-generation smoke test keeps `save_graph_report`
unmocked so regressi... | 822 | 31,657 |
maigret | tests/test_db_updater.py | .py | """Tests for the database auto-update system."""
import json
import os
import hashlib
from datetime import datetime, timezone, timedelta
from unittest.mock import patch, MagicMock
import pytest
from maigret.db_updater import (
_parse_version,
_needs_check,
_is_version_compatible,
_is_update_available... | 237 | 8,680 |
maigret | tests/test_checking.py | .py | import asyncio
from argparse import ArgumentTypeError
from unittest.mock import Mock
import pytest
from aiohttp.client_exceptions import ServerDisconnectedError
from curl_cffi import CurlError
from maigret import search
from maigret.activation import ParsingActivator
from maigret.checking import (
extract_ids_dat... | 1,950 | 67,346 |
maigret | tests/test_maigret.py | .py | """Maigret main module test functions"""
import asyncio
import json
import os
import copy
from unittest.mock import Mock, patch
import pytest
from maigret.maigret import self_check, maigret, save_db_safely
from maigret.maigret import (
extract_ids_from_page,
extract_ids_from_results,
)
from maigret.checking ... | 332 | 12,219 |
maigret | tests/test_submit.py | .py | import re
import pytest
from unittest.mock import MagicMock, patch
from maigret.submit import Submitter
from aiohttp import ClientSession
from maigret.sites import MaigretDatabase, MaigretSite
import logging
@pytest.mark.slow
@pytest.mark.asyncio
async def test_detect_known_engine(test_db, local_test_db):
# Use ... | 410 | 12,840 |
maigret | tests/test_notify.py | .py | from colorama import Fore, Style
from maigret.errors import CheckError
from maigret.notify import QueryNotifyPrint
from maigret.result import MaigretCheckStatus, MaigretCheckResult
def test_notify_illegal():
n = QueryNotifyPrint(color=False)
assert (
n.update(
MaigretCheckResult(
... | 207 | 7,312 |
maigret | tests/test_error_detection.py | .py | """
Unit tests for error page detection helpers.
"""
from maigret.error_detection import detect_error_page
from maigret.errors import CheckError
def test_site_specific_error():
err = detect_error_page(
"this page is blocked",
200,
{"blocked": "Blocked by site"},
ignore_403=False,
... | 39 | 846 |
maigret | tests/test_idempotent_writes.py | .py | """Tests for the 'don't rewrite files unless content actually changed' logic
in utils.generate_db_meta and utils.update_site_data. The point is to keep
sites.md and db_meta.json untouched when only the embedded timestamp/date
would change — so a precommit hook doesn't end up staging a no-op diff
every time someone runs... | 248 | 8,426 |
maigret | tests/test_cli.py | .py | """Maigret command-line arguments parsing tests"""
from argparse import Namespace
from typing import Dict, Any
DEFAULT_ARGS: Dict[str, Any] = {
'all_sites': False,
'auto_disable': False,
'connections': 100,
'cookie_file': None,
'csv': False,
'db_file': 'resources/data.json',
'debug': False... | 151 | 3,729 |
maigret | tests/test_data.py | .py | """Maigret data test functions"""
import pytest
from maigret.utils import is_country_tag
TOP_SITES_ALEXA_RANK_LIMIT = 50
KNOWN_SOCIAL_DOMAINS = [
"facebook.com",
"instagram.com",
"twitter.com",
"tiktok.com",
"vk.com",
"reddit.com",
"pinterest.com",
"snapchat.com",
"linkedin.com",... | 105 | 3,010 |
maigret | tests/test_activation.py | .py | """Maigret activation test functions"""
import inspect
import json
import os
import yarl
import aiohttp
import pytest
from unittest.mock import Mock
from tests.conftest import LOCAL_SERVER_PORT
from maigret import activation as activation_cache
from maigret.activation import (
ParsingActivator,
import_aioht... | 558 | 18,788 |
maigret | tests/test_utils.py | .py | """Maigret utils test functions"""
import itertools
import re
from markupsafe import Markup
from maigret.utils import (
CaseConverter,
is_country_tag,
enrich_link_str,
URLMatcher,
get_dict_ascii_tree,
get_match_ratio,
is_plausible_username,
)
def test_case_convert_camel_to_snake():
... | 260 | 9,289 |
maigret | tests/test_sites.py | .py | """Maigret Database test functions"""
import logging
import re
from typing import Any, Dict
from maigret.sites import MaigretDatabase, MaigretEngine, MaigretSite
EXAMPLE_DB: Dict[str, Any] = {
'engines': {
"XenForo": {
"presenseStrs": ["XenForo"],
"site": {
"absen... | 425 | 13,188 |
maigret | tests/test_generate_changelog.py | .py | """Unit tests for the pure CHANGELOG-manipulation logic in utils/generate_changelog.
The GitHub-fetching part (fetch_release_notes) is intentionally not tested here —
it is a thin `gh api` wrapper. Everything that decides *what the file becomes* is
pure and covered below.
"""
from utils.generate_changelog import buil... | 64 | 2,356 |
maigret | tests/test_permutator.py | .py | import pytest
from maigret.permutator import Permute
def test_gather_strict():
elements = {'a': 1, 'b': 2}
permute = Permute(elements)
result = permute.gather(method="strict")
expected = {
'a_b': 1,
'b_a': 2,
'a-b': 1,
'b-a': 2,
'a.b': 1,
'b.a': 2,
... | 51 | 955 |
maigret | tests/conftest.py | .py | import glob
import logging
import os
import pytest
from _pytest.mark import Mark
from maigret.sites import MaigretDatabase
from maigret.maigret import setup_arguments_parser
from maigret.settings import Settings
from aiohttp import web
LOCAL_SERVER_PORT = 8080
CUR_PATH = os.path.dirname(os.path.realpath(__file__))... | 119 | 2,973 |
maigret | pyinstaller/maigret_standalone.py | .py | #!/usr/bin/env python3
import asyncio
import platform
import sys
import maigret
DOUBLE_CLICK_INTRO = """\
Maigret runs from the command line. You can:
- call it from cmd/PowerShell: maigret_standalone.exe USERNAME [options]
- or enter a username below for a default search.
Full options: maigret_standalone.... | 78 | 1,832 |
maigret | utils/update_site_data.py | .py | #!/usr/bin/env python3
"""Maigret: Supported Site Listing with Alexa ranking and country tags
This module generates the listing of supported sites in file `SITES.md`
and pretty prints file with sites data.
"""
import io
import os
import re
import sys
import socket
import requests
import logging
import threading
import ... | 286 | 9,643 |
maigret | utils/fp_probe_top_sites.py | .py | #!/usr/bin/env python3
"""
Probe likely false-positive sites among the top-N Alexa-ranked entries.
For each of K random *distinct* usernames taken from ``usernameClaimed`` fields in
the Maigret database, runs a clean ``maigret`` scan (``--top-sites N --json simple|ndjson``).
Sites that return CLAIMED in *every* run ar... | 224 | 6,367 |
maigret | utils/check_top_n.py | .py | #!/usr/bin/env python3
"""
Mass site checking utility for Maigret development.
Check top-N sites from data.json and generate a report.
Usage:
python utils/check_top_n.py --top 100 # Check top 100 sites
python utils/check_top_n.py --top 50 --parallel 10 # Check with 10 parallel requests... | 481 | 17,307 |
maigret | utils/sites_diff.py | .py | import sys
import difflib
import requests
a = requests.get(sys.argv[1]).text
b = requests.get(sys.argv[2]).text
tokens_a = set(a.split('"'))
tokens_b = set(b.split('"'))
a_minus_b = tokens_a.difference(tokens_b)
b_minus_a = tokens_b.difference(tokens_a)
print(a_minus_b)
print(b_minus_a)
print(len(a_minus_b))
pri... | 36 | 818 |
maigret | utils/generate_db_meta.py | .py | """Generate db_meta.json from data.json for the auto-update system."""
import argparse
import hashlib
import json
import os.path as path
from datetime import datetime, timezone
from typing import Optional, Tuple
RESOURCES_DIR = path.join(path.dirname(path.dirname(path.abspath(__file__))), "maigret", "resources")
DATA... | 124 | 4,763 |
maigret | utils/import_sites.py | .py | #!/usr/bin/env python3
import json
import random
import re
from unittest.mock import Mock
import alive_progress
import requests
from maigret.maigret import *
from maigret.result import MaigretCheckStatus
from maigret.sites import MaigretSite
URL_RE = re.compile(r"https?://(www\.)?")
TIMEOUT = 200
async def maigre... | 283 | 9,350 |
maigret | utils/generate_changelog.py | .py | """Fill the CHANGELOG.md "What's Changed" section for a release.
Reproduces exactly what the GitHub "Generate release notes" button produces
(``* <PR title> by @<author> in <url>`` bullets, plus New Contributors and the
Full Changelog footer) and drops it under a ``## [<version>] - <date>`` heading
at the top of CHANG... | 144 | 6,025 |
maigret | utils/add_tags.py | .py | #!/usr/bin/env python3
import random
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from maigret.maigret import MaigretDatabase
def update_tags(site):
tags = []
if not site.tags:
print(f'Site {site.name} doesn\'t have tags')
else:
tags = site.tags
print(f'Site {s... | 56 | 1,520 |
maigret | utils/selfcheck_triage.py | .py | #!/usr/bin/env python3
"""
Triage report for `maigret --self-check --diagnose` output.
False negatives (claimed user not detected) and check errors are invisible
in normal usage: users just don't see the account. This tool surfaces them.
Workflow:
# 1. Run self-check on a TEMP COPY of the DB (scans/self-check ma... | 128 | 4,037 |
maigret | utils/check_engines.py | .py | #!/usr/bin/env python3
"""Maigret: Supported Site Listing with Alexa ranking and country tags
This module generates the listing of supported sites in file `SITES.md`
and pretty prints file with sites data.
"""
import asyncio
import json
import logging
from argparse import ArgumentParser, RawDescriptionHelpFormatter
fr... | 145 | 5,368 |
maigret | utils/site_check.py | .py | #!/usr/bin/env python3
"""
Site check utility for Maigret development.
Quickly test site availability, find valid usernames, and diagnose check issues.
Usage:
python utils/site_check.py --site "SiteName" --check-claimed
python utils/site_check.py --site "SiteName" --maigret # Test via Maigret
pyt... | 809 | 33,879 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.