id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
151,261
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def draw_e2e_res(dt_boxes, strs, img_path): src_im = cv2.imread(img_path) ...
null
151,262
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def draw_text_det_res(dt_boxes, img_path): src_im = cv2.imread(img_path) f...
null
151,263
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def resize_img(img, input_size=600): """ resize img and limit the longest s...
Visualize the results of OCR detection and recognition args: image(Image|array): RGB image boxes(list): boxes with shape(N, 4, 2) txts(list): the texts scores(list): txxs corresponding scores drop_score(float): only scores greater than drop_threshold will be visualized font_path: the path of font which is used to draw ...
151,264
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def draw_ocr_box_txt(image, boxes, txts,...
null
151,265
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def base64_to_cv2(b64str): import base64 data = base64.b64decode(b64str.en...
null
151,266
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def draw_boxes(image, boxes, scores=None, drop_score=0.5): if scores is None: ...
null
151,267
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger The provided code snippet includes necessary dependencies for implementing the `ge...
img_height, img_width = img.shape[0:2] left = int(np.min(points[:, 0])) right = int(np.max(points[:, 0])) top = int(np.min(points[:, 1])) bottom = int(np.max(points[:, 1])) img_crop = img[top:bottom, left:right, :].copy() points[:, 0] = points[:, 0] - left points[:, 1] = points[:, 1] - top
151,268
import argparse import os import sys import platform import cv2 import numpy as np import paddle from PIL import Image, ImageDraw, ImageFont import math from paddle import inference import time from ppocr.utils.logging import get_logger def check_gpu(use_gpu): if use_gpu and not paddle.is_compiled_with_cuda(): ...
null
151,269
import os import sys import subprocess import cv2 import copy import numpy as np import json import time import logging from PIL import Image import tools.infer.utility as utility import tools.infer.predict_rec as predict_rec import tools.infer.predict_det as predict_det import tools.infer.predict_cls as predict_cls fr...
Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2]
151,270
import os video_extensions = { '.mp4', '.m4a', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '.3gp2', '.3g2', '.3gpp', '.3gpp2', '.ogg', '.oga', '.ogv', '.ogx', '.wmv', '.wma', '.asf', '.webm', '.flv', '.avi', '.gifv', '.mkv', '.rm', '.rmvb', '.vob', '.dvd', '.mpg', '.mpeg', '.mp2', '....
null
151,271
import os image_extensions = { '.jpg', '.jpeg', '.jpe', '.jif', '.jfif', '.jfi', '.png', '.gif', '.webp', '.tiff', '.tif', '.psd', '.raw', '.arw', '.cr2', '.nrw', '.k25', '.bmp', '.dib', '.heif', '.heic', '.ind', '.indd', '.indt', '.jp2', '.j2k', '.jpf', '.jpx', '.jpm', '.mj2', '.svg', '.svgz', '.ai...
null
151,272
import os video_extensions = { '.mp4', '.m4a', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '.3gp2', '.3g2', '.3gpp', '.3gpp2', '.ogg', '.oga', '.ogv', '.ogx', '.wmv', '.wma', '.asf', '.webm', '.flv', '.avi', '.gifv', '.mkv', '.rm', '.rmvb', '.vob', '.dvd', '.mpg', '.mpeg', '.mp2', '....
null
151,273
import os import matplotlib.patches as patches from matplotlib.path import Path import io import cv2 import random import zipfile import numpy as np from PIL import Image, ImageOps import torch import matplotlib from matplotlib import pyplot as plt def get_random_shape(edge_num=9, ratio=0.7, width=432, height=240): ...
null
151,274
import os import matplotlib.patches as patches from matplotlib.path import Path import io import cv2 import random import zipfile import numpy as np from PIL import Image, ImageOps import torch import matplotlib from matplotlib import pyplot as plt The provided code snippet includes necessary dependencies for implemen...
Find OMPI world size without calling mpi functions :rtype: int
151,275
import os import matplotlib.patches as patches from matplotlib.path import Path import io import cv2 import random import zipfile import numpy as np from PIL import Image, ImageOps import torch import matplotlib from matplotlib import pyplot as plt The provided code snippet includes necessary dependencies for implemen...
Find OMPI world rank without calling mpi functions :rtype: int
151,276
import os import matplotlib.patches as patches from matplotlib.path import Path import io import cv2 import random import zipfile import numpy as np from PIL import Image, ImageOps import torch import matplotlib from matplotlib import pyplot as plt The provided code snippet includes necessary dependencies for implemen...
Find OMPI local rank without calling mpi functions :rtype: int
151,277
import os import matplotlib.patches as patches from matplotlib.path import Path import io import cv2 import random import zipfile import numpy as np from PIL import Image, ImageOps import torch import matplotlib from matplotlib import pyplot as plt def get_master_ip(): if os.environ.get('AZ_BATCH_MASTER_NODE') is ...
null
151,278
import os import json import random import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader from backend.tools.train.utils_sttn import ZipReader, create_random_shape_with_random_motion from backend.tools.train.utils_sttn import Stack, ToTorchFormatTensor, GroupRandomHorizontalFl...
null
151,279
import os import json import argparse from shutil import copyfile import torch import torch.multiprocessing as mp from backend.tools.train.trainer_sttn import Trainer from backend.tools.train.utils_sttn import ( get_world_size, get_local_rank, get_global_rank, get_master_ip, ) args = parser.parse_args()...
null
151,280
import multiprocessing import cv2 import numpy as np from backend import config from backend.inpaint.lama_inpaint import LamaInpaint def inpaint(img, mask): lama_inpaint_instance = LamaInpaint() img_inpainted = lama_inpaint_instance(img, mask) return img_inpainted def inpaint_with_multiple_masks(censored_i...
null
151,281
import multiprocessing import cv2 import numpy as np from backend import config from backend.inpaint.lama_inpaint import LamaInpaint def parallel_inference(inputs, batch_size=None, pool_size=None): """ 并行推理,同时保持结果顺序 """ if pool_size is None: pool_size = multiprocessing.cpu_count() # 使用上下文管理器...
null
151,282
import cv2 The provided code snippet includes necessary dependencies for implementing the `merge_video` function. Write a Python function `def merge_video(video_input_path0, video_input_path1, video_output_path)` to solve the following problem: 将两个视频文件安装水平方向合并 Here is the function: def merge_video(video_input_path0,...
将两个视频文件安装水平方向合并
151,283
import base64 import os import platform import pprint import time import warnings from contextlib import redirect_stdout from io import BytesIO import requests from ...utils.lazy_import import lazy_import from ..utils.recipient_utils import format_to_recipient from ..utils.computer_vision import find_text_in_image, pyt...
null
151,284
import hashlib import io import os import subprocess from typing import List import cv2 import nltk import numpy as np import torch from PIL import Image, ImageDraw, ImageEnhance, ImageFont from sentence_transformers import SentenceTransformer, util from .....terminal_interface.utils.oi_dir import oi_dir from ...utils....
null
151,285
from concurrent.futures import ThreadPoolExecutor import tiktoken def split_into_chunks(text, tokens, llm, overlap): try: encoding = tiktoken.encoding_for_model(llm.model) tokenized_text = encoding.encode(text) chunks = [] for i in range(0, len(tokenized_text), tokens - overlap): ...
null
151,286
from concurrent.futures import ThreadPoolExecutor import tiktoken def fast_llm(llm, system_message, user_message): old_messages = llm.interpreter.messages old_system_message = llm.interpreter.system_message try: llm.interpreter.system_message = system_message llm.interpreter.messages = [] ...
Query the chunks of text using query_chunk_map.
151,287
from concurrent.futures import ThreadPoolExecutor import tiktoken def chunk_responses(responses, tokens, llm): try: encoding = tiktoken.encoding_for_model(llm.model) chunked_responses = [] current_chunk = "" current_tokens = 0 for response in responses: tokenized_...
Reduce query responses in a while loop.
151,288
import difflib from ...utils.lazy_import import lazy_import The provided code snippet includes necessary dependencies for implementing the `get_close_matches_in_text` function. Write a Python function `def get_close_matches_in_text(original_text, filedata, n=3)` to solve the following problem: Returns the closest matc...
Returns the closest matches to the original text in the content of the file.
151,289
import os import platform import shutil from .subprocess_language import SubprocessLanguage def add_active_line_prints(code): """ Add Write-Output statements indicating line numbers to a PowerShell script. """ lines = code.split("\n") for index, line in enumerate(lines): # Insert the Write-O...
Add active line markers Wrap in try-catch block Add end of execution marker
151,290
import ast import os import queue import re import threading import time import traceback from jupyter_client import KernelManager from ..base_language import BaseLanguage def add_active_line_prints(code): """ Add print statements indicating line numbers to a python string. """ # Replace newlines and co...
Add active line markers Wrap in a try except
151,291
import ast import os import queue import re import threading import time import traceback from jupyter_client import KernelManager from ..base_language import BaseLanguage def wrap_in_try_except(code): # Add import traceback code = "import traceback\n" + code # Parse the input code into an AST parsed_...
null
151,292
import ast import os import queue import re import threading import time import traceback from jupyter_client import KernelManager from ..base_language import BaseLanguage def string_to_python(code_as_string): parsed_code = ast.parse(code_as_string) # Initialize containers for different categories import_...
null
151,293
import os import platform import re from .subprocess_language import SubprocessLanguage def add_active_line_prints(code): """ Add echo statements indicating line numbers to a shell string. """ lines = code.split("\n") for index, line in enumerate(lines): # Insert the echo command before the ...
Add active line markers Wrap in a try except (trap in shell) Add end of execution marker
151,294
import ast import os import re import shlex import sys from .subprocess_language import SubprocessLanguage def add_active_line_prints(code): """ Add print statements indicating line numbers to a python string. """ tree = ast.parse(code) transformer = AddLinePrints() new_tree = transformer.visit(...
Add active line markers Wrap in a try except Add end of execution marker
151,295
import re from .subprocess_language import SubprocessLanguage The provided code snippet includes necessary dependencies for implementing the `preprocess_javascript` function. Write a Python function `def preprocess_javascript(code)` to solve the following problem: Add active line markers Wrap in a try catch Add end of...
Add active line markers Wrap in a try catch Add end of execution marker
151,296
import re from ...utils.html_to_png_base64 import html_to_png_base64 from ..base_language import BaseLanguage def is_incompatible(code): lines = code.split("\n") # Check for require statements at the start of any of the first few lines # Check for ES6 import/export statements for line in lines[:5]: ...
null
151,297
import time import warnings from ...utils.lazy_import import lazy_import from ..utils.recipient_utils import format_to_recipient pyautogui = lazy_import("pyautogui") import math import time def smooth_move_to(x, y, duration=2): start_x, start_y = pyautogui.position() dx = x - start_x dy = y - start_y d...
null
151,298
import subprocess The provided code snippet includes necessary dependencies for implementing the `run_applescript` function. Write a Python function `def run_applescript(script)` to solve the following problem: Runs the given AppleScript using osascript and returns the result. Here is the function: def run_applescri...
Runs the given AppleScript using osascript and returns the result.
151,299
import subprocess The provided code snippet includes necessary dependencies for implementing the `run_applescript_capture` function. Write a Python function `def run_applescript_capture(script)` to solve the following problem: Runs the given AppleScript using osascript, captures the output and error, and returns them....
Runs the given AppleScript using osascript, captures the output and error, and returns them.
151,300
def format_to_recipient(text, recipient): return f"@@@RECIPIENT:{recipient}@@@CONTENT:{text}@@@END"
null
151,301
def parse_for_recipient(content): if content.startswith("@@@RECIPIENT:") and "@@@END" in content: parts = content.split("@@@") recipient = parts[1].split(":")[1] new_content = parts[2].split(":")[1] return recipient, new_content return None, content
null
151,302
import base64 import os import random import string from html2image import Html2Image from ....terminal_interface.utils.local_storage_path import get_storage_path def html_to_png_base64(code): # Convert the HTML into an image using html2image hti = Html2Image() # Generate a random filename for the tempora...
null
151,303
import platform import sys def get_active_window(): if platform.system() == "Windows": import pygetwindow as gw win = gw.getActiveWindow() if win is not None: return { "region": (win.left, win.top, win.width, win.height), "title": win.title, ...
null
151,304
import io from ...utils.lazy_import import lazy_import np = lazy_import("numpy") cv2 = lazy_import("cv2") pytesseract = lazy_import("pytesseract") def pytesseract_get_text(img): # Convert PIL Image to NumPy array img_array = np.array(img) # Convert the image to grayscale gray = cv2.cvtColor(img_array,...
null
151,305
def run_text_llm(llm, params): ## Setup try: # Add the system message params["messages"][0][ "content" ] += "\nTo execute code on the user's machine, write a markdown code block. Specify the language after the ```. You will receive the output. Use any programming language....
null
151,306
import litellm import tokentrim as tt from ...terminal_interface.utils.display_markdown_message import ( display_markdown_message, ) from .run_function_calling_llm import run_function_calling_llm from .run_text_llm import run_text_llm from .utils.convert_to_openai_messages import convert_to_openai_messages litellm....
Just uses a dummy API key, since we use litellm without an API key sometimes. Hopefully they will fix this!
151,307
from .utils.merge_deltas import merge_deltas from .utils.parse_partial_json import parse_partial_json function_schema = { "name": "execute", "description": "Executes code on the user's machine **in the users local environment** and returns the output", "parameters": { "type": "object", "prop...
null
151,308
import asyncio import json from typing import Generator import uvicorn from fastapi import Body, FastAPI, Request, Response, WebSocket from fastapi.responses import PlainTextResponse, StreamingResponse def server(interpreter, host="0.0.0.0", port=8000): app = FastAPI() @app.post("/chat") async def stream_...
null
151,309
import json import re import traceback import litellm from ..terminal_interface.utils.display_markdown_message import display_markdown_message from .render_message import render_message def display_markdown_message(message): """ Display markdown message. Works with multiline strings with lots of indentation. ...
Yields chunks. Responds until it decides not to run any more code or say anything else.
151,310
import traceback from .rag.get_relevant_procedures_string import get_relevant_procedures_string from .utils.OLD_get_user_info_string import get_user_info_string def extend_system_message(interpreter): #### Start with the static system message system_message = interpreter.system_message #### Add dynamic c...
null
151,311
import platform import subprocess import pkg_resources import psutil import toml def get_package_mismatches(file_path="pyproject.toml"): with open(file_path, "r") as file: pyproject = toml.load(file) dependencies = pyproject["tool"]["poetry"]["dependencies"] dev_dependencies = pyproject["tool"]["po...
null
151,312
import contextlib import os import uuid import pkg_resources from posthog import Posthog def get_or_create_uuid(): try: uuid_file_path = os.path.join( os.path.expanduser("~"), ".cache", "open-interpreter", "telemetry_user_id" ) os.makedirs( os.path.dirname(uuid_file_...
null
151,313
import contextlib import os import uuid import pkg_resources from posthog import Posthog posthog = Posthog( "phc_6cmXy4MEbLfNGezqGjuUTY8abLu0sAwtGzZFpQW97lc", host="https://app.posthog.com" ) user_id = get_or_create_uuid() def send_telemetry(event_name, properties=None): try: if properties == None: ...
null
151,314
import importlib.util import sys The provided code snippet includes necessary dependencies for implementing the `lazy_import` function. Write a Python function `def lazy_import(name, optional=True)` to solve the following problem: Lazily import a module, specified by the name. Useful for optional packages, to speed up...
Lazily import a module, specified by the name. Useful for optional packages, to speed up startup times.
151,315
import getpass import os import platform def get_user_info_string(): username = getpass.getuser() current_working_directory = os.getcwd() operating_system = platform.system() default_shell = os.environ.get("SHELL") return f"[User Info]\nName: {username}\nCWD: {current_working_directory}\nSHELL: {d...
null
151,316
import numpy as np from chromadb.utils.distance_functions import cosine The provided code snippet includes necessary dependencies for implementing the `search` function. Write a Python function `def search(query, db, embed_function, num_results=2)` to solve the following problem: Finds the most similar value from the ...
Finds the most similar value from the embeddings dictionary to the query. query is a string db is of type [{text: embedding}, {text: embedding}, ...] Args: query (str): The query to which you want to find a similar value. Returns: str: The most similar value from the embeddings dictionary.
151,317
import os import numpy as np from chromadb.utils.embedding_functions import DefaultEmbeddingFunction as setup_embed try: chroma_embedding_function = setup_embed() except: # This does set up a model that we don't strictly need. # If it fails, it's not worth breaking everything. pass def embed_function(q...
null
151,318
import requests from ..llm.utils.convert_to_openai_messages import convert_to_openai_messages def convert_to_openai_messages( messages, function_calling=True, vision=False, shrink_images=True ): """ Converts LMC messages into OpenAI messages """ new_messages = [] for message in messages: ...
null
151,319
import requests from ..utils.vector_search import search def get_relevant_procedures_string(interpreter): # Open Procedures is an open-source database of tiny, up-to-date coding tutorials. # We can query it semantically and append relevant tutorials/procedures to our system message # If download_open_proc...
null
151,320
try: import readline except ImportError: pass import os import platform import random import re import subprocess import time from ..core.utils.scan_code import scan_code from ..core.utils.system_debug_info import system_info from ..core.utils.truncate_output import truncate_output from .components.code_block i...
null
151,321
import argparse import sys import time import pkg_resources from ..core.core import OpenInterpreter from .conversation_navigator import conversation_navigator from .profiles.profiles import open_profile_dir, profile, reset_profile from .utils.check_for_update import check_for_update from .utils.display_markdown_message...
Meant to be used from the command line. Parses arguments, starts OI's terminal interface.
151,322
import re from rich.box import MINIMAL from rich.markdown import Markdown from rich.panel import Panel from .base_block import BaseBlock The provided code snippet includes necessary dependencies for implementing the `textify_markdown_code_blocks` function. Write a Python function `def textify_markdown_code_blocks(text...
To distinguish CodeBlocks from markdown code, we simply turn all markdown code (like '```python...') into text code blocks ('```text') which makes the code black and white.
151,323
import os import shutil from importlib import resources import yaml from .local_storage_path import get_storage_path user_config_path = os.path.join(get_storage_path(), config_filename) def get_config_path(path=user_config_path): # check to see if we were given a path that exists if not os.path.exists(path): ...
null
151,324
import string import time import yaml from .display_markdown_message import display_markdown_message from .get_config import get_config, user_config_path def display_markdown_message(message): def apply_config(self, config): if "version" not in config or config["version"] != "0.2.0": print("") pri...
null
151,325
import os from .local_storage_path import get_storage_path def get_storage_path(subdirectory=None): if subdirectory is None: return config_dir else: return os.path.join(config_dir, subdirectory) def get_conversations(): conversations_dir = get_storage_path("conversations") json_files =...
null
151,326
import base64 import time import torch from io import BytesIO from operator import itemgetter from random import randint from typing import Dict, Optional from urllib.request import urlopen import numpy as np from PIL import Image from stable_inference import StableDiffusionInference from stable_inference.util import (...
null
151,327
import random import time from functools import partial import jax import jax.numpy as jnp import numpy as np import wandb from PIL import Image from dalle_mini import DalleBart, DalleBartProcessor from flax.jax_utils import replicate from flax.training.common_utils import shard_prng_key from vqgan_jax.modeling_flax_vq...
null
151,328
import argparse import os import sys import yaml from collections import OrderedDict yaml.add_representer(OrderedDict, represent_ordereddict) The provided code snippet includes necessary dependencies for implementing the `represent_ordereddict` function. Write a Python function `def represent_ordereddict(dumper, data)...
Used to edit the YAML filters in place so that jina doesn't freak out when we use the newly parsed file. Otherwise the new YAML is sorted by keys and that breaks jina.
151,329
import argparse import os import sys import yaml from collections import OrderedDict def _filter_out(flow_exec_list, name): return list(filter(lambda exc: exc['name'] != name, flow_exec_list))
null
151,330
import functools from typing import Dict, Union from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import optim from flax.metrics import tensorboard from flax.training import checkpoints import gin import jax from jax import numpy as jnp from jax import random impo...
Log statistics to Tensorboard.
151,331
import functools from typing import Dict, Union from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import optim from flax.metrics import tensorboard from flax.training import checkpoints import gin import jax from jax import numpy as jnp from jax import random impo...
Log histograms to Tensorboard.
151,332
import functools from typing import Dict, Union from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import optim from flax.metrics import tensorboard from flax.training import checkpoints import gin import jax from jax import numpy as jnp from jax import random impo...
Log histograms to Tensorboard.
151,333
import functools from typing import Any, Callable, Dict from absl import logging import flax from flax import struct from flax import traverse_util from flax.training import checkpoints import jax from jax import lax from jax import numpy as jnp from jax import random from jax import vmap from hypernerf import model_ut...
Save the state to a checkpoint.
151,334
import functools from typing import Any, Callable, Dict from absl import logging import flax from flax import struct from flax import traverse_util from flax.training import checkpoints import jax from jax import lax from jax import numpy as jnp from jax import random from jax import vmap from hypernerf import model_ut...
One optimization step. Args: model: the model module to evaluate. rng_key: The random number generator. state: model_utils.TrainState, state of model and optimizer. batch: dict. A mini-batch of data for training. scalar_params: scalar-valued parameters. disable_hyper_grads: if True disable gradients to the hyper coordi...
151,335
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform def safe_norm(x, axis=-1, k...
Custom JVP rule for safe_norm.
151,336
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform def robust_whiten(x): me...
null
151,337
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Interpolates latent codes. Args: codes: the codes to interpolate. num_samples: the number of samples to interpolate to. method: which method to use for interpolation. bc_type: interpolation type for spline interpolation. Returns: (np.ndarray): the interpolated codes.
151,338
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Interpolates the cameras to the number of output samples. Uses a spherical linear interpolation (Slerp) to interpolate the camera orientations and a cubic spline to interpolate the camera positions. Args: cameras: the input cameras to interpolate. num_samples: the number of output cameras. Returns: (List[vision_sfm.Cam...
151,339
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform def points_bound(points): ...
Computes the centroid of the points from the bounding box.
151,340
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform def points_bound(points): ...
Computes the bounding size of the points from the bounding box.
151,341
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Transfer data to devices (GPU/TPU).
151,342
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Normalization helper function.
151,343
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform def parallel_map(f, iterabl...
Parallel version of jax.tree_map.
151,344
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Returns a strided subset of a list.
151,345
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Collates a list of pytrees with the same structure.
151,346
import collections from concurrent import futures import contextlib import functools import time from typing import List, Union import jax from jax import tree_util import jax.numpy as jnp import numpy as np from scipy import interpolate from scipy.spatial import transform as scipy_transform The provided code snippet ...
Records the time elapsed.
151,347
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types def downsample_image(image: np.ndarray, scale: int) -> np.ndarray: """Downsamples the image by an integer factor to prevent artifacts...
Resize an image by a scale factor, using integer resizing if possible.
151,348
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types def crop_image(image, left=0, right=0, top=0, bottom=0): pad_width = [max(0, -x) for x in [top, bottom, left, right]] if any(pad_w...
null
151,349
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types The provided code snippet includes necessary dependencies for implementing the `variance_of_laplacian` function. Write a Python functi...
Compute the variance of the Laplacian which measure the focus.
151,350
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types def image_to_float32(image: np.ndarray) -> np.ndarray: """Convert the image to a float32 array and scale values appropriately.""" i...
null
151,351
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types The provided code snippet includes necessary dependencies for implementing the `checkerboard` function. Write a Python function `def c...
Creates a checkerboard pattern with height h and width w.
151,352
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types def make_divisible(image: np.ndarray, divisor: int) -> np.ndarray: """Trim the image if not divisible by the divisor.""" height, wi...
Splits the image into tiles of size `tile_size`.
151,353
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types The provided code snippet includes necessary dependencies for implementing the `join_tiles` function. Write a Python function `def joi...
Reconstructs the image from tiles.
151,354
import math from typing import Tuple from absl import logging import cv2 import imageio import numpy as np from PIL import Image from hypernerf import gpath from hypernerf import types The provided code snippet includes necessary dependencies for implementing the `make_grid` function. Write a Python function `def make...
Creates a grid out an image batch. Args: batch: numpy array of shape [batch_size, height, width, n_channels]. The data can either be float in [0, 1] or int in [0, 255]. If the data has only 1 channel it will be converted to a grey 3 channel image. grid_height: optional int, number of rows to have. If not given, it is s...
151,355
from jax import numpy as jnp from jax.numpy import linalg def conjugate(q): """Compute the conjugate of a quaternion.""" return jnp.concatenate([-im(q), re(q)], axis=-1) def normalize(q): """Normalize a quaternion.""" return q / norm(q) The provided code snippet includes necessary dependencies for implementing...
Compute the inverse of a quaternion.
151,356
from jax import numpy as jnp from jax.numpy import linalg def im(q): """Fetch the imaginary part of the quaternion.""" return q[..., :3] def conjugate(q): """Compute the conjugate of a quaternion.""" return jnp.concatenate([-im(q), re(q)], axis=-1) def multiply(q1, q2): """Multiply two quaternions.""" c = (...
Rotate a vector using a quaternion.
151,357
from jax import numpy as jnp from jax.numpy import linalg def safe_acos(t, eps=1e-7): """A safe version of arccos which avoids evaluating at -1 or 1.""" return jnp.arccos(jnp.clip(t, -1.0 + eps, 1.0 - eps)) def im(q): """Fetch the imaginary part of the quaternion.""" return q[..., :3] def re(q): """Fetch the ...
Computes the quaternion logarithm. References: https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions Args: q: the quaternion in (x,y,z,w) format. eps: an epsilon value for numerical stability. Returns: The logarithm of q.
151,358
from jax import numpy as jnp from jax.numpy import linalg def im(q): """Fetch the imaginary part of the quaternion.""" return q[..., :3] def re(q): """Fetch the real part of the quaternion.""" return q[..., 3:] def norm(q): return linalg.norm(q, axis=-1, keepdims=True) The provided code snippet includes nece...
Computes the quaternion exponential. References: https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions Args: q: the quaternion in (x,y,z,w) format or (x,y,z) if is_pure is True. eps: an epsilon value for numerical stability. Returns: The exponential of q.
151,359
from jax import numpy as jnp from jax.numpy import linalg The provided code snippet includes necessary dependencies for implementing the `to_rotation_matrix` function. Write a Python function `def to_rotation_matrix(q)` to solve the following problem: Constructs a rotation matrix from a quaternion. Args: q: a (*,4) ar...
Constructs a rotation matrix from a quaternion. Args: q: a (*,4) array containing quaternions. Returns: A (*,3,3) array containing rotation matrices.
151,360
from jax import numpy as jnp from jax.numpy import linalg The provided code snippet includes necessary dependencies for implementing the `from_rotation_matrix` function. Write a Python function `def from_rotation_matrix(m, eps=1e-9)` to solve the following problem: Construct quaternion from a rotation matrix. Args: m:...
Construct quaternion from a rotation matrix. Args: m: a (*,3,3) array containing rotation matrices. eps: a small number for numerical stability. Returns: A (*,4) array containing quaternions.