id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
162,775
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `data_loader` function. Write a Python function `def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False)` to solve the following problem: Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices. Shuffle batches if `shuffle` is `True`. Here is the function: def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False): """ Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices. Shuffle batches if `shuffle` is `True`. """ steps_per_epoch = len(dataset) // batch_size if shuffle: batch_idx = jax.random.permutation(rng, len(dataset)) else: batch_idx = jnp.arange(len(dataset)) batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch. batch_idx = batch_idx.reshape((steps_per_epoch, batch_size)) for idx in batch_idx: batch = dataset[idx] batch = {k: jnp.array(v) for k, v in batch.items()} batch = shard(batch) yield batch
Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices. Shuffle batches if `shuffle` is `True`.
162,776
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec def write_train_metric(summary_writer, train_metrics, train_time, step): summary_writer.scalar("train_time", train_time, step) train_metrics = get_metrics(train_metrics) for key, vals in train_metrics.items(): tag = f"train_{key}" for i, val in enumerate(vals): summary_writer.scalar(tag, val, step - len(vals) + i + 1)
null
162,777
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec def write_eval_metric(summary_writer, eval_metrics, step): for metric_name, value in eval_metrics.items(): summary_writer.scalar(f"eval_{metric_name}", value, step)
null
162,778
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `create_learning_rate_fn` function. Write a Python function `def create_learning_rate_fn( train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]` to solve the following problem: Returns a linear warmup, linear_decay learning rate function. Here is the function: def create_learning_rate_fn( train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" steps_per_epoch = train_ds_size // train_batch_size num_train_steps = steps_per_epoch * num_train_epochs warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps) decay_fn = optax.linear_schedule( init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps ) schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps]) return schedule_fn
Returns a linear warmup, linear_decay learning rate function.
162,779
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec logger = logging.getLogger(__name__) def mb_item(x): return x.item() if hasattr(x, "item") else x The provided code snippet includes necessary dependencies for implementing the `save_model_checkpoint` function. Write a Python function `def save_model_checkpoint(model, save_dir, state, with_opt:bool=True, push_to_hub:bool=False)` to solve the following problem: If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`. Here is the function: def save_model_checkpoint(model, save_dir, state, with_opt:bool=True, push_to_hub:bool=False): """ If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`. """ state = jax_utils.unreplicate(state) logger.info(f"SAVING CHECKPOINT IN {save_dir}...") if not push_to_hub: save_dir = f"{save_dir}/ckpt-{mb_item(state.step)-1}" model.save_pretrained( save_dir, params=state.params, push_to_hub=push_to_hub, commit_message=f"Saving weights and logs at step {mb_item(state.step)-1}", ) if with_opt: with open(os.path.join(save_dir, "opt_state.msgpack"), "wb") as f: f.write(to_bytes(state.opt_state)) with open(os.path.join(save_dir, "training_state.json"), "w") as f: json.dump({"step": state.step.item()}, f) logger.info("checkpoint saved")
If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`.
162,780
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec def _zeros_tree_like(inp_tree): return jax.tree_map(jnp.zeros_like, inp_tree) def fake_update(state): fake_updates = _zeros_tree_like(state.params) _, new_inner_opt_state = state.tx.inner_opt.update(fake_updates, state.opt_state.inner_opt_state, state.params) opt_state = state.opt_state new_opt_state = optax.MultiStepsState(mini_step=opt_state.mini_step, gradient_step=opt_state.gradient_step, inner_opt_state=new_inner_opt_state, acc_grads=opt_state.acc_grads) return state.replace(opt_state=new_opt_state)
null
162,781
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec logger = logging.getLogger(__name__) def reinstantiate_states(opt_state): new_state = [] for state in opt_state: if isinstance(state, list): new_state.append(reinstantiate_states(state)) else: cls = getattr(optax, type(state).__name__) new_state.append(cls(**{k:getattr(state, k) for k in state._fields})) return new_state def restore_model_checkpoint(save_dir, state): logger.info(f"RESTORING CHECKPOINT FROM {save_dir}...") with open(os.path.join(save_dir, "flax_model.msgpack"), "rb") as f: params = from_bytes(state.params, f.read()) with open(os.path.join(save_dir, "opt_state.msgpack"), "rb") as f: opt_state = from_bytes(state.opt_state, f.read()) with open(os.path.join(save_dir, "training_state.json"), "r") as f: training_state = json.load(f) step = training_state["step"] logger.info("checkpoint restored") # reinstantiate inner opt state to avoid type conflict if hasattr(opt_state, "inner_opt_state"): print("restoring state of multisteps optimizer") inner_opt_state = reinstantiate_states(opt_state.inner_opt_state) ms_state_dict = {k:getattr(state.opt_state, k) for k in state.opt_state._fields} ms_state_dict["inner_opt_state"] = inner_opt_state opt_state = optax.MultiStepsState(**ms_state_dict) return state.replace(step=step, params=params, opt_state=opt_state)
null
162,782
import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil import datasets from datasets import Dataset, load_dataset, concatenate_datasets from datasets.dataset_dict import DatasetDict from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, IntervalStrategy ) from importlib.util import find_spec logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `rotate_checkpoints` function. Write a Python function `def rotate_checkpoints(ckpt_dir:str, save_total_limit:int)` to solve the following problem: Removes older checkpoints so that `save_total_limit` checkpoints are kept Here is the function: def rotate_checkpoints(ckpt_dir:str, save_total_limit:int): "Removes older checkpoints so that `save_total_limit` checkpoints are kept" # TODO: what to remove is decided using step number only, we might want to improve that ckpts = [str(x) for x in Path(ckpt_dir).glob("ckpt-*")] # sort checkpoints by step ckpts_sorted = sorted(ckpts, key=lambda x: int(x.split('-')[-1])) ckpts_to_delete = ckpts_sorted[:-save_total_limit] for ckpt in ckpts_to_delete: logger.info(f"Deleting older checkpoint [{ckpt}] due to save_total_limit ({save_total_limit})") shutil.rmtree(ckpt)
Removes older checkpoints so that `save_total_limit` checkpoints are kept
162,783
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch def write_train_metric(summary_writer, train_metrics, train_time, step): summary_writer.scalar("train_time", train_time, step) train_metrics = get_metrics(train_metrics) for key, vals in train_metrics.items(): tag = f"train_{key}" for i, val in enumerate(vals): summary_writer.scalar(tag, val, step - len(vals) + i + 1)
null
162,784
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch def write_eval_metric(summary_writer, eval_metrics, step): for metric_name, value in eval_metrics.items(): summary_writer.scalar(f"eval_{metric_name}", value, step)
null
162,785
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch The provided code snippet includes necessary dependencies for implementing the `create_learning_rate_fn` function. Write a Python function `def create_learning_rate_fn( num_train_steps: int, train_batch_size: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]` to solve the following problem: Returns a linear warmup, linear_decay learning rate function. Here is the function: def create_learning_rate_fn( num_train_steps: int, train_batch_size: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps) decay_fn = optax.linear_schedule( init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps ) schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps]) return schedule_fn
Returns a linear warmup, linear_decay learning rate function.
162,786
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch def gpt3_schedule(warmup_steps, total_steps, peak_lr, end_lr): def sch(step): warmup_pct = jnp.clip(step, 0, warmup_steps) / warmup_steps anneal_pct = jnp.clip(step - warmup_steps, 0, total_steps) / total_steps return warmup_pct * peak_lr - (peak_lr - end_lr) * (1 - jnp.cos(jnp.pi * anneal_pct)) / 2 return sch
null
162,787
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch logger = logging.getLogger(__name__) def mb_item(x): return x.item() if hasattr(x, "item") else x The provided code snippet includes necessary dependencies for implementing the `save_model_checkpoint` function. Write a Python function `def save_model_checkpoint(model, save_dir, state, with_opt:bool=True, push_to_hub:bool=False)` to solve the following problem: If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`. Here is the function: def save_model_checkpoint(model, save_dir, state, with_opt:bool=True, push_to_hub:bool=False): """ If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`. """ state = jax_utils.unreplicate(state) logger.info(f"SAVING CHECKPOINT IN {save_dir}...") if not push_to_hub: save_dir = f"{save_dir}/ckpt-{mb_item(state.step)-1}" model.save_pretrained( save_dir, params=state.params, push_to_hub=push_to_hub, commit_message=f"Saving weights and logs at step {mb_item(state.step)-1}", ) if with_opt: with open(os.path.join(save_dir, "opt_state.msgpack"), "wb") as f: f.write(to_bytes(state.opt_state)) with open(os.path.join(save_dir, "training_state.json"), "w") as f: json.dump({"step": state.step.item()}, f) logger.info("checkpoint saved")
If `push_to_hub` is True, will save to `save_dir`. Otherwise will save to `save_dir/ckpt-{step}`.
162,788
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch def _zeros_tree_like(inp_tree): return jax.tree_map(jnp.zeros_like, inp_tree) def fake_update(state): fake_updates = _zeros_tree_like(state.params) _, new_inner_opt_state = state.tx.inner_opt.update(fake_updates, state.opt_state.inner_opt_state, state.params) opt_state = state.opt_state new_opt_state = optax.MultiStepsState(mini_step=opt_state.mini_step, gradient_step=opt_state.gradient_step, inner_opt_state=new_inner_opt_state, acc_grads=opt_state.acc_grads) return state.replace(opt_state=new_opt_state)
null
162,789
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch logger = logging.getLogger(__name__) def reinstantiate_states(opt_state): new_state = [] for state in opt_state: if isinstance(state, list): new_state.append(reinstantiate_states(state)) else: cls = getattr(optax, type(state).__name__) new_state.append(cls(**{k:getattr(state, k) for k in state._fields})) return new_state def restore_model_checkpoint(save_dir, state): logger.info(f"RESTORING CHECKPOINT FROM {save_dir}...") with open(os.path.join(save_dir, "flax_model.msgpack"), "rb") as f: params = from_bytes(state.params, f.read()) with open(os.path.join(save_dir, "opt_state.msgpack"), "rb") as f: opt_state = from_bytes(state.opt_state, f.read()) with open(os.path.join(save_dir, "training_state.json"), "r") as f: training_state = json.load(f) step = training_state["step"] logger.info("checkpoint restored") # reinstantiate inner opt state to avoid type conflict if hasattr(opt_state, "inner_opt_state"): print("restoring state ofmultisteps optimizer") inner_opt_state = reinstantiate_states(opt_state.inner_opt_state) ms_state_dict = {k:getattr(state.opt_state, k) for k in state.opt_state._fields} ms_state_dict["inner_opt_state"] = inner_opt_state opt_state = optax.MultiStepsState(**ms_state_dict) return state.replace(step=step, params=params, opt_state=opt_state)
null
162,790
from ast import Str import logging import math import os import sys import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional import json import shutil from flax import training import numpy as np import datasets from datasets import load_dataset from tqdm import tqdm import jax import jax.profiler import jax.numpy as jnp import optax import transformers import flax from flax import jax_utils, traverse_util from flax.jax_utils import unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key from flax.training.checkpoints import save_checkpoint, restore_checkpoint from flax.serialization import to_bytes, from_bytes from transformers import ( CONFIG_MAPPING, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoTokenizer, FlaxAutoModelForCausalLM, HfArgumentParser, TrainingArguments, is_tensorboard_available, ) from transformers.testing_utils import CaptureLogger from importlib.util import find_spec from utils import PrefetchDataloaderWithFilter, make_batch logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `rotate_checkpoints` function. Write a Python function `def rotate_checkpoints(ckpt_dir:str, save_total_limit:int)` to solve the following problem: Removes older checkpoints so that `save_total_limit` checkpoints are kept Here is the function: def rotate_checkpoints(ckpt_dir:str, save_total_limit:int): "Removes older checkpoints so that `save_total_limit` checkpoints are kept" # TODO: what to remove is decided using step number only, we might want to improve that ckpts = [str(x) for x in Path(ckpt_dir).glob("ckpt-*")] # sort checkpoints by step ckpts_sorted = sorted(ckpts, key=lambda x: int(x.split('-')[-1])) ckpts_to_delete = ckpts_sorted[:-save_total_limit] for ckpt in ckpts_to_delete: logger.info(f"Deleting older checkpoint [{ckpt}] due to save_total_limit ({save_total_limit})") shutil.rmtree(ckpt)
Removes older checkpoints so that `save_total_limit` checkpoints are kept
162,791
import numpy as np import pandas as pd from fastcore.script import * from pathlib import Path def convert_to_gh_downloader(df, path): # select only name, stargazers, and languages columns and save to path df = df[["name", "stargazers", "languages"]] df.to_csv(path / "github_repositories.csv", index=False, header=False)
null
162,792
import os import io from typing import List import json from pathlib import Path import datasets The provided code snippet includes necessary dependencies for implementing the `generate_prompt` function. Write a Python function `def generate_prompt( test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None )` to solve the following problem: Generate a prompt for a given test case. Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51. Here is the function: def generate_prompt( test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None ): """ Generate a prompt for a given test case. Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51. """ _input = "\nQUESTION:\n" with open(prompt_path, "r") as f: data = f.readlines() data = "".join(data) _input += data if starter_path != None: with open(starter_path, "r") as f: data = f.readlines() data = "".join(data) data = "\n" + data # + "\n" _input += data else: # _input += "\n\n" pass with open(test_case_path, "r") as f: data = json.load(f) if not data.get("fn_name"): _input += "\nUse Standard Input format" # \n" else: _input += "\nUse Call-Based format" # \n" _input += "\nANSWER:\n" return _input
Generate a prompt for a given test case. Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51.
162,793
import os import io from typing import List import json from pathlib import Path import datasets def run_reindent(fd_in, fd_out, config): while True: line = fd_in.readline() if not line: break line = line.rstrip('\r\n') # Find indentation style used in file if not set if config['from'] < 0: indent = find_indentation(line, config) if not indent: print(line, file=fd_out) continue indent, newindent = indent # Find current indentation level level = 0 while True: whitespace = line[:len(indent) * (level + 1)] if whitespace == indent * (level + 1): level += 1 else: break content = line[len(indent) * level:] if config['all-tabs']: content = replace_inline_tabs(content, config) line = (newindent * level) + content print(line, file=fd_out) The provided code snippet includes necessary dependencies for implementing the `reindent_code` function. Write a Python function `def reindent_code(codestr)` to solve the following problem: Given code string, reindent it in the same way that the Github dataset was indented (from https://github.com/hendrycks/apps/blob/main/train/dataset_apps/APPSBaseDataset.py) Here is the function: def reindent_code(codestr): """ Given code string, reindent it in the same way that the Github dataset was indented (from https://github.com/hendrycks/apps/blob/main/train/dataset_apps/APPSBaseDataset.py) """ codestr = io.StringIO(codestr) ret = io.StringIO() run_reindent( codestr, ret, config = { "dry-run": False, "help": False, "to": 4, "from": -1, "tabs": True, "encoding": "utf-8", "is-tabs": False, "tabsize": 4, "all-tabs": False } ) return ret.getvalue()
Given code string, reindent it in the same way that the Github dataset was indented (from https://github.com/hendrycks/apps/blob/main/train/dataset_apps/APPSBaseDataset.py)
162,794
import os import pandas as pd from fastcore.script import * from ghapi.all import GhApi GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN") def get_license_info(owner, repo): api = GhApi(owner=owner, repo=repo, token=GITHUB_TOKEN) license = api.licenses.get_for_repo(owner=owner, repo=repo) return license.license.name
null
162,795
import argparse import datasets import lm_dataformat import re import tqdm def get_variables(example): variables = " ".join(re.split(r"\W+", example["text"])) return variables
null
162,796
import argparse import datasets import lm_dataformat import re import tqdm def get_hash(example): variables = " ".join(re.split(r"\W+", example["text"])) return hash(variables)
null
162,797
import argparse import datasets import lm_dataformat import re The provided code snippet includes necessary dependencies for implementing the `get_variables` function. Write a Python function `def get_variables(examples)` to solve the following problem: Convert a code string to a list of variables. We assume a variable is a 'word' with only alphanumeric characters in it. Here is the function: def get_variables(examples): """Convert a code string to a list of variables. We assume a variable is a 'word' with only alphanumeric characters in it.""" variables = [" ".join(re.split(r"\W+", text)) for text in examples["text"]] return {"variables": variables}
Convert a code string to a list of variables. We assume a variable is a 'word' with only alphanumeric characters in it.
162,798
import argparse import datasets import lm_dataformat import re The provided code snippet includes necessary dependencies for implementing the `check_uniques` function. Write a Python function `def check_uniques(example, uniques)` to solve the following problem: If an example is in uniques, return True and remove it from uniques. Here is the function: def check_uniques(example, uniques): """If an example is in uniques, return True and remove it from uniques.""" if example["variables"] in uniques: uniques.remove(example["variables"]) return True else: return False
If an example is in uniques, return True and remove it from uniques.
162,799
import argparse from duplicate_detector import DocumentID, DuplicateDetector from joblib import Parallel, delayed import os import lm_dataformat import tqdm duplicate_detector = DuplicateDetector( args.set_similarity_threshold, args.multiset_similarity_threshold, args.min_num_tokens_per_document, ) duplicate_detector.print_duplicate_clusters_stats(duplicate_clusters) def _process_document(i, doc): code, metadata = doc document_id = DocumentID( index=i, repo_name=metadata["repo_name"], file_name=metadata["file_name"], ) duplicate_detector.add_file(document_id, code)
null
162,800
import chardet import magic import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat import pandas as pd for i in data: if "extensions" not in i: continue lang_exts.extend(i["extensions"]) def split_into_chunks(l, n): n = max(1, n) return [l[i:i + n] for i in range(0, len(l), n)]
null
162,801
import chardet import magic import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat import pandas as pd def filter_by_stars(repo_data, n_stars): return [item for item in repo_data if int(item[1]) >= n_stars]
null
162,802
import chardet import magic import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat import pandas as pd def process_repo(repo_data, repodir, processing_timeout): return timeout(_process_repo, args=(repo_data, repodir), timeout_duration=processing_timeout) def process_repo_list(repo_data, clone_timeout, processing_timeout): out = None try: name, stars, lang = repo_data repodir = f'./.tmp/{name.split("/")[-1]}' # clones master branch of repos with depth 1 (most recent commit only), ignoring any terminal prompts p = subprocess.Popen( f'GIT_TERMINAL_PROMPT=0 git clone --depth 1 --single-branch https://github.com/{name} {repodir}', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) try: p.wait(clone_timeout) except subprocess.TimeoutExpired: print(f'Git clone for {name} timed out ') p.kill() shutil.rmtree(f'{repodir}/.git', ignore_errors=True) # extracts text files from repo and returns them as list : [[text, metadata], ... ] out = process_repo(repo_data, repodir, processing_timeout=processing_timeout) except Exception: err = traceback.format_exc() if verbose: print(err) return out
null
162,803
import chardet import magic import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat import pandas as pd def process_args(): parser = argparse.ArgumentParser( description='CLI for github downloader - A tool for scraping repos as text from github') parser.add_argument('--n_threads', help='number of threads for parallel processing, defaults to cpu_count', default=-1, type=int) parser.add_argument('--n_stars', help='filter repos with less than n_stars stars', default=-1, type=int) parser.add_argument('--chunk_size', help='size of chunks to feed into each thread', default=-1, type=int) parser.add_argument('--clone_timeout', help='timeout for git clone command in seconds', default=150, type=int) parser.add_argument('--processing_timeout', help='timeout for processing repo to text files in seconds', default=150, type=int) parser.add_argument('--commit_freq', help='how often (in number of chunks) to commit the archive file', default=10, type=int) parser.add_argument('-v', '--verbose', help='if flag is present, print errors', action='store_true') return parser.parse_args()
null
162,804
import pandas as pd from fastcore.script import * from joblib import Parallel, delayed from pathlib import Path from subprocess import CalledProcessError, check_output def _run_scorecard(repo): # get results of scorecard results = check_output( [ SCORECARD_PATH, f"--repo=github.com/{repo}", "--checks=Vulnerabilities", "--format=csv", ] ).decode("utf-8") # parse results and convert to propert data types results = results.split("\n")[1] repo, no_vulns, confidence = results.split(",") no_vulns = True if no_vulns == "true" else False confidence = int(confidence) # check results has max confidence. # If not return None else return whether it does not have a vulnerability if confidence < 10: return None else: return no_vulns def run_scorecard( repos_path: Param("Path to the csv containing all of the repos", str) ): repos_path = Path(repos_path) df = pd.read_csv(repos_path).head() # Loop through each repo parrallely and call the scorecard script # TODO: Need to let sleep so GitHub api limit is not exceeded vulnerabilities = Parallel(n_jobs=-1)( delayed(_run_scorecard)(repo) for repo in df["name"] ) df["no_vulnerability"] = vulnerabilities # Save the results to a csv df.to_csv(repos_path.parent / "combined_repos.csv", index=False)
null
162,805
import chardet import magic import lm_dataformat as lmd import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat for i in data: if "extensions" not in i: continue lang_exts.extend(i["extensions"]) def split_into_chunks(l, n): n = max(1, n) return [l[i:i + n] for i in range(0, len(l), n)]
null
162,806
import chardet import magic import lm_dataformat as lmd import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat def filter_by_stars(repo_data, n_stars): return [item for item in repo_data if int(item[1]) >= n_stars]
null
162,807
import chardet import magic import lm_dataformat as lmd import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat bad_extensions = [ 'app', 'bin', 'bmp', 'bz2', 'class', 'csv', 'dat', 'db', 'dll', 'dylib', 'egg', 'eot', 'exe', 'gif', 'gitignore', 'glif', 'gradle', 'gz', 'ico', 'jar', 'jpeg', 'jpg', 'lo', 'lock', 'log', 'mp3', 'mp4', 'nar', 'o', 'ogg', 'otf', 'p', 'pdf', 'png', 'pickle', 'pkl', 'pyc', 'pyd', 'pyo', 'rkt', 'so', 'ss', 'svg', 'tar', 'tsv', 'ttf', 'war', 'webm', 'woff', 'woff2', 'xz', 'zip', 'zst' ] lang_exts = [] def filter_criteria(files): filtered_files = [] for f in files: size = os.path.getsize(f) if '.git' not in f and f[0] is not '.' and \ 'LICENSE' not in f and 'node_modules' not in f and \ '.min.' not in f and f.split('.')[-1] not in bad_extensions and \ f.split('.')[-1] in lang_exts and size
null
162,808
import chardet import magic import lm_dataformat as lmd import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat def process_repo(repo_data, repodir, processing_timeout): def process_repo_list(repo_data, clone_timeout, processing_timeout): out = None try: name, stars, lang = repo_data repodir = f'./.tmp/{name.split("/")[-1]}' # clones master branch of repos with depth 1 (most recent commit only), ignoring any terminal prompts p = subprocess.Popen( f'GIT_TERMINAL_PROMPT=0 git clone --depth 1 --single-branch https://github.com/{name} {repodir}', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) try: p.wait(clone_timeout) except subprocess.TimeoutExpired: print(f'Git clone for {name} timed out ') p.kill() shutil.rmtree(f'{repodir}/.git', ignore_errors=True) # extracts text files from repo and returns them as list : [[text, metadata], ... ] out = process_repo(repo_data, repodir, processing_timeout=processing_timeout) except Exception: err = traceback.format_exc() if verbose: print(err) return out
null
162,809
import chardet import magic import lm_dataformat as lmd import os import random import sys import traceback import shutil import csv import json from multiprocessing import cpu_count, Pool from tqdm import tqdm import argparse import subprocess from itertools import repeat def process_args(): parser = argparse.ArgumentParser( description='CLI for github downloader - A tool for scraping repos as text from github') parser.add_argument('--n_threads', help='number of threads for parallel processing, defaults to cpu_count', default=-1, type=int) parser.add_argument('--n_stars', help='filter repos with less than n_stars stars', default=-1, type=int) parser.add_argument('--chunk_size', help='size of chunks to feed into each thread', default=-1, type=int) parser.add_argument('--clone_timeout', help='timeout for git clone command in seconds', default=150, type=int) parser.add_argument('--processing_timeout', help='timeout for processing repo to text files in seconds', default=150, type=int) parser.add_argument('--commit_freq', help='how often (in number of chunks) to commit the archive file', default=10, type=int) parser.add_argument('-v', '--verbose', help='if flag is present, print errors', action='store_true') return parser.parse_args()
null
162,810
import collections import math def compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation_corpus: list of translations to score. Each translation should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram precisions and brevity penalty. """ matches_by_order = [0] * max_order possible_matches_by_order = [0] * max_order reference_length = 0 translation_length = 0 for (references, translation) in zip(reference_corpus, translation_corpus): reference_length += min(len(r) for r in references) translation_length += len(translation) merged_ref_ngram_counts = collections.Counter() for reference in references: merged_ref_ngram_counts |= _get_ngrams(reference, max_order) translation_ngram_counts = _get_ngrams(translation, max_order) overlap = translation_ngram_counts & merged_ref_ngram_counts for ngram in overlap: matches_by_order[len(ngram) - 1] += overlap[ngram] for order in range(1, max_order + 1): possible_matches = len(translation) - order + 1 if possible_matches > 0: possible_matches_by_order[order - 1] += possible_matches precisions = [0] * max_order for i in range(0, max_order): if smooth: precisions[i] = (matches_by_order[i] + 1.0) / ( possible_matches_by_order[i] + 1.0 ) else: if possible_matches_by_order[i] > 0: precisions[i] = ( float(matches_by_order[i]) / possible_matches_by_order[i] ) else: precisions[i] = 0.0 if min(precisions) > 0: p_log_sum = sum((1.0 / max_order) * math.log(p) for p in precisions) geo_mean = math.exp(p_log_sum) else: geo_mean = 0 ratio = float(translation_length) / reference_length if ratio > 1.0: bp = 1.0 else: bp = math.exp(1 - 1.0 / ratio) bleu = geo_mean * bp bleu_score_dict = { "bleu": bleu, "precision": precisions, "bp": bp, "ratio": ratio, "trans_len": translation_length, "ref_len": reference_length, } return bleu_score_dict # (bleu, precisions, bp, ratio, translation_length, reference_length) The provided code snippet includes necessary dependencies for implementing the `bleu_test_case` function. Write a Python function `def bleu_test_case()` to solve the following problem: A simple functionality test case to evaluate BLEU Here is the function: def bleu_test_case(): """A simple functionality test case to evaluate BLEU""" generated = [[["a", "=", "b", "\n", "y", "=", "a", "+", "1"]]] reference = [["a", "=", "b", "\n", "print", "a"]] score_dict = compute_bleu(generated, reference, smooth=False) return score_dict
A simple functionality test case to evaluate BLEU
162,811
from metrics.bleu import compute_bleu from metrics.parse_check import check_parse Parser = check_parse() def compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation_corpus: list of translations to score. Each translation should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram precisions and brevity penalty. """ matches_by_order = [0] * max_order possible_matches_by_order = [0] * max_order reference_length = 0 translation_length = 0 for (references, translation) in zip(reference_corpus, translation_corpus): reference_length += min(len(r) for r in references) translation_length += len(translation) merged_ref_ngram_counts = collections.Counter() for reference in references: merged_ref_ngram_counts |= _get_ngrams(reference, max_order) translation_ngram_counts = _get_ngrams(translation, max_order) overlap = translation_ngram_counts & merged_ref_ngram_counts for ngram in overlap: matches_by_order[len(ngram) - 1] += overlap[ngram] for order in range(1, max_order + 1): possible_matches = len(translation) - order + 1 if possible_matches > 0: possible_matches_by_order[order - 1] += possible_matches precisions = [0] * max_order for i in range(0, max_order): if smooth: precisions[i] = (matches_by_order[i] + 1.0) / ( possible_matches_by_order[i] + 1.0 ) else: if possible_matches_by_order[i] > 0: precisions[i] = ( float(matches_by_order[i]) / possible_matches_by_order[i] ) else: precisions[i] = 0.0 if min(precisions) > 0: p_log_sum = sum((1.0 / max_order) * math.log(p) for p in precisions) geo_mean = math.exp(p_log_sum) else: geo_mean = 0 ratio = float(translation_length) / reference_length if ratio > 1.0: bp = 1.0 else: bp = math.exp(1 - 1.0 / ratio) bleu = geo_mean * bp bleu_score_dict = { "bleu": bleu, "precision": precisions, "bp": bp, "ratio": ratio, "trans_len": translation_length, "ref_len": reference_length, } return bleu_score_dict # (bleu, precisions, bp, ratio, translation_length, reference_length) The provided code snippet includes necessary dependencies for implementing the `compute_metrics` function. Write a Python function `def compute_metrics(references, generated, lang) -> dict` to solve the following problem: Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. lang(str) : The language generated code belongs to returns: A dicitonary with different metrics intact. Here is the function: def compute_metrics(references, generated, lang) -> dict: """ Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. lang(str) : The language generated code belongs to returns: A dicitonary with different metrics intact. """ metrics_dict = {} # Update as in new metrics are added over here. metrics_dict["smoothed_bleu_4"] = compute_bleu(references, generated, smooth=True) metrics_dict["bleu_4"] = compute_bleu(references, generated, smooth=False) metrics_dict["parse_score"] = Parser(generated, lang)["parse_score"] return metrics_dict
Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. lang(str) : The language generated code belongs to returns: A dicitonary with different metrics intact.
162,812
from tree_sitter import Language, Parser The provided code snippet includes necessary dependencies for implementing the `load_tree_sitter_languages` function. Write a Python function `def load_tree_sitter_languages()` to solve the following problem: Loads language Grammars to evaluate Here is the function: def load_tree_sitter_languages(): """Loads language Grammars to evaluate""" py_parser = Parser() py_parser.set_language(Language('./tree_sitter_utils/build/my-languages.so', 'python')) js_parser = Parser() js_parser.set_language(Language('./tree_sitter_utils/build/my-languages.so', 'javascript')) cpp_parser = Parser() cpp_parser.set_language(Language('./tree_sitter_utils/build/my-languages.so', 'cpp')) go_parser = Parser() go_parser.set_language(Language('./tree_sitter_utils/build/my-languages.so', 'go')) java_parser = Parser() java_parser.set_language(Language('./tree_sitter_utils/build/my-languages.so', 'java')) return { "py" : py_parser, "js" : js_parser, "cpp" : cpp_parser, "go" : go_parser, "java": java_parser }
Loads language Grammars to evaluate
162,813
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum class TimeoutException(Exception): pass def timeout_handler(signum, frame): print("alarm went off") #return raise TimeoutException
null
162,814
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum def parse_args(): parser = argparse.ArgumentParser(description="Utility for testing code generation.") parser.add_argument("-v", "--verbosity-level", action="store", type=int, help="") parser.add_argument("-s", "--source", type=str, default="leetcode", choices=["leetcode", "atcoder", "codewars",], help="which data source to gather from.") parser.add_argument("-d", "--data", type=str, default="question", choices=["question", "q", "solutions", "sol", "s", "starter", "tests", "t"], help="which type of data to receive.") parser.add_argument("-n", "--number", type=int, default=0, help="which problem to query.") args = parser.parse_args() return args
null
162,815
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum def get_valid_problems(data_dir="leetcode"): # these are unnecessary atm if data_dir == "leetcode": root = os.path.join(args.source, "data") elif data_dir == "atcoder": pass root = os.path.join(data_dir, "data") if os.path.exists(os.path.join(data_dir, "valid_problems.json")): with open(os.path.join(data_dir, "valid_problems.json"), "r") as f: return json.load(f) # after we compute it once let's save it and load that instead # TODO determine if might be better to reload each time tmp = os.listdir(root) valid_probs = [] for folder in tmp: prob_path = os.path.join(root, folder) files = os.listdir(prob_path) #TODO add more validity checks if "input_output.json" in files or "sols.json" in files: valid_probs.append(prob_path) valid_probs = sorted(valid_probs) #with open(os.path.join(args.source,"valid_problems.json"), "w") as f: # json.dump(valid_probs, f) return valid_probs
null
162,816
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum def get_question(problem_list, prob_index): root = problem_list[prob_index] #print("get q", root) if os.path.exists(os.path.join(root, "question.txt")): with open(os.path.join(root, "question.txt")) as f: question = f.readlines() else: print("question prompt not found") question = "" question = "".join(question) return question
null
162,817
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum def get_solutions(problem_list, prob_index): root = problem_list[prob_index] if os.path.exists(os.path.join(root, "solutions.json")): with open(os.path.join(root, "solutions.json")) as f: sols = json.load(f) return sols
null
162,818
import argparse import json import os import sys import io import faulthandler from datetime import datetime import signal import numpy as np from io import StringIO from typing import get_type_hints from typing import List, Tuple from unittest.mock import patch, mock_open from pyext import RuntimeModule from enum import Enum class CODE_TYPE(Enum): call_based = 0 standard_input = 1 signal.signal(signal.SIGALRM, timeout_handler) timeout = 4 class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() # Make closing the StringIO a no-op self._stringio.close = lambda x: 1 return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout def custom_compare_(output, ground_truth): if isinstance(output, list): output_1 = "\n".join(output) if stripped_string_compare(output_1, ground_truth): return True if isinstance(output, list): output_2 = [o.lstrip().rstrip() for o in output] output_2 = "\n".join(output_2) if stripped_string_compare(output_2, ground_truth): return True return False def call_method(method, inputs): if isinstance(inputs, list): inputs = "\n".join(inputs) inputs_line_iterator = iter(inputs.split("\n")) # sys.setrecursionlimit(10000) # @patch('builtins.input', side_effect=inputs.split("\n")) # @patch('sys.stdout.write', print) def _inner_call_method(_method): try: return _method() except SystemExit as e: pass finally: pass return _inner_call_method(method) The provided code snippet includes necessary dependencies for implementing the `run_test` function. Write a Python function `def run_test(prob_path:str=None, problem_list:List[str]=None, prob_index:int=None, test:str=None, debug:bool=False)` to solve the following problem: if test is not None it'll try to run the code. otherwise it'll just return an input and output pair. Here is the function: def run_test(prob_path:str=None, problem_list:List[str]=None, prob_index:int=None, test:str=None, debug:bool=False): """ if test is not None it'll try to run the code. otherwise it'll just return an input and output pair. """ if prob_path is None and problem_list is None: print("please provide either prob_path or problem_list") exit() if debug: print(f"start = {datetime.now().time()}") if prob_path is not None: root = prob_path elif problem_list is not None: root = problem_list[prob_index] if os.path.exists(os.path.join(root, "input_output.json")): with open(os.path.join(root, "input_output.json")) as f: in_outs = json.load(f) if debug: print(f"test cases json = {in_outs['inputs']} {in_outs['outputs']}") if in_outs.get("fn_name") is None: which_type = CODE_TYPE.standard_input # Standard input method_name = None else: which_type = CODE_TYPE.call_based # Call-based method_name = in_outs["fn_name"] if debug: print(f"loaded json = {datetime.now().time()}") #else: # continue if test is None: return in_outs elif test is not None: results = [] sol = "import sys\nimport time\nimport itertools\nfrom itertools import accumulate, product, permutations, combinations\nimport collections\nfrom collections import Counter, OrderedDict, deque, defaultdict, ChainMap\nfrom functools import lru_cache\nimport math\nfrom math import sqrt, sin, cos, tan, ceil, fabs, floor, gcd, exp, log, log2\nimport fractions\nfrom typing import List, Tuple\nimport numpy as np\nimport random\nimport heapq\nfrom heapq import *\n" if debug: print(f"loading test code = {datetime.now().time()}") if which_type == CODE_TYPE.call_based: sol += test if debug: # or True: print(f"sol = {sol}") signal.alarm(timeout) try: tmp_sol = RuntimeModule.from_string("tmp_sol", "", sol) if "class Solution" not in test: tmp = tmp_sol else: tmp = tmp_sol.Solution() signal.alarm(0) except Exception as e: signal.alarm(0) print(f"type 0 compilation error = {e}") results.append(-2) return results signal.alarm(0) elif which_type == CODE_TYPE.standard_input: # sol tmp_test = test.split("\n") new_test = [] for x in tmp_test: if (not x.startswith("from ")) and (not x.startswith("import ")): new_test.append("\t" + x + "\n") else: new_test.append(x + "\n") tmp_test = new_test new_test = "" started = False for i in tmp_test: if i.startswith("\t") and not started: new_test += "stdin = sys.stdin\nstdout = sys.stdout\n" new_test += "def code():\n" new_test += i started = True elif started and ((i.startswith("from ")) or (i.startswith("import "))): new_test += "\t" + i else: new_test += i tmp_test = new_test sol += tmp_test if debug: print(f"sol = {sol}") # print(f"{o}") method_name = "code" signal.alarm(timeout) try: tmp_sol = RuntimeModule.from_string("tmp_sol", "", sol) tmp = tmp_sol signal.alarm(0) except Exception as e: signal.alarm(0) print(f"type 1 compilation error = {e}") results.append(-2) return results signal.alarm(0) if debug: print(f"get method = {datetime.now().time()}") try: method = getattr(tmp, method_name) # get_attr second arg must be str except: signal.alarm(0) e = sys.exc_info() print(f"unable to get function error = {e}") return results for index, inputs in enumerate(in_outs["inputs"]): # JSON forces dictionaries to have string keys; this undoes this (assuming a singleton list) try: if isinstance(inputs[0], dict): inputs = [{int(k): v for k,v in inputs[0].items()}] except: True try: if isinstance(in_outs["outputs"][index], dict): in_outs["outputs"][index] = [{int(k): v for k,v in in_outs["outputs"][index].items()}] except: True try: if isinstance(in_outs["outputs"][index][0], dict): in_outs["outputs"][index] = [{int(k): v for k,v in in_outs["outputs"][index][0].items()}] except: True if debug: print(f"time: {datetime.now().time()} testing index = {index} inputs = {inputs}, {type(inputs)}. type = {which_type}") if which_type == CODE_TYPE.call_based: # Call-based signal.alarm(timeout) faulthandler.enable() try: # print("------------") # print(inputs) output = method(*inputs) # ground truth sequences are not tuples if isinstance(output, tuple): output = list(output) tmp_result = output == in_outs["outputs"][index] if isinstance(in_outs["outputs"][index], list) and in_outs["outputs"][index]: tmp_result = tmp_result or (output == in_outs["outputs"][index][0]) # ground truth sequences are not tuples try: if isinstance(output[0], tuple): tmp_result = tmp_result or ([list(x) for x in output] == in_outs["outputs"][index][0]) except: True results.append(tmp_result) # reset the alarm signal.alarm(0) except Exception as e: signal.alarm(0) faulthandler.disable() print(f"Standard input runtime error or time limit exceeded error = {e}") results.append(-1) continue faulthandler.disable() signal.alarm(0) if debug: print(f"outputs = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") elif which_type == CODE_TYPE.standard_input: # Standard input faulthandler.enable() signal.alarm(timeout) passed = False if isinstance(inputs, list): inputs = "\n".join(inputs) if isinstance(in_outs['outputs'][index], list): in_outs['outputs'][index] = "\n".join(in_outs['outputs'][index]) with Capturing() as output: try: call_method(method, inputs) # reset the alarm signal.alarm(0) passed = True except Exception as e: # runtime error or took too long signal.alarm(0) print(f"Call-based runtime error or time limit exceeded error = {repr(e)}{e}") results.append(-1) signal.alarm(0) if not passed: if debug: nl = "\n" if not isinstance(inputs, list): print(f"not passed output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") else: print(f"not passed output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") continue if passed and debug: print(f"==> output = {output}, test outputs = {in_outs['outputs'][index]}") if custom_compare_(output, in_outs['outputs'][index]): tmp_result = True results.append(tmp_result) continue # ground truth sequences are expressed as lists not tuples if isinstance(output, tuple): output = list(output) tmp_result = False try: tmp_result = (output == [in_outs["outputs"][index]]) if isinstance(in_outs["outputs"][index], list): tmp_result = tmp_result or (output == in_outs["outputs"][index]) if isinstance(output[0], str): tmp_result = tmp_result or ([e.strip() for e in output] == in_outs["outputs"][index]) except Exception as e: print(f"Failed check1 exception = {e}") pass if tmp_result == True: results.append(tmp_result) continue # try one more time without \n if isinstance(in_outs["outputs"][index], list): for tmp_index, i in enumerate(in_outs["outputs"][index]): in_outs["outputs"][index][tmp_index] = i.split("\n") in_outs["outputs"][index][tmp_index] = [x.strip() for x in in_outs["outputs"][index][tmp_index] if x] else: in_outs["outputs"][index] = in_outs["outputs"][index].split("\n") in_outs["outputs"][index] = list(filter(len, in_outs["outputs"][index])) in_outs["outputs"][index] = list(map(lambda x:x.strip(), in_outs["outputs"][index])) try: tmp_result = (output == [in_outs["outputs"][index]]) if isinstance(in_outs["outputs"][index], list): tmp_result = tmp_result or (output == in_outs["outputs"][index]) except Exception as e: print(f"Failed check2 exception = {e}") pass if tmp_result == True: results.append(tmp_result) continue # try by converting the output into a split up list too if isinstance(output, list): output = list(filter(len, output)) if debug: nl = "\n" if not isinstance(inputs, list): print(f"output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") else: print(f"output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") if tmp_result == True: results.append(tmp_result) continue try: tmp_result = (output == [in_outs["outputs"][index]]) if isinstance(in_outs["outputs"][index], list): tmp_result = tmp_result or (output == in_outs["outputs"][index]) except Exception as e: print(f"Failed check3 exception = {e}") pass try: output_float = [float(e) for e in output] gt_float = [float(e) for e in in_outs['outputs'][index]] tmp_result = tmp_result or ((len(output_float) == len(gt_float)) and np.allclose(output_float, gt_float)) except Exception as e: pass try: if isinstance(output[0], list): output_float = [float(e) for e in output[0]] gt_float = [float(e) for e in in_outs['outputs'][index][0]] tmp_result = tmp_result or ((len(output_float) == len(gt_float)) and np.allclose(output_float, gt_float)) except Exception as e: pass if tmp_result == True: results.append(tmp_result) continue # try by converting the stuff into split up list if isinstance(in_outs["outputs"][index], list): for tmp_index, i in enumerate(in_outs["outputs"][index]): in_outs["outputs"][index][tmp_index] = set(i.split()) else: in_outs["outputs"][index] = set(in_outs["outputs"][index].split()) try: tmp_result = (output == in_outs["outputs"][index]) except Exception as e: print(f"Failed check4 exception = {e}") continue if tmp_result == True: results.append(tmp_result) continue # try by converting the output into a split up list too if isinstance(output, list): for tmp_index, i in enumerate(output): output[tmp_index] = i.split() output = list(filter(len, output)) for tmp_index, i in enumerate(output): output[tmp_index] = set(i) else: output = output.split() output = list(filter(len, output)) output = set(output) try: tmp_result = (set(frozenset(s) for s in output) == set(frozenset(s) for s in in_outs["outputs"][index])) except Exception as e: print(f"Failed check5 exception = {e}") # if they are all numbers, round so that similar numbers are treated as identical try: tmp_result = tmp_result or (set(frozenset(round(float(t),3) for t in s) for s in output) ==\ set(frozenset(round(float(t),3) for t in s) for s in in_outs["outputs"][index])) except Exception as e: print(f"Failed check6 exception = {e}") if tmp_result == True and debug: print("PASSED") results.append(tmp_result) if debug: nl = "\n" if not isinstance(inputs, list): print(f"output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") else: print(f"output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}") return results
if test is not None it'll try to run the code. otherwise it'll just return an input and output pair.
162,819
import io import json import logging import math import numpy as np import os import pprint import sys import testing_util as test_util import time from datetime import datetime, date from tqdm import tqdm from typing import List def print_results(results, args): res = [] per_prob_res = [] all_correct = [] for index in results: res.extend(results[index]) per_prob_res.append(np.mean(results[index])) all_correct.append(np.all(results[index])) tmp_results = res compile_errors = len(tmp_results[tmp_results==-2]) runtime_errors = len(tmp_results[tmp_results==-1]) failures = len(tmp_results[tmp_results==False]) successes = len(tmp_results[tmp_results==True]) total_testcases = len(res) if args.debug: print(f"number of compile errors = {compile_errors} avg = {compile_errors / total_testcases }") print(f"number of runtime errors = {runtime_errors} avg = {runtime_errors / total_testcases}") print(f"number of test cases run = {total_testcases}") print(f"Test Case Average (average accuracy over problems) = {np.mean(per_prob_res)}") print(f"Strict Accuracy (all test cases passed / total problems) = {np.mean(all_correct)}")
null
162,820
import io import json import logging import math import numpy as np import os import pprint import sys import testing_util as test_util import time from datetime import datetime, date from tqdm import tqdm from typing import List def eval_and_save_problems(args): with open(args.test_loc, "r") as f: problems = sorted(json.load(f)) print(len(problems)) gpt_codes = {} gpt_bleu = {} gpt_codebleu = {} results = {} codes_loc = os.path.join(args.save, f"all_codes.json") if not os.path.exists(codes_loc): codes_loc = os.path.join(args.save, f"{args.start}-{args.end}_codes.json") if os.path.exists(codes_loc): results_loc = os.path.join(args.save, f"all_results.json") else: results_loc = os.path.join(args.save, f"{args.start}-{args.end}_results.json") print(codes_loc, results_loc) with open(codes_loc, "r") as f: gpt_codes = json.load(f) if args.index: problems = [problems[args.index]] else: if args.start > len(problems) or args.start < 0: print(f"start index {args.start} > number of problems {len(problems)}") return start = args.start if args.end is None or args.end > len(problems): end = len(problems) else: end = args.end problems = problems[start:end] if args.stop_early: problems = problems[:args.stop_early] # main eval loop for index, problem in enumerate(tqdm(problems)): try: if args.debug: print(f"\n\nproblem path = {problem}") output_str = gpt_codes[str(index+args.start)] except: print("CANNOT FIND OUTPUT_STR FOR", problem) continue prob_path = os.path.join(args.root, problem) with open(os.path.join(prob_path, "solutions.json"), "r") as f: sols = json.load(f) if not os.path.exists(args.save): os.makedirs(args.save) res = [] for o_idx, o in enumerate(output_str): if args.debug: print(f"\nTesting solution {o_idx}") curr_res = [-2] try: curr_res = test_util.run_test(prob_path=prob_path, test=o, debug=args.debug) fixed = [] for e in curr_res: if isinstance(e, np.ndarray): e = e.item(0) if isinstance(e, np.bool_): e = bool(e) fixed.append(e) curr_res = fixed if not np.all(curr_res): print(f"Results were not all True: {curr_res}") except Exception as e: print(f"test framework exception = {repr(e)}{e}\n") break finally: assert isinstance(curr_res, list) res.append(curr_res) if args.debug: print(f"\nHow to read results [-2] = compile error, [-1] = runtime error [False] = failed test case [True] = passed test case") #print(f"results = {res}") results[index+args.start+args.index] = res with open(results_loc, "w") as f: try: f.write(json.dumps(results)) except Exception as e: import pdb; pdb.set_trace() print("didn't save problem due to {e}") return results
null
162,822
from metrics.bleu import compute_bleu def compute_exact_match(references, generated) -> float: """ Computes Exact Match Accuracy. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. returns: exact_match_accuracy : Float """ assert ( len(references[0]) == len(generated), "Number of Samples should be equal in References and Synthesized Outputs..", ) exact_match_count = 0.0 for gen, ref in zip(generated, references[0]): if gen == ref: exact_match_count += 1 exact_match_acc = exact_match_count / len(generated) return exact_match_acc def compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation_corpus: list of translations to score. Each translation should be tokenized into a list of tokens. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram precisions and brevity penalty. """ matches_by_order = [0] * max_order possible_matches_by_order = [0] * max_order reference_length = 0 translation_length = 0 for (references, translation) in zip(reference_corpus, translation_corpus): reference_length += min(len(r) for r in references) translation_length += len(translation) merged_ref_ngram_counts = collections.Counter() for reference in references: merged_ref_ngram_counts |= _get_ngrams(reference, max_order) translation_ngram_counts = _get_ngrams(translation, max_order) overlap = translation_ngram_counts & merged_ref_ngram_counts for ngram in overlap: matches_by_order[len(ngram) - 1] += overlap[ngram] for order in range(1, max_order + 1): possible_matches = len(translation) - order + 1 if possible_matches > 0: possible_matches_by_order[order - 1] += possible_matches precisions = [0] * max_order for i in range(0, max_order): if smooth: precisions[i] = (matches_by_order[i] + 1.0) / ( possible_matches_by_order[i] + 1.0 ) else: if possible_matches_by_order[i] > 0: precisions[i] = ( float(matches_by_order[i]) / possible_matches_by_order[i] ) else: precisions[i] = 0.0 if min(precisions) > 0: p_log_sum = sum((1.0 / max_order) * math.log(p) for p in precisions) geo_mean = math.exp(p_log_sum) else: geo_mean = 0 ratio = float(translation_length) / reference_length if ratio > 1.0: bp = 1.0 else: bp = math.exp(1 - 1.0 / ratio) bleu = geo_mean * bp bleu_score_dict = { "bleu": bleu, "precision": precisions, "bp": bp, "ratio": ratio, "trans_len": translation_length, "ref_len": reference_length, } return bleu_score_dict # (bleu, precisions, bp, ratio, translation_length, reference_length) The provided code snippet includes necessary dependencies for implementing the `compute_metrics` function. Write a Python function `def compute_metrics(references, generated) -> dict` to solve the following problem: Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. returns: A dicitonary with different metrics intact. Here is the function: def compute_metrics(references, generated) -> dict: """ Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. returns: A dicitonary with different metrics intact. """ metrics_dict = { "smoothed_bleu_4": None, "bleu_4": None, "exact_match_acc": None, } # Update as in new metrics are computed. metrics_dict["smoothed_bleu_4"] = compute_bleu(references, generated, smooth=True) metrics_dict["bleu_4"] = compute_bleu(references, generated, smooth=False) metrics_dict["exact_match_acc"] = compute_exact_match(references, generated) return metrics_dict
Calculates various metrics and returns the calculated dict of these matrics. args: reference: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. translation: list of translations to score. Each translation should be tokenized into a list of tokens. returns: A dicitonary with different metrics intact.
162,823
import io import json import logging import math import random import numpy as np import os import pprint import sys import time import transformers import torch from apps_utils.reindent import run as run_reindent from datetime import datetime, date from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `reindent_code` function. Write a Python function `def reindent_code(codestr)` to solve the following problem: Given code string, reindent it in the same way that the Github dataset was indented Here is the function: def reindent_code(codestr): """ Given code string, reindent it in the same way that the Github dataset was indented """ codestr = io.StringIO(codestr) ret = io.StringIO() run_reindent( codestr, ret, config={ "dry-run": False, "help": False, "to": 10, "from": -1, "tabs": True, "encoding": "utf-8", "is-tabs": False, "tabsize": 10, "all-tabs": False, }, ) return ret.getvalue()
Given code string, reindent it in the same way that the Github dataset was indented
162,824
import io import json import logging import math import random import numpy as np import os import pprint import sys import time import transformers import torch from apps_utils.reindent import run as run_reindent from datetime import datetime, date from tqdm import tqdm def generate_prompt( test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None ): _input = "\nQUESTION:\n" with open(prompt_path, "r") as f: data = f.readlines() data = "".join(data) _input += data if starter_path != None: with open(starter_path, "r") as f: data = f.readlines() data = "".join(data) data = "\n" + data # + "\n" _input += data else: # _input += "\n\n" pass with open(test_case_path, "r") as f: data = json.load(f) if not data.get("fn_name"): _input += "\nUse Standard Input format" # \n" else: _input += "\nUse Call-Based format" # \n" _input += "\nANSWER:\n" return _input
null
162,825
from __future__ import print_function import sys import getopt import codecs import tempfile import shutil import os def run(fd_in, fd_out, config): from reindent_4_spaces import Reindenter import io inter = io.StringIO() ri = Reindenter(fd_in) ri.run() ri.write(inter) fd_in = inter fd_in.seek(0) while True: line = fd_in.readline() if not line: break line = line.rstrip('\r\n') # Find indentation style used in file if not set if config['from'] < 0: indent = find_indentation(line, config) if not indent: print(line, file=fd_out) continue indent, newindent = indent # Find current indentation level level = 0 while True: whitespace = line[:len(indent) * (level + 1)] if whitespace == indent * (level + 1): level += 1 else: break content = line[len(indent) * level:] if config['all-tabs']: content = replace_inline_tabs(content, config) line = (newindent * level) + content print(line, file=fd_out) # print(config) def run_files(filenames, config): for filename in filenames: with codecs.open(filename, encoding=config['encoding']) as fd_in: if config['dry-run']: print("Filename: %s" % filename) fd_out = sys.stdout else: fd_out = tempfile.NamedTemporaryFile(mode='wb', delete=False) fd_out.close() fd_out = codecs.open(fd_out.name, "wb", encoding=config['encoding']) run(fd_in, fd_out, config) if not config["dry-run"]: fd_out.close() shutil.copy(fd_out.name, filename) os.remove(fd_out.name)
null
162,826
import sys import os.path import pkgutil import shutil import tempfile from base64 import b85decode def determine_pip_install_arguments(): implicit_pip = True implicit_setuptools = True implicit_wheel = True # Check if the user has requested us not to install setuptools if "--no-setuptools" in sys.argv or os.environ.get("PIP_NO_SETUPTOOLS"): args = [x for x in sys.argv[1:] if x != "--no-setuptools"] implicit_setuptools = False else: args = sys.argv[1:] # Check if the user has requested us not to install wheel if "--no-wheel" in args or os.environ.get("PIP_NO_WHEEL"): args = [x for x in args if x != "--no-wheel"] implicit_wheel = False # We only want to implicitly install setuptools and wheel if they don't # already exist on the target platform. if implicit_setuptools: try: import setuptools # noqa implicit_setuptools = False except ImportError: pass if implicit_wheel: try: import wheel # noqa implicit_wheel = False except ImportError: pass # Add any implicit installations to the end of our args if implicit_pip: args += ["pip"] if implicit_setuptools: args += ["setuptools"] if implicit_wheel: args += ["wheel"] return ["install", "--upgrade", "--force-reinstall"] + args def monkeypatch_for_cert(tmpdir): """Patches `pip install` to provide default certificate with the lowest priority. This ensures that the bundled certificates are used unless the user specifies a custom cert via any of pip's option passing mechanisms (config, env-var, CLI). A monkeypatch is the easiest way to achieve this, without messing too much with the rest of pip's internals. """ from pip._internal.commands.install import InstallCommand # We want to be using the internal certificates. cert_path = os.path.join(tmpdir, "cacert.pem") with open(cert_path, "wb") as cert: cert.write(pkgutil.get_data("pip._vendor.certifi", "cacert.pem")) install_parse_args = InstallCommand.parse_args def cert_parse_args(self, args): if not self.parser.get_default_values().cert: # There are no user provided cert -- force use of bundled cert self.parser.defaults["cert"] = cert_path # calculated above return install_parse_args(self, args) InstallCommand.parse_args = cert_parse_args def main(): tmpdir = None try: # Create a temporary working directory tmpdir = tempfile.mkdtemp() # Unpack the zipfile into the temporary directory pip_zip = os.path.join(tmpdir, "pip.zip") with open(pip_zip, "wb") as fp: fp.write(b85decode(DATA.replace(b"\n", b""))) # Add the zipfile to sys.path so that we can import it sys.path.insert(0, pip_zip) # Run the bootstrap bootstrap(tmpdir=tmpdir) finally: # Clean up our temporary working directory if tmpdir: shutil.rmtree(tmpdir, ignore_errors=True) def bootstrap(tmpdir): monkeypatch_for_cert(tmpdir) # Execute the included pip and use it to install the latest pip and # setuptools from PyPI from pip._internal.cli.main import main as pip_entry_point args = determine_pip_install_arguments() sys.exit(pip_entry_point(args))
null
162,827
import json from fastcore.script import * from human_eval.data import write_jsonl, read_problems from human_eval.evaluation import evaluate_functional_correctness from pathlib import Path from tqdm.auto import tqdm from transformers import ( AutoTokenizer, # FlaxGPTNeoForCausalLM, GPTNeoForCausalLM ) def generate_text(prompt, n, tokenizer, model, include_prompt=True): inputs = tokenizer(prompt, truncation=True, max_length=MAX_TOKS, return_tensors="pt").to("cuda") output_seq = model.generate( input_ids=inputs.input_ids, max_length=MAX_TOKS, max_new_tokens=MAX_NEW_TOKS, do_sample=True, temperature=0.8, num_return_sequences=n ) outputs = tokenizer.batch_decode(output_seq, skip_special_tokens=False) generated_text = [] for o in outputs: cleaned = clean_text(o.replace(prompt, "")) generated_text.append(prompt + cleaned if include_prompt else cleaned) return generated_text def _eval_human_eval(path, out_path, tokenizer, model): problems = read_problems(str(path)) num_samples_per_task = 10 samples = [] for task_id in tqdm(list(problems.keys())): for text in generate_text( problems[task_id]["prompt"], num_samples_per_task, tokenizer, model, include_prompt=False, ): samples.append(dict(task_id=task_id, completion=text)) write_jsonl(str(out_path / "human_eval.jsonl"), samples) # test out generated functions results = evaluate_functional_correctness(str(out_path / "human_eval.jsonl"), [1, 2, 5], 4, 3.0, str(path)) print(results)
null
162,828
from __future__ import print_function import sys import getopt import codecs import tempfile import shutil import os def run(fd_in, fd_out, config): def run_files(filenames, config): for filename in filenames: with codecs.open(filename, encoding=config['encoding']) as fd_in: if config['dry-run']: print("Filename: %s" % filename) fd_out = sys.stdout else: fd_out = tempfile.NamedTemporaryFile(mode='wb', delete=False) fd_out.close() fd_out = codecs.open(fd_out.name, "wb", encoding=config['encoding']) run(fd_in, fd_out, config) if not config["dry-run"]: fd_out.close() shutil.copy(fd_out.name, filename) os.remove(fd_out.name)
null
162,829
import time, os, sys def logo(): logo0 = r''' ______ __ _______ __ / \ | \ | \ | \ | $$$$$$\ ______ ______ \$$ _______ ______ | $$$$$$$\ ______ ______ _| $$_ | $$___\$$ / \ / \ | \| \ / \ | $$__/ $$ / \ / \| $$ \ \$$ \ | $$$$$$\| $$$$$$\| $$| $$$$$$$\| $$$$$$\| $$ $$| $$$$$$\| $$$$$$\\$$$$$$ _\$$$$$$\| $$ | $$| $$ \$$| $$| $$ | $$| $$ | $$| $$$$$$$\| $$ | $$| $$ | $$ | $$ __ | \__| $$| $$__/ $$| $$ | $$| $$ | $$| $$__| $$| $$__/ $$| $$__/ $$| $$__/ $$ | $$| \ \$$ $$| $$ $$| $$ | $$| $$ | $$ \$$ $$| $$ $$ \$$ $$ \$$ $$ \$$ $$ \$$$$$$ | $$$$$$$ \$$ \$$ \$$ \$$ _\$$$$$$$ \$$$$$$$ \$$$$$$ \$$$$$$ \$$$$ | $$ | \__| $$ | $$ \$$ $$ [+] V2.51-2024年 龙年新春贺岁版 \$$ \$$$$$$ [+] 感谢一路上支持和关注我们的师傅 ______ / \ +-------------------------------------+ | $$$$$$\ _______ ______ _______ + Version: 2.51 + | $$___\$$ / \| \ | \ + Author: 曾哥(@AabyssZG) + \$$ \ | $$$$$$$ \$$$$$$\| $$$$$$$\ + Whoami: https://github.com/AabyssZG + _\$$$$$$\| $$ / $$| $$ | $$ +-------------------------------------+ | \__| $$| $$_____| $$$$$$$| $$ | $$ + 多进程速度提升: Fkalis + \$$ $$ \$$ \\$$ $$| $$ | $$ + Whoami: https://github.com/FFR66 + \$$$$$$ \$$$$$$$ \$$$$$$$ \$$ \$$ +-------------------------------------+ ''' print(logo0)
null
162,830
from inc import output, run, vul, console import requests, sys, json from termcolor import cprint import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() print(header_new) def SpringBoot_Scan_Proxy(args): if args.proxy: proxies = { "http": "http://%(proxy)s/" % {'proxy': args.proxy}, "https": "http://%(proxy)s/" % {'proxy': args.proxy} } cprint(f"=====检测代理可用性中=====", "cyan") testurl = "https://www.baidu.com/" headers = {"User-Agent": "Mozilla/5.0"} # 响应头 try: requests.packages.urllib3.disable_warnings() res = requests.get(testurl, timeout=10, proxies=proxies, verify=False, headers=headers) print(res.status_code) # 发起请求,返回响应码 if res.status_code == 200: print("GET www.baidu.com 状态码为:" + str(res.status_code)) cprint(f"[+] 代理可用,马上执行!", "cyan") if args.urlfile: proxies = f'http://{args.proxy}' SpringBoot_Scan_Header(args, proxies) except KeyboardInterrupt: print("Ctrl + C 手动终止了进程") sys.exit() except Exception as e: print('error:', e) cprint(f"[-] 代理不可用,请更换代理!", "magenta") sys.exit() else: proxies = '' SpringBoot_Scan_Header(args, proxies)
null
162,831
from inc import output, console, run ,proxycheck import re, binascii, argparse, sys, time def get_parser(): parser = argparse.ArgumentParser(usage='python3 SpringBoot-Scan.py',description='SpringBoot-Scan: 针对SpringBoot的开源渗透框架',) p = parser.add_argument_group('SpringBoot-Scan 的参数') p.add_argument("-u", "--url", type=str, help="对单一URL进行信息泄露扫描") p.add_argument("-uf", "--urlfile", type=str, help="读取目标TXT进行信息泄露扫描") p.add_argument("-v", "--vul", type=str, help="对单一URL进行漏洞利用") p.add_argument("-vf", "--vulfile", type=str, help="读取目标TXT进行批量漏洞扫描") p.add_argument("-d", "--dump", type=str, help="扫描并下载SpringBoot敏感文件(可提取敏感信息)") p.add_argument("-p", "--proxy", type=str, default='', help="使用HTTP代理") p.add_argument("-z", "--zoomeye", type=str, default='', help="使用ZoomEye导出Spring框架资产") p.add_argument("-f", "--fofa", type=str, default='', help="使用Fofa导出Spring框架资产") p.add_argument("-y", "--hunter", type=str, default='', help="使用Hunter导出Spring框架资产") p.add_argument("-t", "--newheader", type=str, help="从TXT文件中导入自定义HTTP头部") args = parser.parse_args() return args
null
162,832
from modules import script_callbacks from scripts.wav2lip_uhq_extend_paths import wav2lip_uhq_sys_extend def wav2lip_uhq_sys_extend(): def on_ui_tabs(): def init_wav2lip_uhq(): wav2lip_uhq_sys_extend() from ui import on_ui_tabs script_callbacks.on_ui_tabs(on_ui_tabs)
null
162,833
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def load_wav(path, sr): return librosa.core.load(path, sr=sr)[0]
null
162,834
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def save_wav(wav, path, sr): wav *= 32767 / max(0.01, np.max(np.abs(wav))) wavfile.write(path, sr, wav.astype(np.int16))
null
162,835
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def save_wavenet_wav(wav, path, sr): librosa.output.write_wav(path, wav, sr=sr)
null
162,836
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def inv_preemphasis(wav, k, inv_preemphasize=True): if inv_preemphasize: return signal.lfilter([1], [1, -k], wav) return wav
null
162,837
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def preemphasis(wav, k, preemphasize=True): if preemphasize: return signal.lfilter([1, -k], [1], wav) return wav def _stft(y): if hp.use_lws: return _lws_processor(hp).stft(y).T else: return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size) def _amp_to_db(x): min_level = np.exp(hp.min_level_db / 20 * np.log(10)) return 20 * np.log10(np.maximum(min_level, x)) def _normalize(S): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value, -hp.max_abs_value, hp.max_abs_value) else: return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value) assert S.max() <= 0 and S.min() - hp.min_level_db >= 0 if hp.symmetric_mels: return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value else: return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)) def linearspectrogram(wav): D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) S = _amp_to_db(np.abs(D)) - hp.ref_level_db if hp.signal_normalization: return _normalize(S) return S
null
162,838
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def preemphasis(wav, k, preemphasize=True): if preemphasize: return signal.lfilter([1, -k], [1], wav) return wav def _stft(y): if hp.use_lws: return _lws_processor(hp).stft(y).T else: return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size) def _linear_to_mel(spectogram): global _mel_basis if _mel_basis is None: _mel_basis = _build_mel_basis() return np.dot(_mel_basis, spectogram) def _amp_to_db(x): min_level = np.exp(hp.min_level_db / 20 * np.log(10)) return 20 * np.log10(np.maximum(min_level, x)) def _normalize(S): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value, -hp.max_abs_value, hp.max_abs_value) else: return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value) assert S.max() <= 0 and S.min() - hp.min_level_db >= 0 if hp.symmetric_mels: return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value else: return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)) def melspectrogram(wav): D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) S = _amp_to_db(_linear_to_mel(np.abs(D))) - hp.ref_level_db if hp.signal_normalization: return _normalize(S) return S
null
162,839
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M The provided code snippet includes necessary dependencies for implementing the `pad_lr` function. Write a Python function `def pad_lr(x, fsize, fshift)` to solve the following problem: Compute left and right padding Here is the function: def pad_lr(x, fsize, fshift): """Compute left and right padding """ M = num_frames(len(x), fsize, fshift) pad = (fsize - fshift) T = len(x) + 2 * pad r = (M - 1) * fshift + fsize - T return pad, pad + r
Compute left and right padding
162,840
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def librosa_pad_lr(x, fsize, fshift): return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]
null
162,841
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def _db_to_amp(x): return np.power(10.0, (x) * 0.05)
null
162,842
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from scripts.wav2lip.hparams import hparams as hp def _denormalize(D): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return (((np.clip(D, -hp.max_abs_value, hp.max_abs_value) + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((np.clip(D, 0, hp.max_abs_value) * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db) if hp.symmetric_mels: return (((D + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((D * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db)
null
162,855
import torch import torch.nn.functional as F import os import sys import cv2 import random import datetime import math import argparse import numpy as np import scipy.io as sio import zipfile from .net_s3fd import s3fd from .bbox import * import numpy as np import torch def batch_decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ boxes = torch.cat(( priors[:, :, :2] + loc[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, 2:] * torch.exp(loc[:, :, 2:] * variances[1])), 2) boxes[:, :, :2] -= boxes[:, :, 2:] / 2 boxes[:, :, 2:] += boxes[:, :, :2] return boxes def batch_detect(net, imgs, device): imgs = imgs - np.array([104, 117, 123]) imgs = imgs.transpose(0, 3, 1, 2) if 'cuda' in device: torch.backends.cudnn.benchmark = True imgs = torch.from_numpy(imgs).float().to(device) BB, CC, HH, WW = imgs.size() with torch.no_grad(): olist = net(imgs) bboxlist = [] for i in range(len(olist) // 2): olist[i * 2] = F.softmax(olist[i * 2], dim=1) olist = [oelem.data.cpu() for oelem in olist] for i in range(len(olist) // 2): ocls, oreg = olist[i * 2], olist[i * 2 + 1] FB, FC, FH, FW = ocls.size() # feature map size stride = 2**(i + 2) # 4,8,16,32,64,128 anchor = stride * 4 poss = zip(*np.where(ocls[:, 1, :, :] > 0.05)) for Iindex, hindex, windex in poss: axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride score = ocls[:, 1, hindex, windex] loc = oreg[:, :, hindex, windex].contiguous().view(BB, 1, 4) priors = torch.Tensor([[axc / 1.0, ayc / 1.0, stride * 4 / 1.0, stride * 4 / 1.0]]).view(1, 1, 4) variances = [0.1, 0.2] box = batch_decode(loc, priors, variances) box = box[:, 0] * 1.0 # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1) bboxlist.append(torch.cat([box, score.unsqueeze(1)], 1).cpu().numpy()) bboxlist = np.array(bboxlist) if 0 == len(bboxlist): bboxlist = np.zeros((1, BB, 5)) return bboxlist
null
162,858
import os def get_image_list(data_root, split): filelist = [] with open('filelists/{}.txt'.format(split)) as f: for line in f: line = line.strip() if ' ' in line: line = line.split()[0] filelist.append(os.path.join(data_root, line)) return filelist
null
162,859
import os hparams = HParams( num_mels=80, # Number of mel-spectrogram channels and local conditioning dimensionality # network rescale=True, # Whether to rescale audio prior to preprocessing rescaling_max=0.9, # Rescaling value # Use LWS (https://github.com/Jonathan-LeRoux/lws) for STFT and phase reconstruction # It"s preferred to set True to use with https://github.com/r9y9/wavenet_vocoder # Does not work if n_ffit is not multiple of hop_size!! use_lws=False, n_fft=800, # Extra window size is filled with 0 paddings to match this parameter hop_size=200, # For 16000Hz, 200 = 12.5 ms (0.0125 * sample_rate) win_size=800, # For 16000Hz, 800 = 50 ms (If None, win_size = n_fft) (0.05 * sample_rate) sample_rate=16000, # 16000Hz (corresponding to librispeech) (sox --i <filename>) frame_shift_ms=None, # Can replace hop_size parameter. (Recommended: 12.5) # Mel and Linear spectrograms normalization/scaling and clipping signal_normalization=True, # Whether to normalize mel spectrograms to some predefined range (following below parameters) allow_clipping_in_normalization=True, # Only relevant if mel_normalization = True symmetric_mels=True, # Whether to scale the data to be symmetric around 0. (Also multiplies the output range by 2, # faster and cleaner convergence) max_abs_value=4., # max absolute value of data. If symmetric, data will be [-max, max] else [0, max] (Must not # be too big to avoid gradient explosion, # not too small for fast convergence) # Contribution by @begeekmyfriend # Spectrogram Pre-Emphasis (Lfilter: Reduce spectrogram noise and helps model certitude # levels. Also allows for better G&L phase reconstruction) preemphasize=True, # whether to apply filter preemphasis=0.97, # filter coefficient. # Limits min_level_db=-100, ref_level_db=20, fmin=55, # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To # test depending on dataset. Pitch info: male~[65, 260], female~[100, 525]) fmax=7600, # To be increased/reduced depending on data. ###################### Our training parameters ################################# img_size=96, fps=25, batch_size=16, initial_learning_rate=1e-4, nepochs=200000000000000000, ### ctrl + c, stop whenever eval loss is consistently greater than train loss for ~10 epochs num_workers=16, checkpoint_interval=3000, eval_interval=3000, save_optimizer_state=True, syncnet_wt=0.0, # is initially zero, will be set automatically to 0.03 later. Leads to faster convergence. syncnet_batch_size=64, syncnet_lr=1e-4, syncnet_eval_interval=10000, syncnet_checkpoint_interval=10000, disc_wt=0.07, disc_initial_learning_rate=1e-4, ) def hparams_debug_string(): values = hparams.values() hp = [" %s: %s" % (name, values[name]) for name in sorted(values) if name != "sentences"] return "Hyperparameters:\n" + "\n".join(hp)
null
162,860
import re from typing import List from pathlib import Path from setuptools import setup, find_packages def requirements(name: str) -> List[str]: root = Path(__file__).parent / 'requirements' return root.joinpath(name).read_text().splitlines()
null
162,861
from __future__ import annotations import os import re import json import shlex import shutil import contextlib from copy import deepcopy from typing import ( Iterator, Optional, cast, ) from pathlib import Path from contextvars import ContextVar, copy_context import nox import yaml import click import rtoml import typer from jinja2 import Environment, StrictUndefined, FileSystemLoader from nox.command import CommandFailed from lib.utils import flatten, escape_path from prisma._compat import model_copy, model_json, cached_property from pipelines.utils import ( setup_coverage, get_pkg_location, maybe_install_nodejs_bin, ) from .utils import DatabaseConfig from ._serve import start_database from ._types import SupportedDatabase from .constants import ( ROOT_DIR, TESTS_DIR, DATABASES_DIR, PYTEST_CONFIG, CONFIG_MAPPING, PYRIGHT_CONFIG, SYNC_TESTS_DIR, FEATURES_MAPPING, SUPPORTED_DATABASES, ) session_ctx: ContextVar[nox.Session] = ContextVar('session_ctx') def validate_database(database: str) -> SupportedDatabase: # We convert the input to lowercase so that we don't have to define # two separate names in the CI matrix. database = database.lower() if database not in SUPPORTED_DATABASES: # pragma: no cover raise ValueError(f'Unknown database: {database}') return database def start_database( database: SupportedDatabase, *, version: str | None, session: nox.Session, ) -> None: """Start a docker-compose database service""" if database == 'sqlite': raise ValueError('Cannot start a server for SQLite.') args = shlex.split(f'docker compose -f {DOCKER_COMPOSE_FILE} up -d --remove-orphans') session.run_always( *args, f'{database}{_format_version(version)}', external=True, ) The provided code snippet includes necessary dependencies for implementing the `serve` function. Write a Python function `def serve(database: str, *, version: Optional[str] = None) -> None` to solve the following problem: Start a database server using docker-compose Here is the function: def serve(database: str, *, version: Optional[str] = None) -> None: """Start a database server using docker-compose""" database = validate_database(database) start_database(database, version=version, session=session_ctx.get())
Start a database server using docker-compose
162,862
from __future__ import annotations import os import re import json import shlex import shutil import contextlib from copy import deepcopy from typing import ( Iterator, Optional, cast, ) from pathlib import Path from contextvars import ContextVar, copy_context import nox import yaml import click import rtoml import typer from jinja2 import Environment, StrictUndefined, FileSystemLoader from nox.command import CommandFailed from lib.utils import flatten, escape_path from prisma._compat import model_copy, model_json, cached_property from pipelines.utils import ( setup_coverage, get_pkg_location, maybe_install_nodejs_bin, ) from .utils import DatabaseConfig from ._serve import start_database from ._types import SupportedDatabase from .constants import ( ROOT_DIR, TESTS_DIR, DATABASES_DIR, PYTEST_CONFIG, CONFIG_MAPPING, PYRIGHT_CONFIG, SYNC_TESTS_DIR, FEATURES_MAPPING, SUPPORTED_DATABASES, ) session_ctx: ContextVar[nox.Session] = ContextVar('session_ctx') def test( *, databases: list[str] = cast('list[str]', SUPPORTED_DATABASES), # pyright: ignore[reportCallInDefaultInitializer] exclude_databases: list[str] = [], # pyright: ignore[reportCallInDefaultInitializer] inplace: bool = False, pytest_args: Optional[str] = None, lint: bool = True, test: bool = True, coverage: bool = False, pydantic_v2: bool = True, for_async: bool = typer.Option(default=True, is_flag=False), # pyright: ignore[reportCallInDefaultInitializer] ) -> None: """Run unit tests and Pyright""" if not pydantic_v2: lint = False session = session_ctx.get() exclude = set(validate_databases(exclude_databases)) validated_databases: list[SupportedDatabase] = [ database for database in validate_databases(databases) if database not in exclude ] with session.chdir(DATABASES_DIR): _setup_test_env(session, pydantic_v2=pydantic_v2, inplace=inplace) for database in validated_databases: print(title(CONFIG_MAPPING[database].name)) # point coverage to store data in a database specific location # as to not overwrite any existing data from other database tests if coverage: # pragma: no branch setup_coverage(session, identifier=database) runner = Runner(database=database, track_coverage=coverage, for_async=for_async) runner.setup() if test: # pragma: no branch runner.test(pytest_args=pytest_args) if lint: # pragma: no branch runner.lint() def _setup_test_env(session: nox.Session, *, pydantic_v2: bool, inplace: bool) -> None: if pydantic_v2: session.install('-r', '../pipelines/requirements/deps/pydantic.txt') else: session.install('pydantic==1.10.0') session.install('-r', 'requirements.txt') maybe_install_nodejs_bin(session) if inplace: # pragma: no cover # useful for updating the generated code so that Pylance picks it up session.install('-U', '-e', '..') else: session.install('-U', '..') session.run('python', '-m', 'prisma', 'py', 'version') def raises_command( allowed_exit_codes: set[int], ) -> Iterator[RaisesCommandResult]: """Context manager that intercepts and ignores `nox.CommandFailed` exceptions that are raised due to known exit codes. All other exceptions are passed through. """ result = RaisesCommandResult() try: yield result except CommandFailed as exc: match = COMMAND_FAILED_RE.match(exc.reason or '') if match is None: raise RuntimeError(f'Could not extract exit code from exception {exc}') from exc exit_code = int(match.group(1)) if exit_code not in allowed_exit_codes: raise RuntimeError( f'Unknown code: {exit_code}; Something may have gone wrong ' + 'or this exit code must be added to the list of known exit codes; ' + f'Allowed exit codes: {allowed_exit_codes}' ) from exc result.did_raise = True class Runner: database: SupportedDatabase session: nox.Session config: DatabaseConfig cache_dir: Path track_coverage: bool for_async: bool def __init__( self, *, database: SupportedDatabase, track_coverage: bool, for_async: bool, config: DatabaseConfig | None = None, ) -> None: self.database = database self.session = session_ctx.get() self.for_async = for_async self.track_coverage = track_coverage self.config = config or CONFIG_MAPPING[database] self.cache_dir = ROOT_DIR / '.tests_cache' / 'databases' / database def _create_cache_dir(self) -> None: cache_dir = self.cache_dir if cache_dir.exists(): # pragma: no cover shutil.rmtree(cache_dir) cache_dir.mkdir(parents=True, exist_ok=True) def setup(self) -> None: # TODO: split up more print('database config: ' + model_json(self.config, indent=2)) print('for async: ', self.for_async) exclude_files = self.exclude_files if exclude_files: print(f'excluding files:\n{yaml.dump(list(exclude_files))}') else: print('excluding files: []') self._create_cache_dir() # TODO: only create this if linting self._create_pyright_config() # TODO: only create this if testing pytest_config = self.cache_dir / 'pyproject.toml' rtoml.dump(PYTEST_CONFIG, pytest_config, pretty=True) # create a Prisma Schema file env = Environment( trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, keep_trailing_newline=True, loader=FileSystemLoader(DATABASES_DIR / 'templates'), ) template = env.get_template('schema.prisma.jinja2') self.schema.write_text( template.render( # template variables config=self.config, for_async=self.for_async, partial_generator=escape_path(DATABASES_DIR / 'partials.py'), ) ) # generate the client self.session.run(*self.python_args, 'prisma_cleanup') self.session.run( *self.python_args, 'prisma', 'generate', f'--schema={self.schema}', ) def test(self, *, pytest_args: str | None) -> None: # ensure DB is in correct state self.session.run( *self.python_args, 'prisma', 'db', 'push', '--force-reset', '--accept-data-loss', '--skip-generate', f'--schema={self.schema}', ) args = [] if pytest_args is not None: # pragma: no cover args = shlex.split(pytest_args) # TODO: use PYTEST_ADDOPTS instead self.session.run( *self.python_args, 'pytest', *args, *map( lambda i: f'--ignore={i}', self.exclude_files, ), env={ 'PRISMA_DATABASE': self.database, # TODO: this should be accessible in the core client 'DATABASE_CONFIG': model_json(self.config), }, ) def lint(self) -> None: self.session.run('pyright', '-p', str(self.pyright_config.absolute())) def _create_pyright_config(self) -> None: pkg_location = os.path.relpath(get_pkg_location(session_ctx.get(), 'prisma'), DATABASES_DIR) pyright_config = deepcopy(PYRIGHT_CONFIG) pyright_config['exclude'].extend(self.exclude_files) # exclude the mypy plugin so that we don't have to install `mypy`, it is also # not dynamically generated which means it will stay the same across database providers pyright_config['exclude'].append(str(Path(pkg_location).joinpath('mypy.py'))) # exclude our vendored code # this needs to explicitly be the package location as otherwise our `include` # of the package directory overrides other `exclude`s for the vendor dir pyright_config['exclude'].append(str(Path(pkg_location).joinpath('_vendor'))) # add the generated client code to Pyright too pyright_config['include'].append(pkg_location) # ensure only the tests for sync / async are checked pyright_config['include'].append(tests_reldir(for_async=self.for_async)) self.pyright_config.write_text(json.dumps(pyright_config, indent=2)) def python_args(self) -> list[str]: return shlex.split('coverage run --rcfile=../.coveragerc -m' if self.track_coverage else 'python -m') def pyright_config(self) -> Path: # TODO: move this to the cache dir, it requires some clever path renaming # as Pyright requires that `exclude` be relative to the location of the config file return DATABASES_DIR.joinpath(f'{self.database}.pyrightconfig.json') def schema(self) -> Path: return self.cache_dir.joinpath('schema.prisma') def exclude_files(self) -> set[str]: files = [ tests_relpath(path, for_async=self.for_async) for path in flatten([FEATURES_MAPPING[feature] for feature in self.config.unsupported_features]) ] # ensure the tests for the sync client are not ran during the async tests anc vice versa files.append(tests_reldir(for_async=not self.for_async)) return set(files) def validate_databases(databases: list[str]) -> list[SupportedDatabase]: # Typer by default requires that `List` options be specified multiple times, e.g. # `--databases=sqlite --databases=postgresql` # # I don't like this, I would much rather support this: # `--databases=sqlite,postgresql` # # I couldn't quickly find an option to support this with Typer so # it is handled manually here. databases = flatten([d.split(',') for d in databases]) return list(map(validate_database, databases)) def title(text: str) -> str: # TODO: improve formatting dashes = '-' * 30 return dashes + ' ' + click.style(text, bold=True) + ' ' + dashes def model_copy(model: _ModelT, deep: bool = False) -> _ModelT: if PYDANTIC_V2: return model.model_copy(deep=deep) return model.copy(deep=deep) # pyright: ignore[reportDeprecated] CONFIG_MAPPING: DatabaseMapping[DatabaseConfig] = { 'postgresql': DatabaseConfig( id='postgresql', name='PostgreSQL', env_var='POSTGRESQL_URL', bools_are_ints=False, unsupported_features=set(), default_date_func='CURRENT_DATE', autoincrement_id='Int @id @default(autoincrement())', ), 'cockroachdb': DatabaseConfig( id='cockroachdb', name='CockroachDB', env_var='COCKROACHDB_URL', bools_are_ints=False, default_date_func='CURRENT_DATE', autoincrement_id='BigInt @id @default(sequence())', unsupported_features={ 'json_arrays', 'array_push', 'transactions', }, ), 'sqlite': DatabaseConfig( id='sqlite', name='SQLite', env_var='SQLITE_URL', bools_are_ints=False, default_date_func='', autoincrement_id='Int @id @default(autoincrement())', unsupported_features={ 'enum', 'json', 'date', 'arrays', 'create_many', 'case_sensitivity', }, ), 'mysql': DatabaseConfig( id='mysql', name='MySQL', env_var='MYSQL_URL', bools_are_ints=True, default_date_func='(CURRENT_DATE)', autoincrement_id='Int @id @default(autoincrement())', unsupported_features={ 'arrays', 'case_sensitivity', }, ), 'mariadb': DatabaseConfig( id='mysql', name='MariaDB', env_var='MARIADB_URL', bools_are_ints=True, default_date_func='CURRENT_DATE', autoincrement_id='Int @id @default(autoincrement())', unsupported_features={ 'arrays', 'case_sensitivity', }, ), } SUPPORTED_DATABASES = cast(List[SupportedDatabase], list(get_args(SupportedDatabase))) DATABASES_DIR = Path(__file__).parent The provided code snippet includes necessary dependencies for implementing the `test_inverse` function. Write a Python function `def test_inverse( *, databases: list[str] = cast('list[str]', SUPPORTED_DATABASES), # pyright: ignore[reportCallInDefaultInitializer] coverage: bool = False, inplace: bool = False, pytest_args: Optional[str] = None, pydantic_v2: bool = True, for_async: bool = typer.Option(default=True, is_flag=False), # pyright: ignore[reportCallInDefaultInitializer] ) -> None` to solve the following problem: Ensure unsupported features actually result in either: - Prisma Schema validation failing - Our unit tests & linters fail Here is the function: def test_inverse( *, databases: list[str] = cast('list[str]', SUPPORTED_DATABASES), # pyright: ignore[reportCallInDefaultInitializer] coverage: bool = False, inplace: bool = False, pytest_args: Optional[str] = None, pydantic_v2: bool = True, for_async: bool = typer.Option(default=True, is_flag=False), # pyright: ignore[reportCallInDefaultInitializer] ) -> None: """Ensure unsupported features actually result in either: - Prisma Schema validation failing - Our unit tests & linters fail """ session = session_ctx.get() validated_databases = validate_databases(databases) with session.chdir(DATABASES_DIR): _setup_test_env(session, pydantic_v2=pydantic_v2, inplace=inplace) for database in validated_databases: config = CONFIG_MAPPING[database] print(title(config.name)) if not config.unsupported_features: print(f'There are no unsupported features for {database}.') continue # point coverage to store data in a database specific location # as to not overwrite any existing data from other database tests if coverage: # pragma: no branch setup_coverage(session, identifier=database) # TODO: support for tesing a given list of unsupported features for feature in config.unsupported_features: print(title(f'Testing {feature} feature')) new_config = model_copy(config, deep=True) new_config.unsupported_features.remove(feature) runner = Runner( database=database, config=new_config, for_async=for_async, track_coverage=coverage, ) with raises_command({1}) as result: runner.setup() if result.did_raise: print('Test setup failed (expectedly); Skipping pytest & pyright checks') continue with raises_command({1}): runner.test(pytest_args=pytest_args) with raises_command({1}): runner.lint() click.echo( click.style( f'✅ All tests successfully failed for {database}', fg='green', ) )
Ensure unsupported features actually result in either: - Prisma Schema validation failing - Our unit tests & linters fail
162,863
from __future__ import annotations import os import re import json import shlex import shutil import contextlib from copy import deepcopy from typing import ( Iterator, Optional, cast, ) from pathlib import Path from contextvars import ContextVar, copy_context import nox import yaml import click import rtoml import typer from jinja2 import Environment, StrictUndefined, FileSystemLoader from nox.command import CommandFailed from lib.utils import flatten, escape_path from prisma._compat import model_copy, model_json, cached_property from pipelines.utils import ( setup_coverage, get_pkg_location, maybe_install_nodejs_bin, ) from .utils import DatabaseConfig from ._serve import start_database from ._types import SupportedDatabase from .constants import ( ROOT_DIR, TESTS_DIR, DATABASES_DIR, PYTEST_CONFIG, CONFIG_MAPPING, PYRIGHT_CONFIG, SYNC_TESTS_DIR, FEATURES_MAPPING, SUPPORTED_DATABASES, ) DATABASES_DIR = Path(__file__).parent TESTS_DIR = DATABASES_DIR / 'tests' SYNC_TESTS_DIR = DATABASES_DIR / 'sync_tests' def tests_reldir(*, for_async: bool) -> str: return str((TESTS_DIR if for_async else SYNC_TESTS_DIR).relative_to(DATABASES_DIR))
null
162,864
from __future__ import annotations import os import re import json import shlex import shutil import contextlib from copy import deepcopy from typing import ( Iterator, Optional, cast, ) from pathlib import Path from contextvars import ContextVar, copy_context import nox import yaml import click import rtoml import typer from jinja2 import Environment, StrictUndefined, FileSystemLoader from nox.command import CommandFailed from lib.utils import flatten, escape_path from prisma._compat import model_copy, model_json, cached_property from pipelines.utils import ( setup_coverage, get_pkg_location, maybe_install_nodejs_bin, ) from .utils import DatabaseConfig from ._serve import start_database from ._types import SupportedDatabase from .constants import ( ROOT_DIR, TESTS_DIR, DATABASES_DIR, PYTEST_CONFIG, CONFIG_MAPPING, PYRIGHT_CONFIG, SYNC_TESTS_DIR, FEATURES_MAPPING, SUPPORTED_DATABASES, ) DATABASES_DIR = Path(__file__).parent TESTS_DIR = DATABASES_DIR / 'tests' SYNC_TESTS_DIR = DATABASES_DIR / 'sync_tests' def tests_relpath(path: str, *, for_async: bool) -> str: tests_dir = TESTS_DIR if for_async else SYNC_TESTS_DIR return str((tests_dir / path).relative_to(DATABASES_DIR))
null
162,865
from __future__ import annotations import os import re import json import shlex import shutil import contextlib from copy import deepcopy from typing import ( Iterator, Optional, cast, ) from pathlib import Path from contextvars import ContextVar, copy_context import nox import yaml import click import rtoml import typer from jinja2 import Environment, StrictUndefined, FileSystemLoader from nox.command import CommandFailed from lib.utils import flatten, escape_path from prisma._compat import model_copy, model_json, cached_property from pipelines.utils import ( setup_coverage, get_pkg_location, maybe_install_nodejs_bin, ) from .utils import DatabaseConfig from ._serve import start_database from ._types import SupportedDatabase from .constants import ( ROOT_DIR, TESTS_DIR, DATABASES_DIR, PYTEST_CONFIG, CONFIG_MAPPING, PYRIGHT_CONFIG, SYNC_TESTS_DIR, FEATURES_MAPPING, SUPPORTED_DATABASES, ) session_ctx: ContextVar[nox.Session] = ContextVar('session_ctx') cli = typer.Typer( help='Test suite for testing Prisma Client Python against different database providers.', ) The provided code snippet includes necessary dependencies for implementing the `entrypoint` function. Write a Python function `def entrypoint(session: nox.Session) -> None` to solve the following problem: Wrapper over `cli()` that sets a `session` context variable for easier usage. Here is the function: def entrypoint(session: nox.Session) -> None: """Wrapper over `cli()` that sets a `session` context variable for easier usage.""" def wrapper() -> None: session_ctx.set(session) cli(session.posargs) # copy the current context so that the session object is not leaked ctx = copy_context() return ctx.run(wrapper)
Wrapper over `cli()` that sets a `session` context variable for easier usage.
162,866
from __future__ import annotations from typing import List, cast from pathlib import Path from typing_extensions import get_args from lib import pyright from .utils import DatabaseConfig, DatabaseFeature from ._types import DatabaseMapping, SupportedDatabase TESTS_DIR = DATABASES_DIR / 'tests' The provided code snippet includes necessary dependencies for implementing the `_fromdir` function. Write a Python function `def _fromdir(path: str) -> list[str]` to solve the following problem: Get the contents of a subdirectory within the `` directory Here is the function: def _fromdir(path: str) -> list[str]: """Get the contents of a subdirectory within the `` directory""" # TODO: recurse subdirs return [str(f.relative_to(TESTS_DIR)) for f in (TESTS_DIR / path).iterdir()]
Get the contents of a subdirectory within the `` directory
162,867
from __future__ import annotations import os import time import asyncio import inspect import logging import warnings import contextlib from typing import TYPE_CHECKING, Any, Dict, Union, TypeVar, Iterator, NoReturn, Coroutine from importlib.util import find_spec from ._types import CoroType, FuncType, TypeGuard def _env_bool(key: str) -> bool: return os.environ.get(key, '').lower() in {'1', 't', 'true'}
null
162,868
from __future__ import annotations import os import time import asyncio import inspect import logging import warnings import contextlib from typing import TYPE_CHECKING, Any, Dict, Union, TypeVar, Iterator, NoReturn, Coroutine from importlib.util import find_spec from ._types import CoroType, FuncType, TypeGuard The provided code snippet includes necessary dependencies for implementing the `assert_never` function. Write a Python function `def assert_never(value: NoReturn) -> NoReturn` to solve the following problem: Used by type checkers for exhaustive match cases. https://github.com/microsoft/pyright/issues/767 Here is the function: def assert_never(value: NoReturn) -> NoReturn: """Used by type checkers for exhaustive match cases. https://github.com/microsoft/pyright/issues/767 """ raise AssertionError('Unhandled type: {}'.format(type(value).__name__)) # pragma: no cover
Used by type checkers for exhaustive match cases. https://github.com/microsoft/pyright/issues/767
162,869
from __future__ import annotations import os import time import asyncio import inspect import logging import warnings import contextlib from typing import TYPE_CHECKING, Any, Dict, Union, TypeVar, Iterator, NoReturn, Coroutine from importlib.util import find_spec from ._types import CoroType, FuncType, TypeGuard _T = TypeVar('_T') The provided code snippet includes necessary dependencies for implementing the `make_optional` function. Write a Python function `def make_optional(value: _T) -> _T | None` to solve the following problem: Helper function for type checkers to change the given type to include None. This is useful in cases where you do not have an explicit type for a symbol (e.g. modules) but want to mark it as potentially None. Here is the function: def make_optional(value: _T) -> _T | None: """Helper function for type checkers to change the given type to include None. This is useful in cases where you do not have an explicit type for a symbol (e.g. modules) but want to mark it as potentially None. """ return value
Helper function for type checkers to change the given type to include None. This is useful in cases where you do not have an explicit type for a symbol (e.g. modules) but want to mark it as potentially None.
162,870
from __future__ import annotations import os import time import asyncio import inspect import logging import warnings import contextlib from typing import TYPE_CHECKING, Any, Dict, Union, TypeVar, Iterator, NoReturn, Coroutine from importlib.util import find_spec from ._types import CoroType, FuncType, TypeGuard def is_dict(obj: object) -> TypeGuard[dict[object, object]]: return isinstance(obj, dict)
null
162,871
import sys from types import ModuleType from typing import Any, Type, TypeVar, cast from functools import lru_cache from pydantic import BaseModel from ._types import Protocol, runtime_checkable from ._compat import PYDANTIC_V2, Extra, is_typeddict T = TypeVar('T') class Config: extra: Extra = Extra.forbid class CachedModel(Protocol): __pydantic_model__: BaseModel def _get_module(typ: Type[Any]) -> ModuleType: return sys.modules[typ.__module__] def patch_pydantic() -> None: """Pydantic does not resolve forward references for TypedDict types properly yet see https://github.com/samuelcolvin/pydantic/pull/2761 """ annotated_types: Any if PYDANTIC_V2: from pydantic.v1 import annotated_types else: from pydantic import annotated_types # type: ignore[no-redef] create_model = annotated_types.create_model_from_typeddict def patched_create_model(typeddict_cls: Any, **kwargs: Any) -> Type[BaseModel]: kwargs.setdefault('__module__', typeddict_cls.__module__) return create_model(typeddict_cls, **kwargs) # type: ignore[no-any-return] annotated_types.create_model_from_typeddict = patched_create_model PYDANTIC_V2 = pydantic.VERSION.startswith('2.') The provided code snippet includes necessary dependencies for implementing the `validate` function. Write a Python function `def validate(type: Type[T], data: Any) -> T` to solve the following problem: Validate untrusted data matches a given TypedDict For example: from prisma import validate, types from prisma.models import User def user_create_handler(data: Any) -> None: validated = validate(types.UserCreateInput, data) user = await User.prisma().create(data=validated) Here is the function: def validate(type: Type[T], data: Any) -> T: """Validate untrusted data matches a given TypedDict For example: from prisma import validate, types from prisma.models import User def user_create_handler(data: Any) -> None: validated = validate(types.UserCreateInput, data) user = await User.prisma().create(data=validated) """ create_model_from_typeddict: Any if PYDANTIC_V2: from pydantic.v1 import create_model_from_typeddict else: from pydantic import create_model_from_typeddict # type: ignore # avoid patching pydantic until we know we need to in case our # monkey patching fails patch_pydantic() if not is_typeddict(type): raise TypeError(f'Only TypedDict types are supported, got: {type} instead.') # we cannot use pydantic's builtin type -> model resolver # as we need to be able to update forward references if isinstance(type, CachedModel): # cache the model on the type object, mirroring how pydantic works # mypy thinks this is unreachable, we know it isn't, just ignore model = type.__pydantic_model__ # type: ignore[unreachable] else: # pyright is more strict than mypy here, we also don't care about the # incorrectly inferred type as we have verified that the given type # is indeed a TypedDict model = create_model_from_typeddict( type, __config__=Config, # pyright: ignore[reportGeneralTypeIssues] ) model.update_forward_refs(**vars(_get_module(type))) type.__pydantic_model__ = model # type: ignore instance = model.parse_obj(data) return cast(T, instance.dict(exclude_unset=True))
Validate untrusted data matches a given TypedDict For example: from prisma import validate, types from prisma.models import User def user_create_handler(data: Any) -> None: validated = validate(types.UserCreateInput, data) user = await User.prisma().create(data=validated)
162,872
from __future__ import annotations from typing import Any, Optional def _pick_union_error(errors: list[Any]) -> Any: # Note: uses the same heuristic as the TS client return max( errors, key=lambda e: (len(e.get('argumentPath', [])) + len(e.get('selectionPath'))), )
null
162,873
from __future__ import annotations import logging import warnings from types import TracebackType from typing import Any, Generic, TypeVar, overload from pathlib import Path from datetime import timedelta from typing_extensions import Self, Literal from pydantic import BaseModel from ._types import Datasource, HttpConfig, PrismaMethod, MetricsFormat, TransactionId, DatasourceOverride from .engine import ( SyncQueryEngine, AsyncQueryEngine, BaseAbstractEngine, SyncAbstractEngine, AsyncAbstractEngine, ) from .errors import ClientNotConnectedError, ClientNotRegisteredError from ._compat import model_parse, removeprefix from ._builder import QueryBuilder from ._metrics import Metrics from ._registry import get_client from .generator.models import EngineType The provided code snippet includes necessary dependencies for implementing the `load_env` function. Write a Python function `def load_env(*, override: bool = False, **kwargs: Any) -> None` to solve the following problem: Load environemntal variables from dotenv files Loads from the following files relative to the current working directory: - .env - prisma/.env Here is the function: def load_env(*, override: bool = False, **kwargs: Any) -> None: """Load environemntal variables from dotenv files Loads from the following files relative to the current working directory: - .env - prisma/.env """ from dotenv import load_dotenv load_dotenv('.env', override=override, **kwargs) load_dotenv('prisma/.env', override=override, **kwargs)
Load environemntal variables from dotenv files Loads from the following files relative to the current working directory: - .env - prisma/.env
162,874
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional _T = TypeVar('_T') PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def field_validator( __field: str, *fields: str, pre: bool = False, check_fields: bool | None = None, always: bool | None = None, allow_reuse: bool | None = None, ) -> Callable[[_T], _T]: if PYDANTIC_V2: return cast( # type: ignore[no-any-return] Any, pydantic.field_validator( __field, *fields, mode='before' if pre else 'after', check_fields=check_fields, ), ) kwargs = {} if always is not None: kwargs['always'] = always if allow_reuse is not None: kwargs['allow_reuse'] = allow_reuse return pydantic.validator(__field, *fields, pre=pre, **kwargs) # type: ignore
null
162,875
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional _T = TypeVar('_T') PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def root_validator( *__args: Any, pre: bool = False, skip_on_failure: bool = False, allow_reuse: bool = False, ) -> Callable[[_T], _T]: if PYDANTIC_V2: return pydantic.model_validator( # type: ignore mode='before' if pre else 'after', ) return cast(Any, pydantic.root_validator)( # type: ignore[no-any-return] *__args, pre=pre, skip_on_failure=skip_on_failure, allow_reuse=allow_reuse, )
null
162,876
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001 ...
null
162,877
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional def _get_field_env_var(field: FieldInfo, name: str) -> str | None: if not PYDANTIC_V2: return field.field_info.extra.get('env') # type: ignore extra = field.json_schema_extra if not extra: return None if callable(extra): raise RuntimeError(f'Unexpected json schema for field "{name}" is a function') env = extra.get(ENV_VAR_KEY) if env and isinstance(env, str): return env return None def model_fields(model: type[BaseModel]) -> dict[str, FieldInfo]: if PYDANTIC_V2: return model.model_fields return model.__fields__ # type: ignore def _env_var_resolver(model_cls: type[BaseModel], values: Any) -> dict[str, Any]: assert isinstance(values, dict) for key, field_info in model_cls.model_fields.items(): env_var = _get_field_env_var(field_info, name=key) if not env_var: continue assert isinstance(env_var, str) # Note: we always want to prioritise the env var # over the value given due to how config loading works value = os.environ.get(env_var) if value is not None: values[key] = value return values
null
162,878
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def is_field_required(field: FieldInfo) -> bool: if PYDANTIC_V2: return field.is_required() return field.required # type: ignore
null
162,879
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def model_dict( model: BaseModel, *, by_alias: bool = False, exclude: set[str] | None = None, exclude_unset: bool = False, ) -> dict[str, Any]: if PYDANTIC_V2: return model.model_dump( exclude_unset=exclude_unset, exclude=exclude, by_alias=by_alias, ) return model.dict( # pyright: ignore[reportDeprecated] exclude=exclude, exclude_unset=exclude_unset, by_alias=by_alias, )
null
162,880
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def model_rebuild(model: type[BaseModel]) -> None: if PYDANTIC_V2: model.model_rebuild() else: model.update_forward_refs() # pyright: ignore[reportDeprecated]
null
162,881
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional _ModelT = TypeVar('_ModelT', bound=BaseModel) PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def model_parse_json(model: type[_ModelT], obj: str) -> _ModelT: if PYDANTIC_V2: return model.model_validate_json(obj) else: return model.parse_raw(obj) # pyright: ignore[reportDeprecated]
null
162,882
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional PYDANTIC_V2 = pydantic.VERSION.startswith('2.') def model_json_schema(model: type[BaseModel]) -> dict[str, Any]: if PYDANTIC_V2: return model.model_json_schema() else: return model.schema() # pyright: ignore[reportDeprecated]
null
162,883
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional PYDANTIC_V2 = pydantic.VERSION.startswith('2.') ENV_VAR_KEY = '$env' def Field(*, env: str | None = None, **extra: Any) -> Any: if PYDANTIC_V2: # we store environment variable metadata in $env # as a workaround to support BaseSettings behaviour ourselves # as we can't depend on pydantic-settings json_schema_extra = None if env: json_schema_extra = {ENV_VAR_KEY: env} return pydantic.Field(**extra, json_schema_extra=json_schema_extra) # type: ignore return pydantic.Field(**extra, env=env) # type: ignore
null
162,884
from __future__ import annotations import os import sys from typing import TYPE_CHECKING, Any, TypeVar, Callable, cast from asyncio import get_running_loop as get_running_loop import pydantic from pydantic import BaseModel from pydantic.fields import FieldInfo from .utils import make_optional def removeprefix(string: str, prefix: str) -> str: if string.startswith(prefix): return string[len(prefix) :] return string
null
162,885
from __future__ import annotations import os import re import shutil from typing import TYPE_CHECKING, Any, Dict, List, Union, TypeVar, Iterator from pathlib import Path from textwrap import dedent from ..utils import monkeypatch def is_same_path(path: Path, other: Path) -> bool: return str(path.resolve()).strip() == str(other.resolve()).strip()
null
162,886
from __future__ import annotations import os import re import shutil from typing import TYPE_CHECKING, Any, Dict, List, Union, TypeVar, Iterator from pathlib import Path from textwrap import dedent from ..utils import monkeypatch def monkeypatch(obj: Any, attr: str, new: Any) -> Any: """Temporarily replace a method with a new funtion The previously set method is passed as the first argument to the new function """ def patched(*args: Any, **kwargs: Any) -> Any: return new(old, *args, **kwargs) old = getattr(obj, attr) try: setattr(obj, attr, patched) yield finally: setattr(obj, attr, old) The provided code snippet includes necessary dependencies for implementing the `copy_tree` function. Write a Python function `def copy_tree(src: Path, dst: Path) -> None` to solve the following problem: Recursively copy the contents of a directory from src to dst. This function will ignore certain compiled / cache files for convenience: - *.pyc - __pycache__ Here is the function: def copy_tree(src: Path, dst: Path) -> None: """Recursively copy the contents of a directory from src to dst. This function will ignore certain compiled / cache files for convenience: - *.pyc - __pycache__ """ # we have to do this horrible monkeypatching as # shutil makes an arbitrary call to os.makedirs # which will fail if the directory already exists. # the dirs_exist_ok argument does exist but was only # added in python 3.8 so we cannot use that :( def _patched_makedirs( makedirs: Any, name: str, mode: int = 511, exist_ok: bool = True, # noqa: ARG001 ) -> None: makedirs(name, mode, exist_ok=True) with monkeypatch(os, 'makedirs', _patched_makedirs): shutil.copytree( str(src), str(dst), ignore=shutil.ignore_patterns('*.pyc', '__pycache__'), )
Recursively copy the contents of a directory from src to dst. This function will ignore certain compiled / cache files for convenience: - *.pyc - __pycache__
162,887
from __future__ import annotations import os import re import shutil from typing import TYPE_CHECKING, Any, Dict, List, Union, TypeVar, Iterator from pathlib import Path from textwrap import dedent from ..utils import monkeypatch def clean_multiline(string: str) -> str: string = string.lstrip('\n') assert string, 'Expected non-empty string' lines = string.splitlines() return '\n'.join([dedent(lines[0]), *lines[1:]])
null
162,888
import os import sys import enum import textwrap import importlib from typing import ( TYPE_CHECKING, Any, Dict, List, Type, Tuple, Union, Generic, TypeVar, ClassVar, Iterable, Iterator, NoReturn, Optional, cast, ) from keyword import iskeyword from pathlib import Path from importlib import util as importlib_util, machinery from itertools import chain from contextvars import ContextVar from importlib.abc import InspectLoader from typing_extensions import Annotated, override import click import pydantic from pydantic.fields import PrivateAttr from .. import config from .utils import Faker, Sampler, clean_multiline from ..utils import DEBUG_GENERATOR, assert_never from ..errors import UnsupportedListTypeError from .._compat import ( PYDANTIC_V2, Field as FieldInfo, BaseConfig, ConfigDict, BaseSettings, GenericModel, PlainSerializer, BaseSettingsConfig, model_dict, model_parse, model_rebuild, root_validator, cached_property, field_validator, ) from .._constants import QUERY_BUILDER_ALIASES from ._dsl_parser import parse_schema_dsl config_ctx: ContextVar['Config'] = ContextVar('config_ctx') class BaseModel(pydantic.BaseModel): if PYDANTIC_V2: model_config: ClassVar[ConfigDict] = ConfigDict( arbitrary_types_allowed=True, ignored_types=(cached_property,), ) else: class Config(BaseConfig): arbitrary_types_allowed: bool = True json_encoders: Dict[Type[Any], Any] = { Path: _pathlib_serializer, machinery.ModuleSpec: _module_spec_serializer, } keep_untouched: Tuple[Type[Any], ...] = (cached_property,) from .errors import ( TemplateError, PartialTypeGeneratorError, ) from .schema import Schema, ClientTypes def get_config() -> Union[None, pydantic.BaseModel, 'Config']: return config_ctx.get(None)
null
162,889
import os import sys import enum import textwrap import importlib from typing import ( TYPE_CHECKING, Any, Dict, List, Type, Tuple, Union, Generic, TypeVar, ClassVar, Iterable, Iterator, NoReturn, Optional, cast, ) from keyword import iskeyword from pathlib import Path from importlib import util as importlib_util, machinery from itertools import chain from contextvars import ContextVar from importlib.abc import InspectLoader from typing_extensions import Annotated, override import click import pydantic from pydantic.fields import PrivateAttr from .. import config from .utils import Faker, Sampler, clean_multiline from ..utils import DEBUG_GENERATOR, assert_never from ..errors import UnsupportedListTypeError from .._compat import ( PYDANTIC_V2, Field as FieldInfo, BaseConfig, ConfigDict, BaseSettings, GenericModel, PlainSerializer, BaseSettingsConfig, model_dict, model_parse, model_rebuild, root_validator, cached_property, field_validator, ) from .._constants import QUERY_BUILDER_ALIASES from ._dsl_parser import parse_schema_dsl TYPE_MAPPING = { 'String': '_str', 'Bytes': "'fields.Base64'", 'DateTime': 'datetime.datetime', 'Boolean': '_bool', 'Int': '_int', 'Float': '_float', 'BigInt': '_int', 'Json': "'fields.Json'", 'Decimal': 'decimal.Decimal', } FILTER_TYPES = [ 'String', 'Bytes', 'DateTime', 'Boolean', 'Int', 'BigInt', 'Float', 'Json', 'Decimal', ] def get_datamodel() -> 'Datamodel': return data_ctx.get().dmmf.datamodel from .errors import ( TemplateError, PartialTypeGeneratorError, ) from .schema import Schema, ClientTypes def get_list_types() -> Iterable[Tuple[str, str]]: # WARNING: do not edit this function without also editing Field.is_supported_scalar_list_type() return chain( ((t, TYPE_MAPPING[t]) for t in FILTER_TYPES), ((enum.name, f"'enums.{enum.name}'") for enum in get_datamodel().enums), )
null