id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
33,737
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def multiclass_accuracy(y_true, y_pred): correct = 0 total = len(y_true) for label, pred in zip(y_true, y_pred): correct += label == pred return correct/total
null
33,738
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def accuracy_cm(cm): return np.trace(cm)/np.sum(cm)
null
33,739
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def balanced_accuracy_cm(cm): correctly_classified = np.diagonal(cm) rows_sum = np.sum(cm, axis=1) indices = np.nonzero(rows_sum)[0] if rows_sum.shape[0] != indices.shape[0]: warnings.warn("y_...
null
33,740
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def precision(y_true, y_pred): """ Fraction of True Positive Elements divided by total number of positive predicted units How I view it: Assuming we say someone has cancer: how often are we correct? It...
null
33,741
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def confusion_matrix(y_true, y_pred): y_true = np.array(y_true) y_pred = np.array(y_pred) assert y_true.shape == y_pred.shape unique_classes = np.unique(np.concatenate([y_true, y_pred], axis=0)).shape[...
null
33,742
import numpy as np from scipy.integrate import simpson import matplotlib.pyplot as plt import warnings def precision(y_true, y_pred): """ Fraction of True Positive Elements divided by total number of positive predicted units How I view it: Assuming we say someone has cancer: how often are we correct? It...
null
33,743
import pandas as pd import numpy as np import torch def get_predictions(loader, model, device): model.eval() saved_preds = [] true_labels = [] with torch.no_grad(): for x,y in loader: x = x.to(device) y = y.to(device) scores = model(x) saved_pred...
null
33,744
import pandas as pd import numpy as np import torch def get_submission(model, loader, test_ids, device): all_preds = [] model.eval() with torch.no_grad(): for x,y in loader: print(x.shape) x = x.to(device) score = model(x) prediction = score.float() ...
null
33,745
import pandas as pd import torch from torch.utils.data import TensorDataset from torch.utils.data.dataset import random_split from math import ceil def get_data(): train_data = pd.read_csv("new_shiny_train.csv") y = train_data["target"] X = train_data.drop(["ID_code", "target"], axis=1) X_tensor = torc...
null
33,746
import torch from torch import nn, optim import os import config from torch.utils.data import DataLoader from tqdm import tqdm from sklearn.metrics import cohen_kappa_score from efficientnet_pytorch import EfficientNet from dataset import DRDataset from torchvision.utils import save_image from utils import ( load_c...
null
33,747
import torch from tqdm import tqdm import numpy as np from torch import nn from torch import optim from torch.utils.data import DataLoader, Dataset from utils import save_checkpoint, load_checkpoint, check_accuracy from sklearn.metrics import cohen_kappa_score import config import os import pandas as pd def make_predi...
null
33,748
import torch import pandas as pd import numpy as np import config from tqdm import tqdm import warnings import torch.nn.functional as F def make_prediction(model, loader, output_csv="submission.csv"): preds = [] filenames = [] model.eval() for x, y, files in tqdm(loader): x = x.to(config.DEVIC...
null
33,749
import torch import pandas as pd import numpy as np import config from tqdm import tqdm import warnings import torch.nn.functional as F def check_accuracy(loader, model, device="cuda"): model.eval() all_preds, all_labels = [], [] num_correct = 0 num_samples = 0 for x, y, filename in tqdm(loader): ...
null
33,750
import torch import pandas as pd import numpy as np import config from tqdm import tqdm import warnings import torch.nn.functional as F def save_checkpoint(state, filename="my_checkpoint.pth.tar"): print("=> Saving checkpoint") torch.save(state, filename)
null
33,751
import torch import pandas as pd import numpy as np import config from tqdm import tqdm import warnings import torch.nn.functional as F def load_checkpoint(checkpoint, model, optimizer, lr): print("=> Loading checkpoint") model.load_state_dict(checkpoint["state_dict"]) #optimizer.load_state_dict(checkpoint...
null
33,752
import torch import pandas as pd import numpy as np import config from tqdm import tqdm import warnings import torch.nn.functional as F def get_csv_for_blend(loader, model, output_csv_file): warnings.warn("Important to have shuffle=False (and to ensure batch size is even size) when running get_csv_for_blend also s...
null
33,753
import os import numpy as np from PIL import Image import warnings from multiprocessing import Pool from tqdm import tqdm import cv2 def save_single(args): img_file, input_path_folder, output_path_folder, output_size = args image_original = Image.open(os.path.join(input_path_folder, img_file)) image = trim(...
Uses multiprocessing to make it fast
33,754
import torch from dataset import FacialKeypointDataset from torch import nn, optim import os import config from torch.utils.data import DataLoader from tqdm import tqdm from efficientnet_pytorch import EfficientNet from utils import ( load_checkpoint, save_checkpoint, get_rmse, get_submission ) def tra...
null
33,755
import torch import numpy as np import config import pandas as pd from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `get_submission` function. Write a Python function `def get_submission(loader, dataset, model_15, model_4)` to solve the following problem: This can be ...
This can be done a lot faster.. but it didn't take too much time to do it in this inefficient way
33,756
import torch import numpy as np import config import pandas as pd from tqdm import tqdm def get_rmse(loader, model, loss_fn, device): model.eval() num_examples = 0 losses = [] for batch_idx, (data, targets) in enumerate(loader): data = data.to(device=device) targets = targets.to(device=...
null
33,757
import torch import numpy as np import config import pandas as pd from tqdm import tqdm def save_checkpoint(state, filename="my_checkpoint.pth.tar"): print("=> Saving checkpoint") torch.save(state, filename)
null
33,758
import torch import numpy as np import config import pandas as pd from tqdm import tqdm def load_checkpoint(checkpoint, model, optimizer, lr): print("=> Loading checkpoint") model.load_state_dict(checkpoint["state_dict"]) optimizer.load_state_dict(checkpoint["optimizer"]) # If we don't do this then it...
null
33,759
import numpy as np import pandas as pd import os from PIL import Image def extract_images_from_csv(csv, column, save_folder, resize=(96, 96)): if not os.path.exists(save_folder): os.makedirs(save_folder) for idx, image in enumerate(csv[column]): image = np.array(image.split()).astype(np.uint8)...
null
33,760
import os import torch import torch.nn.functional as F import numpy as np import config from torch import nn, optim from torch.utils.data import DataLoader from tqdm import tqdm from dataset import CatDog from efficientnet_pytorch import EfficientNet from utils import check_accuracy, load_checkpoint, save_checkpoint d...
null
33,761
import os import torch import torch.nn.functional as F import numpy as np import config from torch import nn, optim from torch.utils.data import DataLoader from tqdm import tqdm from dataset import CatDog from efficientnet_pytorch import EfficientNet from utils import check_accuracy, load_checkpoint, save_checkpoint d...
null
33,762
import torch import os import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 import config from tqdm import tqdm from dataset import CatDog from torch.utils.data import DataLoader from sklearn.metrics import log_loss The provided code snippet includes necessary...
Check accuracy of model on data from loader
33,763
import torch import os import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 import config from tqdm import tqdm from dataset import CatDog from torch.utils.data import DataLoader from sklearn.metrics import log_loss def save_checkpoint(state, filename="my_chec...
null
33,764
import torch import os import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 import config from tqdm import tqdm from dataset import CatDog from torch.utils.data import DataLoader from sklearn.metrics import log_loss def load_checkpoint(checkpoint, model): ...
null
33,765
import torch import os import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 import config from tqdm import tqdm from dataset import CatDog from torch.utils.data import DataLoader from sklearn.metrics import log_loss def create_submission(model, model_name, fil...
null
33,766
import torch import os import pandas as pd import numpy as np import albumentations as A from albumentations.pytorch import ToTensorV2 import config from tqdm import tqdm from dataset import CatDog from torch.utils.data import DataLoader from sklearn.metrics import log_loss def blending_ensemble_data(): pred_csvs ...
null
33,767
import locale import os import re import shutil import subprocess import sys import sysconfig from typing import List from pathlib import Path from typing import Optional import pkg_resources from mikazuki.log import log python_bin = sys.executable def run(command, desc: Optional[str] = None, errdesc: O...
null
33,768
import subprocess import sys import os import threading import uuid from enum import Enum from typing import Dict, List from subprocess import Popen, PIPE, TimeoutExpired, CalledProcessError, CompletedProcess import psutil from mikazuki.log import log def kill_proc_tree(pid, including_parent=True): parent = psutil...
null
33,769
import cv2 import numpy as np from PIL import Image def smart_imread(img, flag=cv2.IMREAD_UNCHANGED): if img.endswith(".gif"): img = Image.open(img) img = img.convert("RGB") img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) else: img = cv2.imread(img, flag) return img
null
33,770
import cv2 import numpy as np from PIL import Image def smart_24bit(img): if img.dtype is np.dtype(np.uint16): img = (img / 257).astype(np.uint8) if len(img.shape) == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) elif img.shape[2] == 4: trans_mask = img[:, :, 3] == 0 img[t...
null
33,771
import cv2 import numpy as np from PIL import Image def make_square(img, target_size): old_size = img.shape[:2] desired_size = max(old_size) desired_size = max(desired_size, target_size) delta_w = desired_size - old_size[1] delta_h = desired_size - old_size[0] top, bottom = delta_h // 2, delta...
null
33,772
import cv2 import numpy as np from PIL import Image def smart_resize(img, size): # Assumes the image has already gone through make_square if img.shape[0] > size: img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA) elif img.shape[0] < size: img = cv2.resize(img, (size, size), i...
null
33,773
import re import hashlib from typing import Dict, Callable, NamedTuple from pathlib import Path class Info(NamedTuple): path: Path output_ext: str def hash(i: Info, algo='sha1') -> str: try: hash = hashlib.new(algo) except ImportError: raise ValueError(f"'{algo}' is invalid hash algorit...
null
33,774
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,775
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,776
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,777
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,778
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,779
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,780
import asyncio import json import os from datetime import datetime from pathlib import Path import toml from fastapi import APIRouter, BackgroundTasks, Request from starlette.requests import Request import mikazuki.process as process from mikazuki import launch_utils from mikazuki.app.models import (APIResponse, APIRes...
null
33,781
import asyncio import os import httpx import starlette import websockets from fastapi import APIRouter, Request, WebSocket from httpx import ConnectError from starlette.background import BackgroundTask from starlette.requests import Request from starlette.responses import PlainTextResponse, StreamingResponse from mikaz...
null
33,782
import asyncio import os import httpx import starlette import websockets from fastapi import APIRouter, Request, WebSocket from httpx import ConnectError from starlette.background import BackgroundTask from starlette.requests import Request from starlette.responses import PlainTextResponse, StreamingResponse from mikaz...
null
33,783
import asyncio import mimetypes import os import webbrowser import sys from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from mikazuki.utils.devices import check...
null
33,784
import asyncio import mimetypes import os import webbrowser import sys from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from mikazuki.utils.devices import check...
null
33,785
import asyncio import mimetypes import os import webbrowser import sys from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from mikazuki.utils.devices import check...
null
33,786
import sys def check_torch_gpu(): try: import torch print(f'Torch {torch.__version__}') if torch.cuda.is_available(): if torch.version.cuda: print( f'Torch backend: nVidia CUDA {torch.version.cuda} cuDNN {torch.backends.cudnn.version() if torc...
null
33,787
import glob import os import re import shutil import sys from mikazuki.log import log def check_training_params(data): potential_path = [ "train_data_dir", "reg_data_dir", "output_dir" ] file_paths = [ "sample_prompts" ] for p in potential_path: if p in data and not os.path....
null
33,788
import argparse import locale import os import platform import subprocess import sys import webbrowser from mikazuki.launch_utils import prepare_environment, base_dir_path from mikazuki.log import log def run_tensorboard(): log.info("Starting tensorboard...") subprocess.Popen([sys.executable, "-m", "tensorboard...
null
33,789
from collections import namedtuple import rrc_evaluation_funcs import importlib The provided code snippet includes necessary dependencies for implementing the `default_evaluation_params` function. Write a Python function `def default_evaluation_params()` to solve the following problem: default_evaluation_params: Defau...
default_evaluation_params: Default parameters to use for the validation and evaluation.
33,790
from collections import namedtuple import rrc_evaluation_funcs import importlib The provided code snippet includes necessary dependencies for implementing the `validate_data` function. Write a Python function `def validate_data(gtFilePath, submFilePath, evaluationParams)` to solve the following problem: Method validat...
Method validate_data: validates that all files in the results folder are correct (have the correct name contents). Validates also that there are no missing files in the folder. If some error detected, the method raises the error
33,791
from collections import namedtuple import rrc_evaluation_funcs import importlib def evaluation_imports(): """ evaluation_imports: Dictionary ( key = module name , value = alias ) with python modules used in the evaluation. """ return { 'Polygon':'plg', 'numpy':'np' ...
Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recal...
33,792
import json import sy import zipfile import re import sys import os import codecs import importlib from StringIO import StringIO The provided code snippet includes necessary dependencies for implementing the `load_zip_file_keys` function. Write a Python function `def load_zip_file_keys(file,fileNameRegExp='')` to solv...
Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp
33,793
import json import sysys.path.append('./') import zipfile import re import sys import os import codecs import importlib from StringIO import StringIO def print_help(): sys.stdout.write('Usage: python %s.py -g=<gtFile> -s=<submFile> [-o=<outputFolder> -p=<jsonParams>]' %sys.argv[0]) sys.exit(2) The provided cod...
This process validates a method, evaluates it and if it succed generates a ZIP file with a JSON entry for each sample. Params: p: Dictionary of parmeters with the GT/submission locations. If None is passed, the parameters send by the system are used. default_evaluation_params_fn: points to a function that returns a dic...
33,794
import json import sysys.path.append('./') import zipfile import re import sys import os import codecs import importlib from StringIO import StringIO The provided code snippet includes necessary dependencies for implementing the `main_validation` function. Write a Python function `def main_validation(default_evaluatio...
This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission
33,795
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,796
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,797
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,798
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,799
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,800
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,801
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,802
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,803
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,804
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,805
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,806
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,807
import copy import json import os import logging import uuid from dotenv import load_dotenv from quart import ( Blueprint, Quart, jsonify, make_response, request, send_from_directory, render_template ) from openai import AsyncAzureOpenAI from azure.identity.aio import DefaultAzureCredential,...
null
33,808
import argparse import dataclasses import json import os from azure.identity import DefaultAzureCredential from azure.core.credentials import AzureKeyCredential from azure.keyvault.secrets import SecretClient from azure.ai.formrecognizer import DocumentAnalysisClient from data_utils import chunk_directory def get_docu...
null
33,809
import ast import html import json import os import re import requests from openai import AzureOpenAI import re import tempfile import time from abc import ABC, abstractmethod from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass from functools import partial from typing import Callable, ...
Cleans up the given content using regexes Args: content (str): The content to clean up. Returns: str: The cleaned up content.
33,810
import argparse import json import os import time import uuid import pinecone import requests from data_utils import Document from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential from azure.identity import AzureCliCredential from typing import List from data_u...
null
33,811
import argparse import json import os import uuid import requests from data_utils import Document from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential from azure.identity import AzureCliCredential from pymongo.mongo_client import MongoClient from typing import...
null
33,812
import argparse import json import os import uuid import requests from data_utils import Document from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential from azure.identity import AzureCliCredential from pymongo.mongo_client import MongoClient from typing import...
null
33,813
import argparse from azure.identity import AzureDeveloperCliCredential import urllib3 def update_redirect_uris(credential, app_id, uri): urllib3.request( "PATCH", f"https://graph.microsoft.com/v1.0/applications/{app_id}", headers={ "Authorization": "Bearer " + creden...
null
33,814
import argparse import dataclasses import time from tqdm import tqdm from azure.identity import AzureDeveloperCliCredential from azure.core.credentials import AzureKeyCredential from azure.search.documents.indexes import SearchIndexClient from azure.search.documents.indexes.models import ( SearchableField, Sear...
null
33,815
import argparse import subprocess from azure.identity import AzureDeveloperCliCredential import urllib3 def get_auth_headers(credential): return { "Authorization": "Bearer " + credential.get_token("https://graph.microsoft.com/.default").token } def check_for_application(credential, app_id): ...
null
33,816
import argparse import subprocess from azure.identity import AzureDeveloperCliCredential import urllib3 def get_auth_headers(credential): return { "Authorization": "Bearer " + credential.get_token("https://graph.microsoft.com/.default").token } def create_application(credential): resp = url...
null
33,817
import argparse import subprocess from azure.identity import AzureDeveloperCliCredential import urllib3 def get_auth_headers(credential): return { "Authorization": "Bearer " + credential.get_token("https://graph.microsoft.com/.default").token } def add_client_secret(credential, app_id): res...
null
33,818
import argparse import subprocess from azure.identity import AzureDeveloperCliCredential import urllib3 def update_azd_env(name, val): subprocess.run(f"azd env set {name} {val}", shell=True)
null
33,819
import argparse import dataclasses import json import os import subprocess import requests import time from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential from azure.identity import AzureCliCredential from azure.search.documents import SearchClient from tqdm ...
null
33,820
import argparse import dataclasses import json import os import subprocess import requests import time from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential from azure.identity import AzureCliCredential from azure.search.documents import SearchClient from tqdm ...
null
33,821
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
null
33,822
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
null
33,823
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
null
33,824
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
null
33,825
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Calculate the estimated resolution for resizing an image while preserving aspect ratio. The function first calculates scaling factors for height and width of the image based on the target height and width. Then, based on the chosen resize mode, it either takes the smaller or the larger scaling factor to estimate the ne...
33,826
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Convert a base64 image into the image type the extension uses
33,827
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Fetch ControlNet processing units from a StableDiffusionProcessing.
33,828
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Fetch a single ControlNet processing unit from ControlNet script arguments. The list must not contain script positional arguments. It must only contain processing units.
33,829
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Fetch the maximum number of allowed ControlNet models.
33,830
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Update the arguments of the ControlNet script in `p.script_args` in place, reading from `cn_units`. `cn_units` and its elements are not modified. You can call this function repeatedly, as many times as you want. Does not update `p.script_args` if any of the folling is true: - ControlNet is not present in `p.scripts` - ...
33,831
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
@Deprecated(Raises assertion error if script_args passed in is Tuple) Update the arguments of the ControlNet script in `script_args` in place, reading from `cn_units`. `cn_units` and its elements are not modified. You can call this function repeatedly, as many times as you want. Does not update `script_args` if any of ...
33,832
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
Fetch the list of available models. Each value is a valid candidate of `ControlNetUnit.model`. Keyword arguments: update -- Whether to refresh the list from disk. (default False)
33,833
from dataclasses import dataclass from enum import Enum from copy import copy from typing import List, Any, Optional, Union, Tuple, Dict import numpy as np from modules import scripts, processing, shared from scripts import global_state from scripts.processor import preprocessor_sliders_config, model_free_preprocessors...
get the detail of all preprocessors including sliders: the slider config in Auto1111 webUI Keyword arguments: alias_names -- Whether to get the module detail with alias names instead of internal keys
33,834
import os import io import cv2 import base64 import requests def generate(url: str, payload: dict, file_suffix: str = ""): response = requests.post(url=url, json=payload).json() if "images" not in response: print(response) else: for i, base64image in enumerate(response["images"]): ...
null
33,835
import os import io import cv2 import base64 import requests def read_image(img_path: str) -> str: img = cv2.imread(img_path) _, bytes = cv2.imencode(".png", img) encoded_image = base64.b64encode(bytes).decode("utf-8") return encoded_image
null
33,836
import os import io import cv2 import base64 import requests def generate(url: str, payload: dict): response = requests.post(url=url, json=payload).json() if "images" not in response: print(response) else: for i, base64image in enumerate(response["images"]): with open(f"{os.path...
null