id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
14,100 | import os
import traceback
from Exceptions import PipelineCreateException
from const import EnumInferenceTypes, PitchExtractorType
from data.ModelSlot import EasyVCModelSlot
from voice_changer.EasyVC.pipeline.Pipeline import Pipeline
from voice_changer.RVC.deviceManager.DeviceManager import DeviceManager
from voice_cha... | null |
14,101 | import os
import json
import torch
from onnxsim import simplify
import onnx
from const import TMP_DIR, EnumInferenceTypes
from data.ModelSlot import DiffusionSVCModelSlot
from voice_changer.RVC.deviceManager.DeviceManager import DeviceManager
def _export2onnx(input_model, output_model, output_model_simple, is_half, met... | null |
14,102 | import traceback
from Exceptions import PipelineCreateException
from data.ModelSlot import DiffusionSVCModelSlot
from voice_changer.DiffusionSVC.inferencer.InferencerManager import InferencerManager
from voice_changer.DiffusionSVC.pipeline.Pipeline import Pipeline
from voice_changer.DiffusionSVC.pitchExtractor.PitchExt... | null |
14,103 | import os
from data.ModelSlot import DiffusionSVCModelSlot, ModelSlot
from voice_changer.DiffusionSVC.inferencer.diffusion_svc_model.diffusion.unit2mel import load_model_vocoder_from_combo
from voice_changer.VoiceChangerParamsManager import VoiceChangerParamsManager
from voice_changer.utils.LoadModelParams import LoadM... | null |
14,104 | from torchaudio.transforms import Resample
import pyworld as pw
import numpy as np
import torchcrepe
import torch
import torch.nn.functional as F
def median_pool_1d(x, kernel_size):
x = x.unsqueeze(1)
x = F.pad(x, ((kernel_size - 1) // 2, kernel_size // 2), mode="reflect")
x = x.squeeze(1)
x = x.unfold... | null |
14,105 | from torchaudio.transforms import Resample
import pyworld as pw
import numpy as np
import torchcrepe
import torch
import torch.nn.functional as F
def masked_avg_pool_1d(x, kernel_size):
x = x.unsqueeze(1)
x = F.pad(x, ((kernel_size - 1) // 2, kernel_size // 2), mode="reflect")
mask = ~torch.isnan(x)
ma... | null |
14,108 | import torch
from torch import nn
import math
from functools import partial
from einops import rearrange, repeat
from local_attention import LocalAttention
import torch.nn.functional as F
def exists(val):
def default(val, d):
return val if exists(val) else d | null |
14,112 | import torch
from torch import nn
import math
from functools import partial
from einops import rearrange, repeat
from local_attention import LocalAttention
import torch.nn.functional as F
def orthogonal_matrix_chunk(cols, qr_uniform_q = False, device = None):
def gaussian_orthogonal_random_matrix(nb_rows, nb_columns, ... | null |
14,113 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.nn.utils import weight_norm
from .pcmer import PCmer
def l2_regularization(model, l2_alpha):
l2_loss = []
for module in model.modules():
if type(module) is nn.Conv2d:
l2_loss.append((module.weig... | null |
14,114 | from collections import deque
from functools import partial
from inspect import isfunction
import torch.nn.functional as F
import numpy as np
import torch
from torch import nn
from tqdm import tqdm
def exists(x):
return x is not None
def default(val, d):
if exists(val):
return val
return d() if isf... | null |
14,116 | from collections import deque
from functools import partial
from inspect import isfunction
import torch.nn.functional as F
import numpy as np
import torch
from torch import nn
from tqdm import tqdm
def noise_like(shape, device, repeat=False):
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repea... | null |
14,119 | import os
import yaml
import torch
import torch.nn as nn
import numpy as np
from voice_changer.DiffusionSVC.inferencer.diffusion_svc_model.diffusion.diffusion import GaussianDiffusion
from voice_changer.DiffusionSVC.inferencer.diffusion_svc_model.diffusion.wavenet import WaveNet
from voice_changer.DiffusionSVC.inferenc... | null |
14,120 | import os
import yaml
import torch
import torch.nn as nn
import numpy as np
from voice_changer.DiffusionSVC.inferencer.diffusion_svc_model.diffusion.diffusion import GaussianDiffusion
from voice_changer.DiffusionSVC.inferencer.diffusion_svc_model.diffusion.wavenet import WaveNet
from voice_changer.DiffusionSVC.inferenc... | null |
14,121 | import torch
def expand_dims(v, dims):
"""
Expand the tensor `v` to the dim `dims`.
Args:
`v`: a PyTorch tensor with shape [N].
`dim`: a `int`.
Returns:
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
"""
return v[(...,) + (None,)*(dims - ... | Create a wrapper function for the noise prediction model. DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. We support four types of the diffusion m... |
14,131 | import os
import torch
import torch.utils.data
import numpy as np
import librosa
from librosa.filters import mel as librosa_mel_fn
import soundfile as sf
import torch.nn.functional as F
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
sampling_rate = None
try:
data, sa... | null |
14,141 | import numpy as np
import torch
import torch.nn.functional as F
import pyworld as pw
import parselmouth
import torchcrepe
import librosa
import fsspec
from tqdm import tqdm
from transformers import HubertModel, Wav2Vec2FeatureExtractor, Wav2Vec2ForCTC
from fairseq import checkpoint_utils
from encoder.hubert.model impor... | null |
14,142 | import numpy as np
import torch
import torch.nn.functional as F
import pyworld as pw
import parselmouth
import torchcrepe
import librosa
import fsspec
from tqdm import tqdm
from transformers import HubertModel, Wav2Vec2FeatureExtractor, Wav2Vec2ForCTC
from fairseq import checkpoint_utils
from encoder.hubert.model impor... | null |
14,143 | import numpy as np
import torch
import torch.nn.functional as F
import pyworld as pw
import parselmouth
import torchcrepe
import librosa
import fsspec
from tqdm import tqdm
from transformers import HubertModel, Wav2Vec2FeatureExtractor, Wav2Vec2ForCTC
from fairseq import checkpoint_utils
from encoder.hubert.model impor... | null |
14,144 | import os
import numpy as np
from tqdm import tqdm
import pickle
import torch
from pathlib import Path
def train_index(path):
import faiss
# from: RVC https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI
# 获取文件列表
listdir_res = []
for file in os.listdir(path):
listdir_res.ap... | null |
14,145 | import librosa
import torch
import torchaudio
class Slicer:
def __init__(self,
sr: int,
threshold: float = -40.,
min_length: int = 5000,
min_interval: int = 300,
hop_size: int = 20,
max_sil_kept: int = 5000):
... | null |
14,146 | import librosa
import torch
import torchaudio
def split(audio, sample_rate, hop_size, db_thresh=-40, min_len=5000):
slicer = Slicer(
sr=sample_rate,
threshold=db_thresh,
min_length=min_len)
chunks = dict(slicer.slice(audio))
result = []
for k, v in chunks.items():
tag = v... | null |
14,147 | from typing import Any, Union
from const import TMP_DIR
import torch
import os
import numpy as np
from dataclasses import dataclass, asdict, field
import onnxruntime
from mods.log_control import VoiceChangaerLogger
from voice_changer.IORecorder import IORecorder
from voice_changer.utils.Timer import Timer2
from voice_c... | null |
14,148 | from typing import Any, Union
from const import TMP_DIR
import torch
import os
import numpy as np
from dataclasses import dataclass, asdict, field
import onnxruntime
from mods.log_control import VoiceChangaerLogger
from voice_changer.IORecorder import IORecorder
from voice_changer.utils.Timer import Timer2
from voice_c... | null |
14,149 | from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
def convert_continuos_f0(f0, f0_size):
# 正式版チェックOK
# get start and end of f0
if (f0 == 0).all():
return np.zeros((f0_size,))
start_f0 = f0[f0 != 0][0]
end_f0 = f0[f0 != 0][-1]
# padding start an... | null |
14,150 | from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
hann_window = {}
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
# 正式版チェックOK
if torch.min(y) < -1.:
print('min value is ', torch.min(y))
if torch.max(y) > 1.:
print... | null |
14,151 | from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
class HParams():
# 正式版チェックOK
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return ... | null |
14,152 | from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
def load_checkpoint(checkpoint_path, model, optimizer=None):
# 正式版チェックOK
assert os.path.isfile(checkpoint_path), f"No such file or directory: {checkpoint_path}"
checkpoint_dict = torch.load(checkpoint_path, map_loc... | null |
14,153 | import torch
from torch.nn import ConstantPad1d as pad1d
The provided code snippet includes necessary dependencies for implementing the `pd_indexing` function. Write a Python function `def pd_indexing(x, d, dilation, batch_index, ch_index)` to solve the following problem:
Pitch-dependent indexing of past and future sa... | Pitch-dependent indexing of past and future samples. Args: x (Tensor): Input feature map (B, C, T). d (Tensor): Input pitch-dependent dilated factors (B, 1, T). dilation (Int): Dilation size. batch_index (Tensor): Batch index ch_index (Tensor): Channel index Returns: Tensor: Past output tensor (B, out_channels, T) Tens... |
14,154 | import torch
from torch.nn import ConstantPad1d as pad1d
The provided code snippet includes necessary dependencies for implementing the `index_initial` function. Write a Python function `def index_initial(n_batch, n_ch, tensor=True)` to solve the following problem:
Tensor batch and channel index initialization. Args: ... | Tensor batch and channel index initialization. Args: n_batch (Int): Number of batch. n_ch (Int): Number of channel. tensor (bool): Return tensor or numpy array Returns: Tensor: Batch index Tensor: Channel index |
14,159 | import sys
from logging import getLogger
import numpy as np
import torch
from torch.nn.functional import interpolate
The provided code snippet includes necessary dependencies for implementing the `validate_length` function. Write a Python function `def validate_length(xs, ys=None, hop_size=None)` to solve the followin... | Validate length Args: xs (ndarray): numpy array of features ys (ndarray): numpy array of audios hop_size (int): upsampling factor Returns: (ndarray): length adjusted features |
14,160 | import sys
from logging import getLogger
import numpy as np
import torch
from torch.nn.functional import interpolate
The provided code snippet includes necessary dependencies for implementing the `dilated_factor` function. Write a Python function `def dilated_factor(batch_f0, fs, dense_factor)` to solve the following ... | Pitch-dependent dilated factor Args: batch_f0 (ndarray): the f0 sequence (T) fs (int): sampling rate dense_factor (int): the number of taps in one cycle Return: dilated_factors(np array): float array of the pitch-dependent dilated factors (T) |
14,161 | import numpy as np
import torch
import torch.nn as nn
def upsample(signal: torch.Tensor, factor: int) -> torch.Tensor:
signal = signal.permute(0, 2, 1)
signal = nn.functional.interpolate(torch.cat((signal, signal[:, :, -1:]), 2), size=signal.shape[-1] * factor + 1, mode='linear', align_corners=True)
signal... | null |
14,162 | import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Tuple
from const import RVCSampleMode, getSampleJsonAndModelIds
from data.ModelSample import ModelSamples, generateModelSample
from data.ModelSlot import DiffusionSVCModelSlot, ModelSlot, RVCModelSlot
from mods.lo... | null |
14,163 | import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Tuple
from const import RVCSampleMode, getSampleJsonAndModelIds
from data.ModelSample import ModelSamples, generateModelSample
from data.ModelSlot import DiffusionSVCModelSlot, ModelSlot, RVCModelSlot
from mods.lo... | null |
14,164 | import json
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Tuple
from const import RVCSampleMode, getSampleJsonAndModelIds
from data.ModelSample import ModelSamples, generateModelSample
from data.ModelSlot import DiffusionSVCModelSlot, ModelSlot, RVCModelSlot
from mods.lo... | null |
14,165 | import os
from concurrent.futures import ThreadPoolExecutor
from downloader.Downloader import download
from mods.log_control import VoiceChangaerLogger
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
from Exceptions import WeightDownladException
logger = VoiceChangaerLogger.get_instance().getLogge... | null |
14,166 | import os
import shutil
from fastapi import UploadFile
def sanitize_filename(filename: str) -> str:
safe_filename = os.path.basename(filename)
max_length = 255
if len(safe_filename) > max_length:
file_root, file_ext = os.path.splitext(safe_filename)
safe_filename = file_root[: max_length - l... | null |
14,167 | import os
import shutil
from fastapi import UploadFile
def sanitize_filename(filename: str) -> str:
safe_filename = os.path.basename(filename)
max_length = 255
if len(safe_filename) > max_length:
file_root, file_ext = os.path.splitext(safe_filename)
safe_filename = file_root[: max_length - l... | null |
14,168 | from enum import Enum
import os
import sys
import tempfile
from typing import Literal, TypeAlias
os.makedirs(TMP_DIR, exist_ok=True)
def getFrontendPath():
frontend_path = os.path.join(sys._MEIPASS, "dist") if hasattr(sys, "_MEIPASS") else "../client/demo/dist"
return frontend_path | null |
14,169 | import argparse
import pyaudio
import wave
import struct
import socketio
import ssl
from datetime import datetime
import time
import urllib3
import signal
import sys
import numpy as np
def setupArgParser():
parser = argparse.ArgumentParser()
parser.add_argument("--url", type=str, default="http://localhost:1888... | null |
14,170 | import os
import json
import argparse
from alfworld_trial import run_trial
from generate_reflections import update_memory
from typing import Any, List, Dict
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--num_trials", type=int, help="The number of trials to run")
parser.add_argume... | null |
14,171 | from typing import List, Dict
def _get_base_query(base_query: str, start_info: str, memory: List[str]) -> str:
query = base_query
# add memory if it exists
if len(memory) > 0:
query += '\n\nYour memory for the task below:'
for i, m in enumerate(memory):
query += f'\nTrial {i}:\... | null |
14,172 | from utils import get_completion
from typing import List, Dict, Any
with open("./reflexion_few_shot_examples.txt", 'r') as f:
FEW_SHOT_EXAMPLES = f.read()
def _generate_reflection_query(log_str: str, memory: List[str]) -> str:
"""Allows the Agent to reflect upon a past experience."""
scenario: str = _get_sc... | Updates the given env_config with the appropriate reflections. |
14,173 | import os
import sys
import json
import yaml
import openai
import importlib
import alfworld
import alfworld.agents.environment
from utils import Model, get_chat, get_completion
from env_history import EnvironmentHistory
from typing import List, Dict, Any, Tuple
with open(os.path.join(FOLDER, PROMPT_FILE), 'r') as f:
... | null |
14,174 | from generators.model import ModelBase, Message
import random
from typing import Union, List, Optional, Callable
def print_messages(system_message_text: str, user_message_text: str) -> None:
print(f"""----------------------- SYSTEM MESSAGE -----------------------)
{system_message_text}
-----------------------------... | null |
14,175 | from generators.model import ModelBase, Message
import random
from typing import Union, List, Optional, Callable
def sample_n_random(items: List[str], n: int) -> List[str]:
"""Sample min(n, len(items)) random items from a list"""
assert n >= 0
if n >= len(items):
return items
return random.sampl... | Generates tests for a function. |
14,176 | from generators.model import ModelBase, Message
import random
from typing import Union, List, Optional, Callable
class Message():
class ModelBase():
def __init__(self, name: str):
def __repr__(self) -> str:
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: f... | null |
14,177 | from generators.model import ModelBase, message_to_str
from .generator_types import Generator
from .generator_utils import generic_generate_func_impl, generic_generate_internal_tests, generic_generate_self_reflection
from typing import Optional, List, Union
import ast
import re
from .parse import parse_code_block, add_... | 3 cases: 1. good syntax 2. first line not good 3. entire body not good |
14,178 | from generators.model import ModelBase, message_to_str
from .generator_types import Generator
from .generator_utils import generic_generate_func_impl, generic_generate_internal_tests, generic_generate_self_reflection
from typing import Optional, List, Union
import ast
import re
from .parse import parse_code_block, add_... | null |
14,179 | from typing import List, Union, Optional, Literal
import dataclasses
from tenacity import (
retry,
stop_after_attempt, # type: ignore
wait_random_exponential, # type: ignore
)
import openai
class Message():
role: MessageRole
content: str
def message_to_str(message: Message) -> str:
return f"{m... | null |
14,180 | from typing import List, Union, Optional, Literal
import dataclasses
from tenacity import (
retry,
stop_after_attempt, # type: ignore
wait_random_exponential, # type: ignore
)
import openai
def gpt_completion(
model: str,
prompt: str,
max_tokens: int = 1024,
stop_strs: Opt... | null |
14,181 | from typing import List, Union, Optional, Literal
import dataclasses
from tenacity import (
retry,
stop_after_attempt, # type: ignore
wait_random_exponential, # type: ignore
)
import openai
class Message():
def gpt_chat(
model: str,
messages: List[Message],
max_tokens: int = 1024,
tempera... | null |
14,182 | from generators.model import ModelBase
from .generator_types import Generator
from .generator_utils import generic_generate_func_impl, generic_generate_internal_tests, generic_generate_self_reflection
from .parse import parse_code_block, add_code_block
from typing import List, Optional, Union
The provided code snippet... | Dumps the tests to a string. |
14,183 | from generators.model import ModelBase
from .generator_types import Generator
from .generator_utils import generic_generate_func_impl, generic_generate_internal_tests, generic_generate_self_reflection
from .parse import parse_code_block, add_code_block
from typing import List, Optional, Union
The provided code snippet... | Parses the tests from a string. |
14,184 | import re
from typing import Optional
def parse_first_func(code: str, lang: str) -> Optional[str]:
assert lang == "python", "Only python is supported for now. TODO: Rust"
code_lines = code.split("\n")
def_i = -1
last_i = 0
got_return = False
for i, line in enumerate(code_lines):
if line.... | null |
14,185 | import re
from typing import Optional
def add_code_block(string: str, lang: str) -> str:
return f"```{lang}\n{string}\n```" | null |
14,186 | from .py_generate import PyGenerator
from .rs_generate import RsGenerator
from .generator_types import Generator
from .model import CodeLlama, ModelBase, GPT4, GPT35, StarChat, GPTDavinci
class PyGenerator(Generator):
def self_reflection(self, func: str, feedback: str, model: ModelBase) -> str:
return gene... | null |
14,187 | from .py_generate import PyGenerator
from .rs_generate import RsGenerator
from .generator_types import Generator
from .model import CodeLlama, ModelBase, GPT4, GPT35, StarChat, GPTDavinci
class ModelBase():
def __init__(self, name: str):
self.name = name
self.is_chat = False
def __repr__(self)... | null |
14,189 | import os
import gzip
import json
import openai
import jsonlines
from typing import List
def read_jsonl_gz(path: str) -> List[dict]:
if not path.endswith(".jsonl.gz"):
raise ValueError(f"File `{path}` is not a jsonl.gz file.")
with gzip.open(path, "rt") as f:
data = [json.loads(line) for line i... | null |
14,190 | import os
import argparse
from immediate_refinement import run_immediate_refinement
from immediate_reflexion import run_immediate_reflexion
from simple import run_simple
from reflexion import run_reflexion
from reflexion_ucs import run_reflexion_ucs
from test_acc import run_test_acc
from utils import read_jsonl, read_j... | null |
14,191 | import os
import argparse
from immediate_refinement import run_immediate_refinement
from immediate_reflexion import run_immediate_reflexion
from simple import run_simple
from reflexion import run_reflexion
from reflexion_ucs import run_reflexion_ucs
from test_acc import run_test_acc
from utils import read_jsonl, read_j... | null |
14,192 | import sys
import signal
from utils import read_jsonl
TIMEOUT = 5
assert len(sys.argv) == 2, "Please provide a log file"
def red_text(text: str) -> str:
def green_text(text: str) -> str:
def count_test_cases(test_str: str) -> int:
def read_jsonl(path: str) -> List[dict]:
def validate_py_results(log_path: str):
i... | null |
14,193 | import os, json
from threading import Thread
def to_jsonl(dict_data, file_path):
with open(file_path, 'a') as file:
json_line = json.dumps(dict_data)
file.write(json_line + os.linesep) | null |
14,194 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
cargo_harness_dir = os.path.join(os.path.dirname(
os.path.realpath(__file__)), "cargo_harness")
def create_temp_project() ->... | null |
14,195 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
def indent_code(code: str, spaces: int = 4) -> str:
def write_to_file(path: str, code: str):
prelude = "fn main() {\n"
p... | null |
14,196 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
def write_to_file_toplevel(path: str, code: str):
# delete the file if it exists
if os.path.exists(path):
os.rem... | null |
14,197 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
def timeout_handler(_, __):
raise TimeoutError()
The provided code snippet includes necessary dependencies for implementing... | Runs the given command with a timeout. Produces a tuple of stdout and stderr. If the command times out, returns None. |
14,198 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
assert_no_panic = r"""
macro_rules! assert_eq_nopanic {
($left:expr, $right:expr) => {
std::panic::catch_unwind(|| {
... | Transform all asserts into assert_eq_nopanic! asserts, inserting the macro definition at the top of the code. |
14,199 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
assert_no_panic = r"""
macro_rules! assert_eq_nopanic {
($left:expr, $right:expr) => {
std::panic::catch_unwind(|| {
... | Revert all assert_eq_nopanic! asserts back into assert_eq! asserts. |
14,200 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
class CompileErr:
def __init__(self, rendered):
self.rendered = rendered
def __str__(self):
return self.r... | null |
14,201 | import os
import signal
import subprocess
import json
from .executor_utils import timeout_handler
from .executor_types import ExecuteResult, Executor
from typing import List, Tuple, Optional
class RuntimeErr:
def __init__(self, left, right, line, column, panic_reason):
# right and left are only used for ass... | null |
14,202 | import ast
import signal
import astunparse
from .executor_utils import function_with_timeout
from typing import List
from .executor_types import ExecuteResult, Executor
def get_call_str(assert_statement: str) -> str:
ast_parsed = ast.parse(assert_statement)
try:
call_str = ast_parsed.body[0].test.left #... | null |
14,203 | from .py_executor import PyExecutor
from .rs_executor import RsExecutor
from .executor_types import Executor
from .leet_executor import LeetExecutor
class PyExecutor(Executor):
def execute(self, func: str, tests: List[str], timeout: int = 5) -> ExecuteResult:
# Combine function code and assert statement
... | null |
14,204 | import sys
import signal
from utils import read_jsonl
from executors import RsExecutor
assert len(sys.argv) == 2, "Please provide a log file"
def red_text(text: str) -> str:
return f"\033[91m{text}\033[0m"
def green_text(text: str) -> str:
return f"\033[92m{text}\033[0m"
def count_test_cases(test_str: str) -> i... | null |
14,205 | import sys
from datasets.load import load_dataset
from utils import write_jsonl
def write_jsonl(path: str, data: List[dict], append: bool = False):
with jsonlines.open(path, mode='a' if append else 'w') as writer:
for item in data:
writer.write(item)
def download_dataset(dataset_name: str):
... | null |
14,206 | import os
import joblib
def summarize_trial(agents):
correct = [a for a in agents if a.is_correct()]
incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]
return correct, incorrect
def remove_fewshot(prompt: str) -> str:
prefix = prompt.split('Here are some examples:')[0]
suffix ... | null |
14,207 | import os
import joblib
def remove_fewshot(prompt: str) -> str:
prefix = prompt.split('Here are some examples:')[0]
suffix = prompt.split('(END OF EXAMPLES)')[1]
return prefix.strip('\n').strip() + '\n' + suffix.strip('\n').strip()
def summarize_react_trial(agents):
correct = [a for a in agents if a.is... | null |
14,208 | import os
import joblib
def save_agents(agents, dir: str):
os.makedirs(dir, exist_ok=True)
for i, agent in enumerate(agents):
joblib.dump(agent, os.path.join(dir, f'{i}.joblib')) | null |
14,209 | from langchain.agents.react.base import DocstoreExplorer
from langchain.llms.base import BaseLLM
def reactLLMMock(prompt: str) -> str:
last_line = prompt.split('\n')[-1].strip()
last_action = last_line.split(' ')[0].lower()
if last_action == 'thought':
return 'It does not mention the eastern sector... | null |
14,210 | from langchain.agents.react.base import DocstoreExplorer
from langchain.llms.base import BaseLLM
def reflectLLMMock(prompt: str) -> str:
return "Last time i should have answered correctly" | null |
14,211 | import re
import string
from typing import Tuple
import gym
from langchain import Wikipedia
from langchain.agents.react.base import DocstoreExplorer
def parse_action(string):
pattern = r'^(\w+)\[(.+)\]$'
match = re.match(pattern, string)
if match:
action_type = match.group(1)
argument ... | null |
14,212 | import re
import string
from typing import Tuple
import gym
from langchain import Wikipedia
from langchain.agents.react.base import DocstoreExplorer
def normalize_answer(s):
def remove_articles(text):
return re.sub(r"\b(a|an|the)\b", " ", text)
def white_space_fix(text):
return " ".join(text.split())
de... | null |
14,213 | import re, string, os
from typing import List, Union, Literal
from enum import Enum
import tiktoken
from langchain import OpenAI, Wikipedia
from langchain.llms.base import BaseLLM
from langchain.chat_models import ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
SystemM... | null |
14,214 | import re, string, os
from typing import List, Union, Literal
from enum import Enum
import tiktoken
from langchain import OpenAI, Wikipedia
from langchain.llms.base import BaseLLM
from langchain.chat_models import ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
SystemM... | null |
14,215 | import re, string, os
from typing import List, Union, Literal
from enum import Enum
import tiktoken
from langchain import OpenAI, Wikipedia
from langchain.llms.base import BaseLLM
from langchain.chat_models import ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
SystemM... | null |
14,216 | import re, string, os
from typing import List, Union, Literal
from enum import Enum
import tiktoken
from langchain import OpenAI, Wikipedia
from langchain.llms.base import BaseLLM
from langchain.chat_models import ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
SystemM... | null |
14,217 | import re, string, os
from typing import List, Union, Literal
from enum import Enum
import tiktoken
from langchain import OpenAI, Wikipedia
from langchain.llms.base import BaseLLM
from langchain.chat_models import ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
SystemM... | null |
14,218 | import os
from typing import List
import dotenv
import gym
import tiktoken
from langchain import OpenAI
from langchain.llms.base import BaseLLM
from langchain.prompts import PromptTemplate
from environment import QAEnv
from prompts import reflect_prompt, react_agent_prompt, react_reflect_agent_prompt, REFLECTION_HEADER... | null |
14,219 | import os
from typing import List
import dotenv
import gym
import tiktoken
from langchain import OpenAI
from langchain.llms.base import BaseLLM
from langchain.prompts import PromptTemplate
from environment import QAEnv
from prompts import reflect_prompt, react_agent_prompt, react_reflect_agent_prompt, REFLECTION_HEADER... | null |
14,220 | import os
import openai
from tenacity import (
retry,
stop_after_attempt, # type: ignore
wait_random_exponential, # type: ignore
)
from typing import Optional, List, Union
openai.api_key = os.getenv('OPENAI_API_KEY')
def get_completion(prompt: Union[str, List[str]], max_tokens: int = 256, stop_strs: Option... | null |
14,221 | import os
import json
import argparse
from webshop_trial import run_trial
from generate_reflections import update_memory
from typing import Any, List, Dict
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--num_trials", type=int, help="The number of trials to run")
parser.add_argumen... | null |
14,222 | from typing import List, Dict
def _get_base_query(base_query: str, start_info: str, memory: List[str]) -> str:
query = base_query
# add memory if it exists
if len(memory) > 0:
query += '\nYour memory for the task below:'
for i, m in enumerate(memory):
query += f'\nTrial {i}:\n{... | null |
14,223 | from utils import get_completion
from typing import List, Dict, Any
with open("./reflection_few_shot_examples.txt", 'r') as f:
FEW_SHOT_EXAMPLES = f.read()
def _generate_reflection_query(log_str: str, memory: List[str]) -> str:
"""Allows the Agent to reflect upon a past experience."""
scenario: str = _get_s... | Updates the given env_config with the appropriate reflections. |
14,224 | import os
import sys
import openai
import requests
from bs4 import BeautifulSoup
from bs4.element import Comment
from env_history import EnvironmentHistory
from typing import Any, Dict, List, Tuple
WEBSHOP_URL = "http://3.83.245.205:3000"
def clean_str(p):
return p.encode().decode("unicode-escape").encode("latin1").d... | null |
14,225 | import os
import sys
import openai
import requests
from bs4 import BeautifulSoup
from bs4.element import Comment
from env_history import EnvironmentHistory
from typing import Any, Dict, List, Tuple
with open("./base_prompt.txt", 'r') as f:
BASE_PROMPT = f.read()
class webshopEnv:
def __init__(self):
def s... | null |
14,226 | import argparse
import sys
import os
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, utils
from tqdm import tqdm
from vqvae import VQVAE
from scheduler import CycleScheduler
import distributed as dist
def train(epoch, loader, model, optimiz... | null |
14,227 | import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets
from tqdm import tqdm
from pixelsnail import PixelSNAIL
def train(epoch, loader, model, optimizer, device):
loader = tqdm(loader)
criterion = nn.CrossEntropyLoss()
for i, (... | null |
14,228 | import argparse
import pickle
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
import lmdb
from tqdm import tqdm
from dataset import ImageFileDataset, CodeRow
from vqvae import VQVAE
CodeRow = namedtuple('CodeRow', ['top', 'bottom', 'filename'])
def extract(lmdb_env, loader, mod... | null |
14,229 | import argparse
import os
import torch
from torchvision.utils import save_image
from tqdm import tqdm
from vqvae import VQVAE
from pixelsnail import PixelSNAIL
def sample_model(model, device, batch, size, temperature, condition=None):
row = torch.zeros(batch, *size, dtype=torch.int64).to(device)
cache = {}
... | null |
14,230 | import argparse
import os
import torch
from torchvision.utils import save_image
from tqdm import tqdm
from vqvae import VQVAE
from pixelsnail import PixelSNAIL
class VQVAE(nn.Module):
def __init__(
self,
in_channel=3,
channel=128,
n_res_block=2,
n_res_channel=32,
emb... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.