id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
13,739
import requests import json import re import openai from time import time, sleep from datetime import datetime from halo import Halo import textwrap import yaml def get_messages(bus, layer): url = f'http://127.0.0.1:900/message?bus={bus}&layer={layer}' response = requests.get(url) if response.status_code =...
null
13,740
import requests import json import re import openai from time import time, sleep from datetime import datetime from halo import Halo import textwrap import yaml def format_messages(messages): formatted_messages = [] for message in messages: time = datetime.fromtimestamp(message['timestamp']).strftime('...
null
13,741
import requests import json import re import openai from time import time, sleep from datetime import datetime from halo import Halo import textwrap import yaml def chatbot(conversation, model="gpt-4", temperature=0, max_tokens=2000): try: spinner = Halo(text='Thinking...', spinner='dots') spinner....
null
13,742
import requests import json import re import openai from time import time, sleep from datetime import datetime from halo import Halo import textwrap import yaml def chat_print(text): formatted_lines = [textwrap.fill(line, width=120, initial_indent=' ', subsequent_indent=' ') for line in text.split('\n')] ...
null
13,743
from flask import Flask, request import yaml import time import os import glob def post_message(): message = request.json message['timestamp'] = time.time() with open(f"logs/log_{message['timestamp']}_{message['bus']}_{message['layer']}.yaml", 'w', encoding='utf-8') as file: yaml.dump(message, file...
null
13,744
from flask import Flask, request import yaml import time import os import glob def get_messages(): bus = request.args.get('bus') layer = int(request.args.get('layer')) files = glob.glob('logs/*.yaml') messages = [] for file in files: with open(file, 'r', encoding='utf-8') as f: ...
null
13,745
import sys from typing import Any import loguru logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger(handler: Any = sys.stderr, **kwargs: dict[str, Any]) -> Any` to solve the following problem: Get a logger i...
Get a logger instance. Lanarky uses `loguru` for logging. Args: handler: The handler to use for the logger. Returns: A loguru logger instance.
13,746
import re from typing import Any, Awaitable, Callable from fastapi import Depends from pydantic import BaseModel, create_model from starlette.routing import compile_path from lanarky.events import Events from lanarky.logging import logger from lanarky.utils import model_dump, model_fields from lanarky.websockets import...
Build a factory endpoint for API routes. Args: path: The path for the route. endpoint: openai resource factory function.
13,747
import re from typing import Any, Awaitable, Callable from fastapi import Depends from pydantic import BaseModel, create_model from starlette.routing import compile_path from lanarky.events import Events from lanarky.logging import logger from lanarky.utils import model_dump, model_fields from lanarky.websockets import...
Build a factory endpoint for WebSocket routes. Args: path: The path for the route. endpoint: openai resource factory function.
13,748
from typing import Any, Callable, Optional from fastapi import params from lanarky.utils import model_dump from .resources import OpenAIResource from .utils import create_request_model, create_response_model def model_dump(model: pydantic.BaseModel, **kwargs) -> dict[str, Any]: """Dump a pydantic model to a dictio...
Dependency injection for OpenAI. Args: dependency: a "dependable" resource factory callable. dependency_kwargs: kwargs to pass to resource dependency. use_cache: use_cache parameter of `fastapi.Depends`.
13,749
import re from typing import Any, Awaitable, Callable from fastapi import Depends from langchain.agents import AgentExecutor from langchain.chains.base import Chain from langchain.schema.document import Document from pydantic import BaseModel, create_model from starlette.routing import compile_path from lanarky.adapter...
Build a factory endpoint for API routes. Args: path: The path for the route. endpoint: LangChain instance factory function.
13,750
import re from typing import Any, Awaitable, Callable from fastapi import Depends from langchain.agents import AgentExecutor from langchain.chains.base import Chain from langchain.schema.document import Document from pydantic import BaseModel, create_model from starlette.routing import compile_path from lanarky.adapter...
Build a factory endpoint for WebSocket routes. Args: path: The path for the route. endpoint: LangChain instance factory function.
13,751
from typing import Any, Optional from fastapi.websockets import WebSocket from langchain.callbacks.base import AsyncCallbackHandler from langchain.callbacks.streaming_stdout_final_only import ( FinalStreamingStdOutCallbackHandler, ) from langchain.globals import get_llm_cache from langchain.schema.document import D...
Get token data based on mode. Args: token: The token to use. mode: The stream mode.
13,752
from typing import Any, Callable, Optional from fastapi import params from langchain.chains.base import Chain from lanarky.adapters.langchain.utils import create_request_model, create_response_model from lanarky.utils import model_dump def create_request_model(chain: Chain, prefix: str = "") -> BaseModel: """Creat...
Dependency injection for LangChain. Args: dependency: a "dependable" chain factory callable. dependency_kwargs: kwargs to pass to chain dependency. use_cache: use_cache parameter of `fastapi.Depends`.
13,753
import json import gradio as gr from langchain.chains import RetrievalQA from langchain.chat_models import ChatOpenAI from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores.faiss import FAISS from lanarky import Lanarky from lanarky.adapters.langchain.routing import LangchainAPIRouter from...
null
13,754
import gradio as gr from lanarky import Lanarky from lanarky.adapters.openai.resources import ChatCompletionResource from lanarky.adapters.openai.routing import OpenAIAPIRouter from lanarky.clients import StreamingClient def chat(system: str = "You are a sassy assistant") -> ChatCompletionResource: return ChatCompl...
null
13,755
import sys from fastapi import FastAPI version = f"{sys.version_info.major}.{sys.version_info.minor}" async def read_root(): message = f"Hello world! From FastAPI running on Uvicorn with Gunicorn. Using Python {version}" return {"message": message}
null
13,756
import os import subprocess import sys build_push = os.environ.get("BUILD_PUSH") def process_tag(*, env: dict): use_env = {**os.environ, **env} script = "scripts/test.sh" if build_push: script = "scripts/build-push.sh" return_code = subprocess.call(["bash", script], env=use_env) if return_c...
null
13,757
import os import subprocess import sys environments = [ {"NAME": "latest", "PYTHON_VERSION": "3.11"}, {"NAME": "python3.11", "PYTHON_VERSION": "3.11"}, {"NAME": "python3.10", "PYTHON_VERSION": "3.10"}, {"NAME": "python3.9", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.8", "PYTHON_VERSION": "3.8"}, ...
null
13,758
import torch import traceback import socket import json from scene.cameras import MiniCam host = "127.0.0.1" port = 6009 listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def init(wish_host, wish_port): global host, port, listener host = wish_host port = wish_port listener.bind((host, port))...
null
13,759
import torch import traceback import socket import json from scene.cameras import MiniCam conn = None addr = None listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def try_connect(): global conn, addr, listener try: conn, addr = listener.accept() print(f"\nConnected by {addr}") ...
null
13,760
import torch import traceback import socket import json from scene.cameras import MiniCam conn = None def send(message_bytes, verify): global conn if message_bytes != None: conn.sendall(message_bytes) conn.sendall(len(verify).to_bytes(4, 'little')) conn.sendall(bytes(verify, 'ascii'))
null
13,761
import torch import traceback import socket import json from scene.cameras import MiniCam def read(): global conn messageLength = conn.recv(4) messageLength = int.from_bytes(messageLength, 'little') message = conn.recv(messageLength) return json.loads(message.decode("utf-8")) class MiniCam: def...
null
13,762
import numpy as np import collections import struct def rotmat2qvec(R): Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat K = np.array([ [Rxx - Ryy - Rzz, 0, 0, 0], [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0], [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0], [Ryz - Rzy, Rzx - Rxz, Rxy - Ry...
null
13,763
import numpy as np import collections import struct The provided code snippet includes necessary dependencies for implementing the `read_colmap_bin_array` function. Write a Python function `def read_colmap_bin_array(path)` to solve the following problem: Taken from https://github.com/colmap/colmap/blob/dev/scripts/pyt...
Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py :param path: path to the colmap binary file. :return: nd array with the floating point values in the value
13,764
import os import sys import json from typing import NamedTuple from pathlib import Path import imageio import torch import numpy as np from PIL import Image from plyfile import PlyData, PlyElement from scene.gaussian_model import BasicPointCloud from scene.cameras import MiniCam, Camera from scene.colmap_loader import ...
null
13,765
import os import sys import json from typing import NamedTuple from pathlib import Path import imageio import torch import numpy as np from PIL import Image from plyfile import PlyData, PlyElement from scene.gaussian_model import BasicPointCloud from scene.cameras import MiniCam, Camera from scene.colmap_loader import ...
null
13,766
import os import sys import json from typing import NamedTuple from pathlib import Path import imageio import torch import numpy as np from PIL import Image from plyfile import PlyData, PlyElement from scene.gaussian_model import BasicPointCloud from scene.cameras import MiniCam, Camera from scene.colmap_loader import ...
null
13,767
from zoedepth.utils.misc import count_parameters, parallelize from zoedepth.utils.config import get_config from zoedepth.utils.arg_utils import parse_unknown from zoedepth.trainers.builder import get_trainer from zoedepth.models.builder import build_model from zoedepth.data.data_mono import MixedNYUKITTI import torch.u...
null
13,768
import gradio as gr from zoedepth.utils.misc import colorize from PIL import Image import tempfile def predict_depth(model, image): depth = model.infer_pil(image) return depth def colorize(value, vmin=None, vmax=None, cmap='gray_r', invalid_val=-99, invalid_mask=None, background_color=(128, 128, 128, 255), gam...
null
13,769
import gradio as gr import numpy as np import trimesh from zoedepth.utils.geometry import depth_to_points, create_triangles from functools import partial import tempfile def get_mesh(model, image, keep_edges=False): image.thumbnail((1024,1024)) # limit the size of the input image depth = predict_depth(model, i...
null
13,770
import gradio as gr import numpy as np import trimesh from zoedepth.utils.geometry import create_triangles from functools import partial import tempfile def get_mesh(model, image, keep_edges=False): image.thumbnail((1024,1024)) # limit the size of the image depth = predict_depth(model, image) pts3d = pano_...
null
13,771
from zoedepth.utils.misc import count_parameters, parallelize from zoedepth.utils.config import get_config from zoedepth.utils.arg_utils import parse_unknown from zoedepth.trainers.builder import get_trainer from zoedepth.models.builder import build_model from zoedepth.data.data_mono import DepthDataLoader import torch...
null
13,772
from zoedepth.utils.config import get_config from zoedepth.models.builder import build_model import numpy as np import torch def get_config(model_name, mode='train', dataset=None, **overwrite_kwargs): """Main entry point to get the config for the model. Args: model_name (str): name of the desired mode...
Zoe_M12_N model. This is the version of ZoeDepth that has a single metric head Args: pretrained (bool): If True, returns a model pre-trained on NYU-Depth-V2 midas_model_type (str): Midas model type. Should be one of the models as listed in torch.hub.list("intel-isl/MiDaS"). Default: DPT_BEiT_L_384 config_mode (str): Co...
13,773
from zoedepth.utils.config import get_config from zoedepth.models.builder import build_model import numpy as np import torch def get_config(model_name, mode='train', dataset=None, **overwrite_kwargs): """Main entry point to get the config for the model. Args: model_name (str): name of the desired mode...
Zoe_M12_K model. This is the version of ZoeDepth that has a single metric head Args: pretrained (bool): If True, returns a model pre-trained on NYU-Depth-V2 midas_model_type (str): Midas model type. Should be one of the models as listed in torch.hub.list("intel-isl/MiDaS"). Default: DPT_BEiT_L_384 config_mode (str): Co...
13,774
from zoedepth.utils.config import get_config from zoedepth.models.builder import build_model import numpy as np import torch def get_config(model_name, mode='train', dataset=None, **overwrite_kwargs): """Main entry point to get the config for the model. Args: model_name (str): name of the desired mode...
ZoeDepthNK model. This is the version of ZoeDepth that has two metric heads and uses a learned router to route to experts. Args: pretrained (bool): If True, returns a model pre-trained on NYU-Depth-V2 midas_model_type (str): Midas model type. Should be one of the models as listed in torch.hub.list("intel-isl/MiDaS"). D...
13,776
import os import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class DDAD(Dataset): def __init__(self, data_dir_root, resize_shape): import glob # image paths are of the form <data_dir_root>/{outleft, depthmap}/*.pn...
null
13,783
import glob import os import h5py import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class HyperSim(Dataset): def __init__(self, data_dir_root): def __getitem__(self, idx): def __len__(self): def get_hypersim_loader(d...
null
13,801
import json import os from zoedepth.utils.easydict import EasyDict as edict from zoedepth.utils.arg_utils import infer_type import pathlib import platform DATASETS_CONFIG = { "kitti": { "dataset": "kitti", "min_depth": 0.001, "max_depth": 80, "data_path": os.path.join(HOME_DIR, "shor...
null
13,803
from scipy import ndimage import base64 import math import re from io import BytesIO import matplotlib import matplotlib.cm import numpy as np import requests import torch import torch.distributed as dist import torch.nn import torch.nn as nn import torch.utils.data.distributed from PIL import Image from torchvision.tr...
null
13,804
from scipy import ndimage import base64 import math import re from io import BytesIO import matplotlib import matplotlib.cm import numpy as np import requests import torch import torch.distributed as dist import torch.nn import torch.nn as nn import torch.utils.data.distributed from PIL import Image from torchvision.tr...
null
13,808
import argparse from pprint import pprint import torch from zoedepth.utils.easydict import EasyDict as edict from tqdm import tqdm from zoedepth.data.data_mono import DepthDataLoader from zoedepth.models.builder import build_model from zoedepth.utils.arg_utils import parse_unknown from zoedepth.utils.config import chan...
null
13,809
import argparse from pprint import pprint import torch from zoedepth.utils.easydict import EasyDict as edict from tqdm import tqdm from zoedepth.data.data_mono import DepthDataLoader from zoedepth.models.builder import build_model from zoedepth.utils.arg_utils import parse_unknown from zoedepth.utils.config import chan...
null
13,810
from errno import EEXIST from os import makedirs, path import os def mkdir_p(folder_path): # Creates a directory. equivalent to using mkdir -p on the command line try: makedirs(folder_path) except OSError as exc: # Python >2.5 if exc.errno == EEXIST and path.isdir(folder_path): ...
null
13,811
from errno import EEXIST from os import makedirs, path import os def searchForMaxIteration(folder): saved_iters = [int(fname.split("_")[-1]) for fname in os.listdir(folder)] return max(saved_iters)
null
13,812
import json import numpy as np import torch from scene.cameras import Camera, MiniCam from utils.general import PILtoTorch from utils.graphics import fov2focal, focal2fov, getWorld2View, getProjectionMatrix class MiniCam: def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_t...
null
13,813
import json import numpy as np import torch from scene.cameras import Camera, MiniCam from utils.general import PILtoTorch from utils.graphics import fov2focal, focal2fov, getWorld2View, getProjectionMatrix def loadCam(args, id, cam_info, resolution_scale): orig_w, orig_h = cam_info.image.size if args.resolutio...
null
13,814
import json import numpy as np import torch from scene.cameras import Camera, MiniCam from utils.general import PILtoTorch from utils.graphics import fov2focal, focal2fov, getWorld2View, getProjectionMatrix class Camera(nn.Module): def __init__(self, colmap_id, R, T, FoVx, FoVy, image, gt_alpha_mask, ...
null
13,815
import matplotlib import matplotlib.cm import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `colorize` function. Write a Python function `def colorize(value, vmin=None, vmax=None, cmap='jet', invalid_val=-99, invalid_mask=None, background_color=(128, 128, 128, ...
Converts a depth map to a color image. Args: value (torch.Tensor, numpy.ndarry): Input depth map. Shape: (H, W) or (1, H, W) or (1, 1, H, W). All singular dimensions are squeezed vmin (float, optional): vmin-valued entries are mapped to start color of cmap. If None, value.min() is used. Defaults to None. vmax (float, o...
13,816
import torch def mse(img1, img2): return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True) def psnr(img1, img2): mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True) return 20 * torch.log10(1.0 / torch.sqrt(mse))
null
13,817
from math import exp import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 with torch.no_grad(): kernelsize=3 conv = torch.nn.Conv2d(1, 1, kernel_size=kernelsize, padding=(kernelsize//2)) kernel = torch.tensor([[0.,1.,0.],[1.,0.,1.],[0.,1.,0.]]).resha...
null
13,818
from math import exp import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 def l2_loss(network_output, gt): return ((network_output - gt) ** 2).mean()
null
13,819
from math import exp import torch import torch.nn.functional as F from torch.autograd import Variable def create_window(window_size, channel): _1D_window = gaussian(window_size, 1.5).unsqueeze(1) _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) window = Variable(_2D_window.expand...
null
13,820
from math import exp import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 with torch.no_grad(): kernelsize=3 conv = torch.nn.Conv2d(1, 1, kernel_size=kernelsize, padding=(kernelsize//2)) kernel = torch.tensor([[0.,1.,0.],[1.,0.,1.],[0.,1.,0.]]).resha...
image: (H, W, 3)
13,821
from math import exp import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 with torch.no_grad(): kernelsize=3 conv = torch.nn.Conv2d(1, 1, kernel_size=kernelsize, padding=(kernelsize//2)) kernel = torch.tensor([[0.,1.,0.],[1.,0.,1.],[0.,1.,0.]]).resha...
array: (H,W) / mask: (H,W)
13,822
import os import numpy as np import torch def generate_seed(scale, viewangle): # World 2 Camera #### rotate x,y render_poses = [np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0]])] ang = 5 for i,j in zip([ang,2*ang,3*ang,2*ang,ang,0,-ang,-2*ang,-3*ang,-2*ang,-ang,0,ang,2*ang,3*ang,2*ang,ang,0], [0,0,0,ang,2*...
null
13,823
import os import numpy as np import torch def generate_seed_360_half(viewangle, n_views): N = n_views // 2 halfangle = viewangle / 2 render_poses = np.zeros((N*2, 3, 4)) for i in range(N): th = (halfangle/N)*i/180*np.pi render_poses[i,:3,:3] = np.array([[np.cos(th), 0, np.sin(th)], [0,...
null
13,824
import os import numpy as np import torch def generate_seed_hemisphere_(degree, nviews): # thlist = np.array([degree, 0, 0, 0, -degree]) # philist = np.array([0, -degree, 0, degree, 0]) thlist = degree * np.sin(np.linspace(0, 2*np.pi, nviews)) philist = degree * np.cos(np.linspace(0, 2*np.pi, nviews)) ...
null
13,825
import os import numpy as np import torch def generate_seed_nothing(): degree = 5 thlist = np.array([0]) philist = np.array([0]) assert len(thlist) == len(philist) render_poses = np.zeros((len(thlist), 3, 4)) for i in range(len(thlist)): th = thlist[i] phi = philist[i] ...
null
13,826
import os import numpy as np import torch def generate_seed_lookaround(): degsum = 60 thlist = np.concatenate((np.linspace(0, degsum, 4), np.linspace(0, -degsum, 4)[1:], np.linspace(0, degsum, 4), np.linspace(0, -degsum, 4)[1:], np.linspace(0, degsum, 4), np.linspace(0, -degsum, 4)[1:])) philist = np.conc...
null
13,827
import os import numpy as np import torch def generate_seed_lookdown(): degsum = 60 thlist = np.concatenate((np.linspace(0, degsum, 4), np.linspace(0, -degsum, 4)[1:], np.linspace(0, degsum, 4), np.linspace(0, -degsum, 4)[1:])) philist = np.concatenate((np.linspace(0,0,7), np.linspace(-22.5,-22.5,7))) ...
null
13,828
import os import numpy as np import torch def generate_seed_headbanging_circle(maxdeg, nviews_per_round, round=3, fullround=1): radius = np.concatenate((np.linspace(0, maxdeg, nviews_per_round*round), maxdeg*np.ones(nviews_per_round*fullround), np.linspace(maxdeg, 0, nviews_per_round*round))) thlist = 2.66*ra...
null
13,829
import os import numpy as np import torch def generate_seed_360(viewangle, n_views): N = n_views render_poses = np.zeros((N, 3, 4)) for i in range(N): th = (viewangle/N)*i/180*np.pi render_poses[i,:3,:3] = np.array([[np.cos(th), 0, np.sin(th)], [0, 1, 0], [-np.sin(th), 0, np.cos(th)]]) ...
null
13,830
import math from typing import NamedTuple import numpy as np import torch def geom_transform_points(points, transf_matrix): P, _ = points.shape ones = torch.ones(P, 1, dtype=points.dtype, device=points.device) points_hom = torch.cat([points, ones], dim=1) points_out = torch.matmul(points_hom, transf_ma...
null
13,831
import sys import random from datetime import datetime import numpy as np import torch def inverse_sigmoid(x): return torch.log(x/(1-x))
null
13,832
import sys import random from datetime import datetime import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `get_expon_lr_func` function. Write a Python function `def get_expon_lr_func( lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=10000...
Copied from Plenoxels Continuous learning rate decay function. Adapted from JaxNeRF The returned rate is lr_init when step=0 and lr_final when step=max_steps, and is log-linearly interpolated elsewhere (equivalent to exponential decay). If lr_delay_steps>0 then the learning rate will be scaled by some smooth function o...
13,833
import sys import random from datetime import datetime import numpy as np import torch def strip_lowerdiag(L): def strip_symmetric(sym): return strip_lowerdiag(sym)
null
13,834
import sys import random from datetime import datetime import numpy as np import torch def build_rotation(r): def build_scaling_rotation(s, r): L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device="cuda") R = build_rotation(r) L[:,0,0] = s[:,0] L[:,1,1] = s[:,1] L[:,2,2] = s[:,2] L =...
null
13,835
import sys import random from datetime import datetime import numpy as np import torch def safe_state(silent): old_f = sys.stdout class F: def __init__(self, silent): self.silent = silent def write(self, x): if not self.silent: if x.endswith("\n"): ...
null
13,836
import torch C0 = 0.28209479177387814 C1 = 0.4886025119029199 C2 = [ 1.0925484305920792, -1.0925484305920792, 0.31539156525252005, -1.0925484305920792, 0.5462742152960396 ] C3 = [ -0.5900435899266435, 2.890611442640554, -0.4570457994644658, 0.3731763325901154, -0.4570457994644658...
Evaluate spherical harmonics at unit directions using hardcoded SH polynomials. Works with torch/np/jnp. ... Can be 0 or more batch dimensions. Args: deg: int SH deg. Currently, 0-3 supported sh: jnp.ndarray SH coeffs [..., C, (deg + 1) ** 2] dirs: jnp.ndarray unit directions [..., 3] Returns: [..., C]
13,837
import torch C0 = 0.28209479177387814 def RGB2SH(rgb): return (rgb - 0.5) / C0
null
13,838
import os import sys import hashlib import logging from typing import Union from urllib.parse import urlparse import numpy as np import torch from torch.hub import download_url_to_file, get_dir def handle_error(model_path: str, model_md5: str, e: str) -> None: _md5 = md5sum(model_path) if _md5 != model_md5: ...
null
13,839
import os import sys import hashlib import logging from typing import Union from urllib.parse import urlparse import numpy as np import torch from torch.hub import download_url_to_file, get_dir def norm_img(np_img: np.ndarray) -> np.ndarray: if len(np_img.shape) == 2: np_img = np_img[:, :, np.newaxis] ...
null
13,840
import os import sys import hashlib import logging from typing import Union from urllib.parse import urlparse import numpy as np import torch from torch.hub import download_url_to_file, get_dir def ceil_modulo(x: int, mod: int) -> int: def pad_img_to_modulo(img: np.ndarray, mod: int) -> np.ndarray: if len(img.shap...
null
13,841
import os from setuptools import setup, find_packages def version() -> str: with open(os.path.join(os.path.dirname(__file__), 'stable_whisper/_version.py')) as f: return f.read().split('=')[-1].strip().strip('"').strip("'")
null
13,842
import os from setuptools import setup, find_packages def read_me() -> str: with open('README.md', 'r', encoding='utf-8') as f: return f.read()
null
13,843
from typing import Optional, Union import numpy as np import torch from ..audio import convert_demucs_kwargs, prep_audio from ..non_whisper import transcribe_any from ..utils import isolate_useful_options HF_MODELS = { "tiny.en": "openai/whisper-tiny.en", "tiny": "openai/whisper-tiny", "base.en": "openai/wh...
null
13,844
import os import warnings import argparse from typing import Optional, List, Union from os.path import splitext, split, join import numpy as np import torch from ..result import WhisperResult from ..utils import isolate_useful_options, str_to_valid_type, get_func_parameters from ..audio import SUPPORTED_DENOISERS from ...
null
13,845
import warnings import re import torch import numpy as np from typing import Union, List, Tuple, Optional, Callable from copy import deepcopy from itertools import chain from tqdm import tqdm from .stabilization import suppress_silence, get_vad_silence_func, VAD_SAMPLE_RATES from .stabilization.nonvad import audio2timi...
null
13,846
import warnings import re import torch import numpy as np from typing import Union, List, Tuple, Optional, Callable from copy import deepcopy from itertools import chain from tqdm import tqdm from .stabilization import suppress_silence, get_vad_silence_func, VAD_SAMPLE_RATES from .stabilization.nonvad import audio2timi...
null
13,847
import warnings import re import torch import numpy as np from typing import Union, List, Tuple, Optional, Callable from copy import deepcopy from itertools import chain from tqdm import tqdm from .stabilization import suppress_silence, get_vad_silence_func, VAD_SAMPLE_RATES from .stabilization.nonvad import audio2timi...
null
13,848
import warnings import re import torch import numpy as np from typing import Union, List, Tuple, Optional, Callable from copy import deepcopy from itertools import chain from tqdm import tqdm from .stabilization import suppress_silence, get_vad_silence_func, VAD_SAMPLE_RATES from .stabilization.nonvad import audio2timi...
Return a nested list of words such that each sublist contains words that are locked together.
13,849
import subprocess import warnings from typing import Union, Optional, BinaryIO, Tuple, Iterable import numpy as np import torch import torchaudio from whisper.audio import SAMPLE_RATE def audio_to_tensor_resample( audio: Union[torch.Tensor, np.ndarray, str, bytes], original_sample_rate: Optional[int] = ...
null
13,850
import random from typing import Union, Optional import torch from .utils import load_audio from ..audio.utils import resample from ..default import cached_model_instances def load_demucs_model(cache: bool = True): model_name = 'htdemucs' _model_cache = cached_model_instances['demucs'] if cache else None if...
Isolates vocals / remove noise from ``audio`` with Demucs. Official repo, https://github.com/facebookresearch/demucs.
13,851
from typing import Union, Optional import torch from .utils import load_audio from ..audio.utils import resample from ..default import cached_model_instances def load_dfnet_model(cache: bool = True, **kwargs): model_name = 'dfnet' _model_cache = cached_model_instances['dfnet'] if cache else None if _model_c...
Remove noise from ``audio`` with DeepFilterNet. Official repo: https://github.com/Rikorose/DeepFilterNet.
13,852
import os from typing import Optional def set_val(key: str, val): has_key(key) DEFAULT_KWARGS[key] = val def get_val(key: str, default=None): if default is None: has_key(key) return DEFAULT_KWARGS[key] return default def set_get_val(key: str, new_val=None): if new_val is not None: ...
null
13,853
from typing import Tuple import numpy as np import torch from torch.nn import functional as F from .utils import mask2timing, timing2mask from ..audio.utils import audio_to_tensor_resample from whisper.audio import N_SAMPLES_PER_TOKEN def wav2mask( audio: (torch.Tensor, np.ndarray, str, bytes), q_levels...
null
13,854
from typing import Tuple import numpy as np import torch from torch.nn import functional as F from .utils import mask2timing, timing2mask from ..audio.utils import audio_to_tensor_resample from whisper.audio import N_SAMPLES_PER_TOKEN def visualize_mask( loudness_tensor: torch.Tensor, silence_mask: tor...
null
13,855
import warnings from typing import Optional, List import torch from tqdm import tqdm from .utils import SetTorchThread from ..default import cached_model_instances cached_model_instances = dict( demucs={ 'htdemucs': None }, silero_vad={ True: None, False: None }, dfnet={ ...
null
13,856
import warnings from typing import Optional, List import torch from tqdm import tqdm from .utils import SetTorchThread from ..default import cached_model_instances class SetTorchThread: def __init__(self, temp_thread_count: int): self.original_thread_count = torch.get_num_threads() self.temp_thread...
null
13,857
import warnings from typing import Optional, List import torch from tqdm import tqdm from .utils import SetTorchThread from ..default import cached_model_instances VAD_SAMPLE_RATES = (16000, 8000) VAD_WINDOWS = (256, 512, 768, 1024, 1536) def assert_sr_window(sr: int, window: int): assert sr in VAD_SAMPLE_RATES, f...
null
13,858
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts def segment2vttblock(segment: dict, strip=True) -> str: return f'{sec2vtt(segment["start"])} --> {sec2vtt(segment["end"])}\n' \ f'{finalize_text(segm...
Generate SRT/VTT from ``result`` to display segment-level and/or word-level timestamp. Parameters ---------- result : dict or list or stable_whisper.result.WhisperResult Result of transcription. filepath : str, default None, meaning content will be returned as a ``str`` Path to save file. segment_level : bool, default ...
13,859
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts def segment2tsvblock(segment: dict, strip=True) -> str: return f'{sec2milliseconds(segment["start"])}' \ f'\t{sec2milliseconds(segment["end"])}' \ ...
Generate TSV from ``result`` to display segment-level and/or word-level timestamp. Parameters ---------- result : dict or list or stable_whisper.result.WhisperResult Result of transcription. filepath : str, default None, meaning content will be returned as a ``str`` Path to save file. segment_level : bool, default True...
13,860
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts def segment2assblock(segment: dict, idx: int, strip=True) -> str: return f'Dialogue: {idx},{sec2ass(segment["start"])},{sec2ass(segment["end"])},Default,,0,0,0,...
Generate Advanced SubStation Alpha (ASS) file from ``result`` to display segment-level and/or word-level timestamp. Parameters ---------- result : dict or list or stable_whisper.result.WhisperResult Result of transcription. filepath : str, default None, meaning content will be returned as a ``str`` Path to save file. s...
13,861
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts def result_to_any(result: (dict, list), filepath: str = None, filetype: str = None, segments2blocks: Callable ...
Generate plain-text without timestamps from ``result``. Parameters ---------- result : dict or list or stable_whisper.result.WhisperResult Result of transcription. filepath : str, default None, meaning content will be returned as a ``str`` Path to save file. min_dur : float, default 0.2 Minimum duration allowed for any...
13,862
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts def _save_as_file(content: str, path: str): with open(path, 'w', encoding='utf-8') as f: f.write(content) print(f'Saved: {os.path.abspath(path)}') ...
Save ``result`` as JSON file to ``path``. Parameters ---------- result : dict or list or stable_whisper.result.WhisperResult Result of transcription. path : str Path to save file. ensure_ascii : bool, default False Whether to escape non-ASCII characters. Examples -------- >>> import stable_whisper >>> model = stable_wh...
13,863
import json import os import warnings from typing import List, Tuple, Union, Callable from itertools import chain from .stabilization.utils import valid_ts The provided code snippet includes necessary dependencies for implementing the `load_result` function. Write a Python function `def load_result(json_path: str) -> ...
Return a ``dict`` of the contents in ``json_path``.
13,864
import os import subprocess as sp import warnings from typing import List The provided code snippet includes necessary dependencies for implementing the `encode_video_comparison` function. Write a Python function `def encode_video_comparison( audiofile: str, subtitle_files: List[str], output_vi...
Encode multiple subtitle files into one video with the subtitles vertically stacked. Parameters ---------- audiofile : str Path of audio file. subtitle_files : list of str List of paths for subtitle file. output_videopath : str, optional Output video path. labels : list of str, default, None, meaning use ``subtitle_fil...
13,865
from typing import TYPE_CHECKING, List, Union from dataclasses import replace import torch import numpy as np from whisper.decoding import DecodingTask, DecodingOptions, DecodingResult def _suppress_ts(ts_logits: torch.Tensor, ts_token_mask: torch.Tensor = None): if ts_token_mask is not None: ts_logits[:, ...
null
13,866
from features import SignalGenerator, dilated_factor from scipy.interpolate import interp1d import torch import numpy as np import json import os def convert_continuos_f0(f0, f0_size): # get start and end of f0 if (f0 == 0).all(): return np.zeros((f0_size,)) start_f0 = f0[f0 != 0][0] end_f0 = f...
null