id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
144,194
from typing import Any, Dict, List, Optional, Tuple, Union def safe_get( container: Union[str, List[Any], Dict[Any, Any], Tuple], key: Any, default: Optional[Any] = None, ) -> Any: if isinstance(container, dict): return container.get(key, default) else: return safe_get_with_brackets(...
null
144,195
from abc import ABC, abstractmethod from pathlib import Path from typing import List, Optional class SQLDriver(ABC): """Abstract class for SQL drivers. The expose common functionality for validating SQL queries. """ def validate_sql(self, query: str) -> List[str]: ... def get_schema(self) ->...
null
144,196
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, Optional, Type, Union, get_args, get_origin from pydantic import BaseModel, validator from pydantic.fields import ModelField from guardrails.datatypes import Boolean as B...
null
144,197
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, Optional, Type, Union, get_args, get_origin from pydantic import BaseModel, validator from pydantic.fields import ModelField from guardrails.datatypes import Boolean as B...
Convert a Pydantic BaseModel to an OpenAI function. Args: model: The Pydantic BaseModel to convert. Returns: OpenAI function paramters.
144,198
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, Optional, Type, Union, get_args, get_origin from pydantic import BaseModel, validator from pydantic.fields import ModelField from guardrails.datatypes import Boolean as B...
Create an Object from a Pydantic model.
144,199
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union, get_args from pydantic import BaseModel, ConfigDict, field_validator from pydantic.fields import FieldInfo from guardrails.datatypes...
null
144,200
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union, get_args from pydantic import BaseModel, ConfigDict, field_validator from pydantic.fields import FieldInfo from guardrails.datatypes...
Convert a Pydantic BaseModel to an OpenAI function. Args: model: The Pydantic BaseModel to convert. Returns: OpenAI function paramters.
144,201
import typing import warnings from copy import deepcopy from datetime import date, time from enum import Enum from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union, get_args from pydantic import BaseModel, ConfigDict, field_validator from pydantic.fields import FieldInfo from guardrails.datatypes...
Create an Object from a Pydantic model.
144,202
import sys from functools import wraps from operator import attrgetter from typing import Any, List, Optional, Union from opentelemetry import context from opentelemetry.context import Context from opentelemetry.trace import StatusCode, Tracer from guardrails.stores.context import get_tracer as get_context_tracer from ...
null
144,203
import sys from functools import wraps from operator import attrgetter from typing import Any, List, Optional, Union from opentelemetry import context from opentelemetry.context import Context from opentelemetry.trace import StatusCode, Tracer from guardrails.stores.context import get_tracer as get_context_tracer from ...
null
144,204
import sys from functools import wraps from operator import attrgetter from typing import Any, List, Optional, Union from opentelemetry import context from opentelemetry.context import Context from opentelemetry.trace import StatusCode, Tracer from guardrails.stores.context import get_tracer as get_context_tracer from ...
null
144,205
import sys from functools import wraps from operator import attrgetter from typing import Any, List, Optional, Union from opentelemetry import context from opentelemetry.context import Context from opentelemetry.trace import StatusCode, Tracer from guardrails.stores.context import get_tracer as get_context_tracer from ...
This is the standard otel tracer set to talk to a grpc open telemetry collector running on port 4317.
144,206
import sys from functools import wraps from operator import attrgetter from typing import Any, List, Optional, Union from opentelemetry import context from opentelemetry.context import Context from opentelemetry.trace import StatusCode, Tracer from guardrails.stores.context import get_tracer as get_context_tracer from ...
This tracer will emit spans directly to an otlp endpoint, configured by the following environment variables: OTEL_EXPORTER_OTLP_PROTOCOL OTEL_EXPORTER_OTLP_TRACES_ENDPOINT OTEL_EXPORTER_OTLP_HEADERS We recommend using Grafana to collect your metrics. A full example of how to do that is in our (docs)[https://docs.guards...
144,207
import os import random from typing import List from lxml.etree import Element as E from rich.pretty import pretty_repr from guardrails import datatypes as dt from guardrails.classes.history.call import Call from guardrails.utils.reask_utils import gather_reasks class Call(ArbitraryModel): iterations: Stack[Iterat...
Generate artifacts for testing. Artifacts include: rail_spec, compiled_prompt, llm_output, validated_response. The artifacts are saved by on_fail_type. Check out tests/integration_tests/test_assets/entity_extraction/ for examples. This function is only intended to be used to create artifacts for integration tests once ...
144,208
import os import random from typing import List from lxml.etree import Element as E from rich.pretty import pretty_repr from guardrails import datatypes as dt from guardrails.classes.history.call import Call from guardrails.utils.reask_utils import gather_reasks The provided code snippet includes necessary dependencie...
Generate random schemas that represent a valid schema. Args: n: The number of schemas to generate. depth: The depth of nesting
144,209
from typing import Any, Dict, List, Optional, Tuple, Type, Union from guardrails.utils.safe_get import safe_get from guardrails.validator_base import Validator def safe_get( container: Union[str, List[Any], Dict[Any, Any], Tuple], key: Any, default: Optional[Any] = None, ) -> Any: if isinstance(contain...
null
144,210
from typing import Union The provided code snippet includes necessary dependencies for implementing the `cast_xml_to_string` function. Write a Python function `def cast_xml_to_string(xml_value: Union[memoryview, bytes, bytearray, str]) -> str` to solve the following problem: Cast XML value to a string. Args: xml_value...
Cast XML value to a string. Args: xml_value (Union[memoryview, bytes, bytearray, str]): The XML value to cast. Returns: str: The XML value as a string.
144,211
from typing import Dict, List import tiktoken The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_string` function. Write a Python function `def num_tokens_from_string(text: str, model_name: str) -> int` to solve the following problem: Returns the number of tokens in a text ...
Returns the number of tokens in a text string. Supported for OpenAI models only. This is a helper function that is required when OpenAI's `stream` parameter is set to `True`, because OpenAI does not return the number of tokens in that case. Requires the `tiktoken` package to be installed. Args: text (str): The text str...
144,212
from typing import Dict, List import tiktoken The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_messages` function. Write a Python function `def num_tokens_from_messages( messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo-0613" ) -> int` to solve the following...
Return the number of tokens used by a list of messages.
144,213
from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai import openai.error from tenacity import retry, retry_if_exception_type, wait_exponential_jitter from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import ( BaseAsyncOpenAIClient, BaseSyncO...
null
144,214
from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai import openai.error from tenacity import retry, retry_if_exception_type, wait_exponential_jitter from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import ( BaseAsyncOpenAIClient, BaseSyncO...
null
144,215
from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai import openai.error from tenacity import retry, retry_if_exception_type, wait_exponential_jitter from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import ( BaseAsyncOpenAIClient, BaseSyncO...
null
144,216
from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai import openai.error from tenacity import retry, retry_if_exception_type, wait_exponential_jitter from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import ( BaseAsyncOpenAIClient, BaseSyncO...
null
144,217
import os from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import BaseOpenAIClient from guardrails.utils.openai_utils.streaming_utils import ( num_tokens_from_messages, num_tokens_from_st...
null
144,218
import os from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import BaseOpenAIClient from guardrails.utils.openai_utils.streaming_utils import ( num_tokens_from_messages, num_tokens_from_st...
null
144,219
import os from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import BaseOpenAIClient from guardrails.utils.openai_utils.streaming_utils import ( num_tokens_from_messages, num_tokens_from_st...
null
144,220
import os from typing import Any, AsyncIterable, Dict, Iterable, List, cast import openai from guardrails.utils.llm_response import LLMResponse from guardrails.utils.openai_utils.base import BaseOpenAIClient from guardrails.utils.openai_utils.streaming_utils import ( num_tokens_from_messages, num_tokens_from_st...
null
144,221
from copy import deepcopy from datetime import datetime from typing import Any, Dict, List, Optional from guardrails.utils.pydantic_utils import ArbitraryModel from guardrails.utils.reask_utils import FieldReAsk, ReAsk, prune_obj_for_reasking from guardrails.validator_base import ValidationResult def update_response_by...
Merge the reask output into the original output. Args: prev_logs: validation output object from the previous iteration. current_logs: validation output object from the current iteration. Returns: The merged output.
144,222
import argparse, os import PIL import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange, repeat from torchvision.utils import make_grid from torch import autocast from contextlib import nullcontext from ...
null
144,223
import argparse, os import PIL import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange, repeat from torchvision.utils import make_grid from torch import autocast from contextlib import nullcontext from ...
null
144,224
import argparse, os import PIL import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange, repeat from torchvision.utils import make_grid from torch import autocast from contextlib import nullcontext from ...
null
144,225
import argparse, os import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange from torchvision.utils import make_grid from pytorch_lightning import seed_everything from torch import autocast fr...
null
144,226
import argparse, os import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange from torchvision.utils import make_grid from pytorch_lightning import seed_everything from torch import autocast fr...
null
144,227
import argparse, os import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange from torchvision.utils import make_grid from pytorch_lightning import seed_everything from torch import autocast fr...
null
144,228
import sys import torch import numpy as np import streamlit as st from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.util import instantiate_f...
null
144,229
import sys import torch import numpy as np import streamlit as st from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.models.diffusion.ddim imp...
null
144,230
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,231
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,232
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,233
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,234
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,235
import importlib import streamlit as st import torch import cv2 import numpy as np import PIL from omegaconf import OmegaConf from PIL import Image from tqdm import trange import io, os from torch import autocast from einops import rearrange, repeat from torchvision.utils import make_grid from pytorch_lightning import ...
null
144,236
import sys import cv2 import torch import numpy as np import streamlit as st from PIL import Image from omegaconf import OmegaConf from einops import repeat from streamlit_drawable_canvas import st_canvas from imwatermark import WatermarkEncoder from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import ins...
null
144,237
import sys import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.util import instantiate_from...
null
144,238
import sys import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.util import instantiate_from...
null
144,239
import sys import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.models.diffusion.ddim import...
null
144,240
import sys import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat, rearrange from pytorch_lightning import seed_everything from imwatermark import WatermarkEncoder from scripts.txt2img import put_watermark from ldm.models.diffusion.ddim import...
null
144,241
import sys import cv2 import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat from imwatermark import WatermarkEncoder from pathlib import Path from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import instantiate_from_config torch...
null
144,242
import sys import cv2 import torch import numpy as np import gradio as gr from PIL import Image from omegaconf import OmegaConf from einops import repeat from imwatermark import WatermarkEncoder from pathlib import Path from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import instantiate_from_config def i...
null
144,243
import math import torch as th import torch.nn as nn import torch.nn.functional as F from .nn import timestep_embedding The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f16` function. Write a Python function `def convert_module_to_f16(param)` to solve the following prob...
Convert primitive modules to float16.
144,244
import enum import math import numpy as np import torch as th def get_beta_schedule(beta_schedule, *, beta_start, beta_end, num_diffusion_timesteps): """ This is the deprecated API for creating beta schedules. See get_named_beta_schedule() for the new library of schedules. """ if beta_schedule == "q...
Get a pre-defined beta schedule for the given name. The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility.
144,245
import enum import math import numpy as np import torch as th The provided code snippet includes necessary dependencies for implementing the `_extract_into_tensor` function. Write a Python function `def _extract_into_tensor(arr, timesteps, broadcast_shape)` to solve the following problem: Extract values from a 1-D num...
Extract values from a 1-D numpy array for a batch of indices. :param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ......
144,246
import torch as th from .gaussian_diffusion import GaussianDiffusion The provided code snippet includes necessary dependencies for implementing the `space_timesteps` function. Write a Python function `def space_timesteps(num_timesteps, section_counts)` to solve the following problem: Create a list of timesteps to use ...
Create a list of timesteps to use from an original diffusion process, given the number of timesteps we want to take from equally-sized portions of the original process. For example, if there's 300 timesteps and the section counts are [10,15,20] then the first 100 timesteps are strided to be 10 timesteps, the second 100...
144,247
from abc import abstractmethod import torch as th class UniformSampler(ScheduleSampler): def __init__(self, diffusion): super(UniformSampler, self).__init__() self.diffusion = diffusion self.register_buffer( "_weights", th.ones([diffusion.num_timesteps]), persistent=False ...
Create a ScheduleSampler from a library of pre-defined samplers. :param name: the name of the sampler. :param diffusion: the diffusion object to sample for.
144,248
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `conv_nd` function. Write a Python function `def conv_nd(dims, *args, **kwargs)` to solve the following problem: Create a 1D, 2D, or 3D convolution module....
Create a 1D, 2D, or 3D convolution module.
144,249
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `linear` function. Write a Python function `def linear(*args, **kwargs)` to solve the following problem: Create a linear module. Here is the function: de...
Create a linear module.
144,250
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `avg_pool_nd` function. Write a Python function `def avg_pool_nd(dims, *args, **kwargs)` to solve the following problem: Create a 1D, 2D, or 3D average poo...
Create a 1D, 2D, or 3D average pooling module.
144,251
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` to solve the following problem: Zero out the parameters of a module and return it...
Zero out the parameters of a module and return it.
144,252
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `scale_module` function. Write a Python function `def scale_module(module, scale)` to solve the following problem: Scale the parameters of a module and ret...
Scale the parameters of a module and return it.
144,253
import math import torch as th import torch.nn as nn import torch.nn.functional as F class GroupNorm32(nn.GroupNorm): def __init__(self, num_groups, num_channels, swish, eps=1e-5): super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps) self.swish = swish def forward(self, x)...
Make a standard normalization layer, with an optional swish activation. :param channels: number of input channels. :return: an nn.Module for normalization.
144,254
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `timestep_embedding` function. Write a Python function `def timestep_embedding(timesteps, dim, max_period=10000)` to solve the following problem: Create si...
Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings.
144,255
import math import torch as th import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def mean_flat(tensor)` to solve the following problem: Take the mean over all non-batch dimensions. Here is...
Take the mean over all non-batch dimensions.
144,256
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat from ldm.util import instantiate_from_config def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which de...
null
144,352
import torch import torch.nn as nn import kornia from torch.utils.checkpoint import checkpoint from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel import open_clip from ldm.util import default, count_params, autocast from ldm.modules.diffusionmodules.upscaling import ImageConcatWithNoiseA...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
144,358
import torch import torch.nn.functional as F import math from tqdm import tqdm def expand_dims(v, dims): """ Expand the tensor `v` to the dim `dims`. Args: `v`: a PyTorch tensor with shape [N]. `dim`: a `int`. Returns: a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total d...
Create a wrapper function for the noise prediction model. DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. We support four types of the diffusion m...
144,364
from os import path from crosslinked.logger import Log def delimiter2list(value, delim=","): return value.split(delim) if value else []
null
144,365
from os import path from crosslinked.logger import Log def delimiter2dict(value, delim_one=";", delim_two=":"): x = {} for item in value.split(delim_one): if item: sp = item.split(delim_two) x[sp[0].strip()] = delim_two.join(sp[1:]).strip() return x
null
144,366
from os import path from crosslinked.logger import Log class Log: # Quick log class for CLI output def info(msg): print(' '.join([highlight('[*]', 'bold', 'blue'), msg])) def success(msg): print(' '.join([highlight('[+]', 'bold', 'green'), msg])) def warn(msg): print(' '.join(...
null
144,367
import logging import requests import threading from time import sleep from random import choice from bs4 import BeautifulSoup from unidecode import unidecode from urllib.parse import urlparse from crosslinked.logger import Log from datetime import datetime, timedelta from urllib3 import disable_warnings, exceptions d...
null
144,368
import logging import requests import threading from time import sleep from random import choice from bs4 import BeautifulSoup from unidecode import unidecode from urllib.parse import urlparse from crosslinked.logger import Log from datetime import datetime, timedelta from urllib3 import disable_warnings, exceptions de...
null
144,369
import logging import requests import threading from time import sleep from random import choice from bs4 import BeautifulSoup from unidecode import unidecode from urllib.parse import urlparse from crosslinked.logger import Log from datetime import datetime, timedelta from urllib3 import disable_warnings, exceptions d...
null
144,370
import logging import requests import threading from time import sleep from random import choice from bs4 import BeautifulSoup from unidecode import unidecode from urllib.parse import urlparse from crosslinked.logger import Log from datetime import datetime, timedelta from urllib3 import disable_warnings, exceptions d...
null
144,371
import os import sys import logging def debug_args(args): for k in args.__dict__: logging.debug('{:20} => {}'.format(k, args.__dict__[k]))
null
144,372
import os import sys import logging def highlight(data, style='bold', fg='blue'): return code_gen(data, style, fg, windows=True if os.name == 'nt' else False) def setup_debug_logger(): debug_output_string = "{} %(message)s".format(highlight('DEBUG', fg='purple')) formatter = logging.Formatter(debug_output_...
null
144,373
import os import sys import logging def first_run(logger): # init headings in CSV log file logger.info('Datetime,Search,Name,Title,URL,rawText') def setup_file_logger(file_name, log_name='cLinked_file', file_mode='w'): formatter = logging.Formatter('%(message)s') fileHandler = logging.FileHandler(file_...
null
144,374
import os import sys import logging def setup_cli_logger(log_level=logging.INFO, logger_name='cLinked'): formatter = logging.Formatter('%(message)s') StreamHandler = logging.StreamHandler(sys.stdout) StreamHandler.setFormatter(formatter) logger = logging.getLogger(logger_name) logger.propagate = F...
null
144,376
from setuptools import find_packages, setup import os import subprocess import time version_file = 'gfpgan/version.py' def get_hash(): def write_version_py(): content = """# GENERATED VERSION FILE # TIME: {} __version__ = '{}' __gitsha__ = '{}' version_info = ({}) """ sha = get_hash() with open('VERSION', ...
null
144,377
from setuptools import find_packages, setup import os import subprocess import time version_file = 'gfpgan/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
null
144,380
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def Normalize(in_channels): return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
null
144,382
import os os.system('python setup.py develop') os.system('pip install realesrgan') import cv2 import shutil import tempfile import torch from basicsr.archs.srvgg_arch import SRVGGNetCompact from gfpgan import GFPGANer def clean_folder(folder): for filename in os.listdir(folder): file_path = os.path.join(fo...
null
144,383
import argparse import math import torch from gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean def modify_checkpoint(checkpoint_bilinear, checkpoint_clean): for ori_k, ori_v in checkpoint_bilinear.items(): if 'stylegan_decoder' in ori_k: if 'style_mlp' in ori_k: # style_mlp_layers ...
null
144,384
from ane_transformers.reference.layer_norm import LayerNormANE import torch import torch.nn as nn from transformers.models.distilbert import modeling_distilbert def correct_for_bias_scale_order_inversion(state_dict, prefix, local_metadata, strict, missing_keys, ...
null
144,385
from ane_transformers.reference.layer_norm import LayerNormANE import torch import torch.nn as nn from transformers.models.distilbert import modeling_distilbert The provided code snippet includes necessary dependencies for implementing the `linear_to_conv2d_map` function. Write a Python function `def linear_to_conv2d_...
Unsqueeze twice to map nn.Linear weights to nn.Conv2d weights
144,386
import os import traceback import time import pyuac import asyncio import questionary import importlib import tqdm from docopt import docopt from questionary import ValidationError from pluggy import PluginManager from get_width import get_width from utils.log import log, fight_log from utils.config import read_json_fi...
null
144,387
import sys import pyuac import traceback import tkinter as tk from tkinter import messagebox try: import time import flet as ft from re import sub from cryptography.fernet import Fernet from flet_core import MainAxisAlignment from utils.log import log,level from utils.map import Map as map_w...
if page.session.contains_key("updata_log"): page.session.remove("updata_log")
144,388
from .get_angle import get_camera_angle, get_angle import time import pyautogui import win32con, win32api import numpy as np import sys import cv2 print(f'前进{t}秒') pyautogui.keyDown("w") time.sleep(t) pyautogui.keyUp("w") def move(t, run=True): print(f'前进{t}秒') pyautogui.keyDown("w") if run: pyautogui.keyDow...
null
144,389
import time import cv2 as cv import numpy as np import pygetwindow as gw from PIL import Image, ImageGrab from .config import _, sra_config_obj from .log import log def show_img(img, scale=1, title='Image'): # cv.namedWindow('image', cv.WINDOW_NORMAL) h, w = img.shape[:2] img = cv.resize( img ,(int(w*scale...
null
144,390
import time import cv2 as cv import numpy as np import pygetwindow as gw from PIL import Image, ImageGrab from .config import _, sra_config_obj from .log import log def show_imgs(imgs, title='Image'): cv.imshow(title, np.hstack(imgs)) cv.waitKey(0) cv.destroyAllWindows()
null
144,391
import time from pynput.keyboard import Key from utils.calculated import calculated from utils.log import _, log def get_percentile(rect, shape): #获取长方形的相对坐标 x1,y1,x2,y2 = rect w,h = shape return [x1/w*100,y1/h*100,x2/w*100,y2/h*100]
null
144,392
import itertools import os import re import sys import time import copy from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union import cv2 as cv import numpy as np import pywinctl as pwc n32api import hashlib import pprint from cnocr import CnOcr from P...
说明: 将多个风格化文本序列,按行进行横向并联 参数: :param sep: 插入在文本序列间的内容,默认为空 :param prefix: 文本前缀 :param indent: 起始位置的缩进长度,默认为零
144,393
import itertools import os import re import sys import time import copy from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union import cv2 as cv import numpy as np import pywinctl as pwc n32api import hashlib import pprint from cnocr import CnOcr from P...
说明: 打印风格化文本
144,394
import itertools import os import re import sys import time import copy from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union import cv2 as cv import numpy as np import pywinctl as pwc import hashlib import pprint from cnocr import CnOcr from PIL impo...
说明: 求任意类型数据 (包括list和dict) 的哈希值 首先将数据规范化输出为str,再计算md5转16进制 参数: :param data: 任意类型数据 :param key_filter: 键值过滤器 :param speed_modified: 是否对速度属性进行修饰 (忽略小数位数值)
144,395
import itertools import os import re import sys import time import copy from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union import cv2 as cv import numpy as np import pywinctl as pwc import hashlib import pprint from cnocr import CnOcr from PIL impo...
说明: 封装str.rjust()&str.ljust(),以适应中文字符的实际宽度
144,396
import gettext import inspect import os import sys import jsonschema from pathlib import Path from typing import Any, Union, get_type_hints import orjson from orjson import JSONDecodeError from .exceptions import TypeError from .log import log os.makedirs(USER_DATA_PREFIX, exist_ok=True) The provided code snippet incl...
获取文件夹下的文件夹列表
144,397
import gettext import inspect import os import sys import jsonschema from pathlib import Path from typing import Any, Union, get_type_hints import orjson from orjson import JSONDecodeError from .exceptions import TypeError from .log import log The provided code snippet includes necessary dependencies for implementing ...
说明: 在指定位置添加键值对 参数: :param dictionary 需要添加的字典 :param key: 键 :param value: 值 :param position: 需要添加的位置 返回: new_dictionary: 添加后的字典
144,398
import gettext import inspect import os import sys import jsonschema from pathlib import Path from typing import Any, Union, get_type_hints import orjson from orjson import JSONDecodeError from .exceptions import TypeError from .log import log The provided code snippet includes necessary dependencies for implementing ...
说明: 将指定键值对插入指定key后面 参数: :param my_dict: 被操作的字典 :param new_key: 需要插入的key :param new_value: 需要插入的value :param insert_after_key: 插入到那个key后面
144,399
import gettext import inspect import os import sys import jsonschema from pathlib import Path from typing import Any, Union, get_type_hints import orjson from orjson import JSONDecodeError from .exceptions import TypeError from .log import log CONFIG_FILE_NAME = "config.json" def read_json_file(filename: str, path=Fals...
null
144,400
import gettext import inspect import os import sys import jsonschema from pathlib import Path from typing import Any, Union, get_type_hints import orjson from orjson import JSONDecodeError from .exceptions import TypeError from .log import log CONFIG_FILE_NAME = "config.json" def read_json_file(filename: str, path=Fals...
加载配置文件
144,401
import time import cv2 as cv import numpy as np import pywinctl as pwc import Image, ImageGrab from .config import _, sra_config_obj from .log import log def show_img(img, scale=1, title='Image', not_close=False): # cv.namedWindow('image', cv.WINDOW_NORMAL) #h, w = img.shape[:2] #img = cv.resize( img ,(int...
null
144,402
import time import cv2 as cv import numpy as np import pywinctl as pwc import Image, ImageGrab from .config import _, sra_config_obj from .log import log def show_imgs(imgs, title='Image'): cv.imshow(title, np.hstack(imgs)) cv.waitKey(0) cv.destroyAllWindows()
null