repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
gym
gym/envs/mujoco/humanoid.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box def mass_center(model, sim): mass = np.expand_dims(model.body_mass, 1) xpos = sim.data.xipos return (np.sum(mass * xpos, 0) / np.sum(mass))[0] class HumanoidEnv(MuJocoPyEnv, utils.EzPickle): ...
95
2,800
gym
gym/envs/mujoco/swimmer.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class SwimmerEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 25, } ...
60
1,676
gym
gym/envs/mujoco/pusher.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class PusherEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 20, } ...
85
2,504
gym
gym/envs/mujoco/humanoid_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 1, "distance": 4.0, "lookat": np.array((0.0, 0.0, 2.0)), "elevation": -20.0, } def mass_center(model, data): mass = np.expand_dims(model.body_mass, a...
375
27,951
gym
gym/envs/mujoco/hopper_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "trackbodyid": 2, "distance": 3.0, "lookat": np.array((0.0, 0.0, 1.15)), "elevation": -20.0, } class HopperEnv(MujocoEnv, utils.EzPickle): """ ### Description ...
299
16,025
gym
gym/envs/mujoco/walker2d.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class Walker2dEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 125, } ...
62
1,897
gym
gym/envs/mujoco/inverted_double_pendulum.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class InvertedDoublePendulumEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps"...
70
2,125
gym
gym/envs/mujoco/ant_v3.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "distance": 4.0, } class AntEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ...
187
5,705
gym
gym/envs/mujoco/reacher.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class ReacherEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 50, } ...
76
2,190
gym
gym/envs/mujoco/humanoidstandup_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box class HumanoidStandupEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment is based on the environment introduced by Tassa, Erez and Todorov in ["Synthesis and stabilization of co...
260
21,674
gym
gym/envs/mujoco/inverted_pendulum.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class InvertedPendulumEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 25, ...
57
1,596
gym
gym/envs/mujoco/mujoco_rendering.py
.py
import collections import os import time from threading import Lock import glfw import imageio import mujoco import numpy as np def _import_egl(width, height): from mujoco.egl import GLContext return GLContext(width, height) def _import_glfw(width, height): from mujoco.glfw import GLContext retur...
553
19,629
gym
gym/envs/mujoco/ant_v4.py
.py
import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = { "distance": 4.0, } class AntEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment is based on the environment introduced by Schulman, Moritz, Levine...
357
19,981
gym
gym/envs/mujoco/swimmer_v4.py
.py
__credits__ = ["Rushiv Arora"] import numpy as np from gym import utils from gym.envs.mujoco import MujocoEnv from gym.spaces import Box DEFAULT_CAMERA_CONFIG = {} class SwimmerEnv(MujocoEnv, utils.EzPickle): """ ### Description This environment corresponds to the Swimmer environment described in Rémi...
240
11,896
gym
tests/test_core.py
.py
from typing import Optional import numpy as np import pytest from gym import core, spaces from gym.wrappers import OrderEnforcing, TimeLimit class ArgumentEnv(core.Env): observation_space = spaces.Box(low=0, high=1, shape=(1,)) action_space = spaces.Box(low=0, high=1, shape=(1,)) calls = 0 def __in...
140
4,240
gym
tests/testing_env.py
.py
"""Provides a generic testing environment for use in tests with custom reset, step and render functions.""" import types from typing import Any, Dict, Optional, Tuple, Union import gym from gym import spaces from gym.core import ActType, ObsType from gym.envs.registration import EnvSpec def basic_reset_fn( self,...
83
3,161
gym
tests/wrappers/test_autoreset.py
.py
"""Tests the gym.wrapper.AutoResetWrapper operates as expected.""" from typing import Generator, Optional from unittest.mock import MagicMock import numpy as np import pytest import gym from gym.wrappers import AutoResetWrapper from tests.envs.utils import all_testing_env_specs class DummyResetEnv(gym.Env): """...
137
4,731
gym
tests/wrappers/test_transform_reward.py
.py
import numpy as np import pytest import gym from gym.wrappers import TransformReward @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) def test_transform_reward(env_id): # use case #1: scale scales = [0.1, 200] for scale in scales: env = gym.make(env_id, disable_env_checker=True)...
63
1,834
gym
tests/wrappers/utils.py
.py
import gym def has_wrapper(wrapped_env: gym.Env, wrapper_type: type) -> bool: while isinstance(wrapped_env, gym.Wrapper): if isinstance(wrapped_env, wrapper_type): return True wrapped_env = wrapped_env.env return False
10
257
gym
tests/wrappers/test_clip_action.py
.py
import numpy as np import gym from gym.wrappers import ClipAction def test_clip_action(): # mountaincar: action-based rewards env = gym.make("MountainCarContinuous-v0", disable_env_checker=True) wrapped_env = ClipAction( gym.make("MountainCarContinuous-v0", disable_env_checker=True) ) se...
29
790
gym
tests/wrappers/test_video_recorder.py
.py
import gc import os import re import time import pytest import gym from gym.wrappers.monitoring.video_recorder import VideoRecorder class BrokenRecordableEnv(gym.Env): metadata = {"render_modes": ["rgb_array_list"]} def __init__(self, render_mode="rgb_array_list"): self.render_mode = render_mode ...
120
2,910
gym
tests/wrappers/test_gray_scale_observation.py
.py
import pytest import gym from gym import spaces from gym.wrappers import GrayScaleObservation @pytest.mark.parametrize("env_id", ["CarRacing-v2"]) @pytest.mark.parametrize("keep_dim", [True, False]) def test_gray_scale_observation(env_id, keep_dim): rgb_env = gym.make(env_id, disable_env_checker=True) asser...
27
920
gym
tests/wrappers/test_record_episode_statistics.py
.py
import numpy as np import pytest import gym from gym.wrappers import RecordEpisodeStatistics, VectorListInfo from gym.wrappers.record_episode_statistics import add_vector_episode_statistics @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) @pytest.mark.parametrize("deque_size", [2, 5]) def test_reco...
103
3,578
gym
tests/wrappers/test_time_limit.py
.py
import pytest import gym from gym.envs.classic_control.pendulum import PendulumEnv from gym.wrappers import TimeLimit def test_time_limit_reset_info(): env = gym.make("CartPole-v1", disable_env_checker=True) env = TimeLimit(env) ob_space = env.observation_space obs, info = env.reset() assert ob_s...
58
1,703
gym
tests/wrappers/test_order_enforcing.py
.py
import pytest import gym from gym.envs.classic_control import CartPoleEnv from gym.error import ResetNeeded from gym.wrappers import OrderEnforcing from tests.envs.utils import all_testing_env_specs from tests.wrappers.utils import has_wrapper @pytest.mark.parametrize( "spec", all_testing_env_specs, ids=[spec.id...
46
1,786
gym
tests/wrappers/test_pixel_observation.py
.py
"""Tests for the pixel observation wrapper.""" from typing import Optional import numpy as np import pytest import gym from gym import spaces from gym.wrappers.pixel_observation import STATE_KEY, PixelObservationWrapper class FakeEnvironment(gym.Env): def __init__(self, render_mode="single_rgb_array"): ...
126
4,188
gym
tests/wrappers/test_flatten.py
.py
"""Tests for the flatten observation wrapper.""" from collections import OrderedDict from typing import Optional import numpy as np import pytest import gym from gym.spaces import Box, Dict, flatten, unflatten from gym.wrappers import FlattenObservation class FakeEnvironment(gym.Env): def __init__(self, observ...
99
3,314
gym
tests/wrappers/test_time_aware_observation.py
.py
import pytest import gym from gym import spaces from gym.wrappers import TimeAwareObservation @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) def test_time_aware_observation(env_id): env = gym.make(env_id, disable_env_checker=True) wrapped_env = TimeAwareObservation(env) assert isinst...
37
1,277
gym
tests/wrappers/test_record_video.py
.py
import os import shutil import gym from gym.wrappers import capped_cubic_video_schedule def test_record_video_using_default_trigger(): env = gym.make( "CartPole-v1", render_mode="rgb_array_list", disable_env_checker=True ) env = gym.wrappers.RecordVideo(env, "videos") env.reset() for _ in...
87
2,831
gym
tests/wrappers/test_atari_preprocessing.py
.py
import numpy as np import pytest from gym.spaces import Box, Discrete from gym.wrappers import AtariPreprocessing, StepAPICompatibility from tests.testing_env import GenericTestEnv, old_step_fn class AleTesting: """A testing implementation for the ALE object in atari games.""" grayscale_obs_space = Box(low=...
127
4,102
gym
tests/wrappers/test_flatten_observation.py
.py
import numpy as np import pytest import gym from gym import spaces from gym.wrappers import FlattenObservation @pytest.mark.parametrize("env_id", ["Blackjack-v1"]) def test_flatten_observation(env_id): env = gym.make(env_id, disable_env_checker=True) wrapped_env = FlattenObservation(env) obs, info = env...
24
702
gym
tests/wrappers/test_frame_stack.py
.py
import numpy as np import pytest import gym from gym.wrappers import FrameStack try: import lz4 except ImportError: lz4 = None @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "CarRacing-v2"]) @pytest.mark.parametrize("num_stack", [2, 3, 4]) @pytest.mark.parametrize( "lz4_compress", ...
53
1,457
gym
tests/wrappers/test_human_rendering.py
.py
import re import pytest import gym from gym.wrappers import HumanRendering def test_human_rendering(): for mode in ["rgb_array", "rgb_array_list"]: env = HumanRendering( gym.make("CartPole-v1", render_mode=mode, disable_env_checker=True) ) assert env.render_mode == "human" ...
33
828
gym
tests/wrappers/test_rescale_action.py
.py
import numpy as np import pytest import gym from gym.wrappers import RescaleAction def test_rescale_action(): env = gym.make("CartPole-v1", disable_env_checker=True) with pytest.raises(AssertionError): env = RescaleAction(env, -1, 1) del env env = gym.make("Pendulum-v1", disable_env_checker=...
32
861
gym
tests/wrappers/test_vector_list_info.py
.py
import pytest import gym from gym.wrappers import RecordEpisodeStatistics, VectorListInfo ENV_ID = "CartPole-v1" NUM_ENVS = 3 ENV_STEPS = 50 SEED = 42 def test_usage_in_vector_env(): env = gym.make(ENV_ID, disable_env_checker=True) vector_env = gym.vector.make(ENV_ID, num_envs=NUM_ENVS, disable_env_checker=...
59
2,090
gym
tests/wrappers/test_filter_observation.py
.py
from typing import Optional, Tuple import numpy as np import pytest import gym from gym import spaces from gym.wrappers.filter_observation import FilterObservation class FakeEnvironment(gym.Env): def __init__( self, render_mode=None, observation_keys: Tuple[str, ...] = ("state",) ): self.obs...
88
2,972
gym
tests/wrappers/test_transform_observation.py
.py
import numpy as np import pytest import gym from gym.wrappers import TransformObservation @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) def test_transform_observation(env_id): def affine_transform(x): return 3 * x + 2 env = gym.make(env_id, disable_env_checker=True) wrapped_...
36
1,085
gym
tests/wrappers/test_resize_observation.py
.py
import pytest import gym from gym import spaces from gym.wrappers import ResizeObservation @pytest.mark.parametrize("env_id", ["CarRacing-v2"]) @pytest.mark.parametrize("shape", [16, 32, (8, 5), [10, 7]]) def test_resize_observation(env_id, shape): env = gym.make(env_id, disable_env_checker=True) env = Resiz...
23
739
gym
tests/wrappers/test_passive_env_checker.py
.py
import re import warnings import numpy as np import pytest import gym from gym.wrappers.env_checker import PassiveEnvChecker from tests.envs.test_envs import PASSIVE_CHECK_IGNORE_WARNING from tests.envs.utils import all_testing_initialised_envs from tests.testing_env import GenericTestEnv @pytest.mark.parametrize( ...
104
3,060
gym
tests/wrappers/test_normalize.py
.py
from typing import Optional import numpy as np from numpy.testing import assert_almost_equal import gym from gym.wrappers.normalize import NormalizeObservation, NormalizeReward class DummyRewardEnv(gym.Env): metadata = {} def __init__(self, return_reward_idx=0): self.action_space = gym.spaces.Discr...
126
3,760
gym
tests/wrappers/test_step_compatibility.py
.py
import pytest import gym from gym.spaces import Discrete from gym.wrappers import StepAPICompatibility class OldStepEnv(gym.Env): def __init__(self): self.action_space = Discrete(2) self.observation_space = Discrete(2) def step(self, action): obs = self.observation_space.sample() ...
83
2,458
gym
tests/wrappers/test_nested_dict.py
.py
"""Tests for the filter observation wrapper.""" from typing import Optional import numpy as np import pytest import gym from gym.spaces import Box, Dict, Tuple from gym.wrappers import FilterObservation, FlattenObservation class FakeEnvironment(gym.Env): def __init__(self, observation_space, render_mode=None): ...
121
4,067
gym
tests/vector/test_numpy_utils.py
.py
from collections import OrderedDict import numpy as np import pytest from gym.spaces import Dict, Tuple from gym.vector.utils.numpy_utils import concatenate, create_empty_array from gym.vector.utils.spaces import BaseGymSpaces from tests.vector.utils import spaces @pytest.mark.parametrize( "space", spaces, ids=...
143
5,025
gym
tests/vector/utils.py
.py
import time from typing import Optional import numpy as np import gym from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Tuple from gym.utils.seeding import RandomNumberGenerator spaces = [ Box(low=np.array(-1.0), high=np.array(1.0), dtype=np.float64), Box(low=np.array([0.0]), high=np.ar...
140
3,834
gym
tests/vector/test_vector_env_info.py
.py
import numpy as np import pytest import gym from gym.vector.sync_vector_env import SyncVectorEnv from tests.vector.utils import make_env ENV_ID = "CartPole-v1" NUM_ENVS = 3 ENV_STEPS = 50 SEED = 42 @pytest.mark.parametrize("asynchronous", [True, False]) def test_vector_env_info(asynchronous): env = gym.vector.m...
57
2,180
gym
tests/vector/test_async_vector_env.py
.py
import re from multiprocessing import TimeoutError import numpy as np import pytest from gym.error import AlreadyPendingCallError, ClosedEnvironmentError, NoAsyncCallError from gym.spaces import Box, Discrete, MultiDiscrete, Tuple from gym.vector.async_vector_env import AsyncVectorEnv from tests.vector.utils import (...
309
10,139
gym
tests/vector/test_shared_memory.py
.py
import multiprocessing as mp from collections import OrderedDict from multiprocessing import Array, Process from multiprocessing.sharedctypes import SynchronizedArray import numpy as np import pytest from gym.error import CustomSpaceError from gym.spaces import Dict, Tuple from gym.vector.utils.shared_memory import (...
178
5,713
gym
tests/vector/test_vector_env.py
.py
from functools import partial import numpy as np import pytest from gym.spaces import Discrete, Tuple from gym.vector.async_vector_env import AsyncVectorEnv from gym.vector.sync_vector_env import SyncVectorEnv from gym.vector.vector_env import VectorEnv from tests.testing_env import GenericTestEnv from tests.vector.u...
126
4,274
gym
tests/vector/test_spaces.py
.py
import copy import numpy as np import pytest from numpy.testing import assert_array_equal from gym.spaces import Box, Dict, MultiDiscrete, Space, Tuple from gym.vector.utils.spaces import batch_space, iterate from tests.vector.utils import CustomSpace, assert_rng_equal, custom_spaces, spaces expected_batch_spaces_4 ...
200
6,908
gym
tests/vector/test_sync_vector_env.py
.py
import numpy as np import pytest from gym.envs.registration import EnvSpec from gym.spaces import Box, Discrete, MultiDiscrete, Tuple from gym.vector.sync_vector_env import SyncVectorEnv from tests.envs.utils import all_testing_env_specs from tests.vector.utils import ( CustomSpace, assert_rng_equal, make_...
178
5,756
gym
tests/vector/test_vector_env_wrapper.py
.py
import numpy as np from gym.vector import VectorEnvWrapper, make class DummyWrapper(VectorEnvWrapper): def __init__(self, env): self.env = env self.counter = 0 def reset_async(self, **kwargs): super().reset_async() self.counter += 1 def test_vector_env_wrapper_inheritance()...
32
972
gym
tests/vector/test_vector_make.py
.py
import pytest import gym from gym.vector import AsyncVectorEnv, SyncVectorEnv from gym.wrappers import OrderEnforcing, TimeLimit, TransformObservation from gym.wrappers.env_checker import PassiveEnvChecker from tests.wrappers.utils import has_wrapper def test_vector_make_id(): env = gym.vector.make("CartPole-v1"...
85
2,726
gym
tests/spaces/utils.py
.py
from typing import List import numpy as np from gym.spaces import ( Box, Dict, Discrete, Graph, MultiBinary, MultiDiscrete, Sequence, Space, Text, Tuple, ) TESTING_FUNDAMENTAL_SPACES = [ Discrete(3), Discrete(3, start=-1), Box(low=0.0, high=1.0), Box(low=0.0, h...
104
3,047
gym
tests/spaces/test_space.py
.py
from functools import partial import pytest from gym import Space from gym.spaces import utils TESTING_SPACE = Space() @pytest.mark.parametrize( "func", [ TESTING_SPACE.sample, partial(TESTING_SPACE.contains, None), partial(utils.flatdim, TESTING_SPACE), partial(utils.flatte...
25
561
gym
tests/spaces/test_graph.py
.py
import re import numpy as np import pytest from gym.spaces import Discrete, Graph, GraphInstance def test_node_space_sample(): space = Graph(node_space=Discrete(3), edge_space=None) space.seed(0) sample = space.sample( mask=(tuple(np.array([0, 1, 0], dtype=np.int8) for _ in range(5)), None), ...
138
4,111
gym
tests/spaces/test_sequence.py
.py
import re import numpy as np import pytest import gym.spaces def test_sample(): """Tests the sequence sampling works as expects and the errors are correctly raised.""" space = gym.spaces.Sequence(gym.spaces.Box(0, 1)) # Test integer mask length for length in range(4): sample = space.sample(...
60
1,673
gym
tests/spaces/test_multibinary.py
.py
import numpy as np from gym.spaces import MultiBinary def test_sample(): space = MultiBinary(4) sample = space.sample(mask=np.array([0, 0, 1, 1], dtype=np.int8)) assert np.all(sample == [0, 0, 1, 1]) sample = space.sample(mask=np.array([0, 1, 2, 2], dtype=np.int8)) assert sample[0] == 0 and sam...
20
603
gym
tests/spaces/test_dict.py
.py
from collections import OrderedDict import numpy as np import pytest from gym.spaces import Box, Dict, Discrete def test_dict_init(): with pytest.raises( AssertionError, match=r"^Unexpected Dict space input, expecting dict, OrderedDict or Sequence, actual type: ", ): Dict(Discrete(2)...
141
4,135
gym
tests/spaces/test_box.py
.py
import re import warnings import numpy as np import pytest import gym.error from gym.spaces import Box from gym.spaces.box import get_inf @pytest.mark.parametrize( "box,expected_shape", [ ( # Test with same 1-dim low and high shape Box(low=np.zeros(2), high=np.ones(2), dtype=np.int32), ...
317
10,945
gym
tests/spaces/test_spaces.py
.py
import copy import itertools import json # note: ujson fails this test due to float equality import pickle import tempfile from typing import List, Union import numpy as np import pytest from gym.spaces import Box, Discrete, MultiBinary, MultiDiscrete, Space, Text from gym.utils import seeding from gym.utils.env_che...
481
18,219
gym
tests/spaces/test_discrete.py
.py
import numpy as np from gym.spaces import Discrete def test_space_legacy_pickling(): """Test the legacy pickle of Discrete that is missing the `start` parameter.""" legacy_state = { "shape": ( 1, 2, 3, ), "dtype": np.int64, "np_random": np.r...
41
1,167
gym
tests/spaces/test_utils.py
.py
from itertools import zip_longest from typing import Optional import numpy as np import pytest import gym from gym.spaces import Box, Graph, utils from gym.utils.env_checker import data_equivalence from tests.spaces.utils import TESTING_SPACES, TESTING_SPACES_IDS TESTING_SPACES_EXPECTED_FLATDIMS = [ # Discrete ...
136
3,718
gym
tests/spaces/test_multidiscrete.py
.py
import pytest from gym.spaces import Discrete, MultiDiscrete from gym.utils.env_checker import data_equivalence def test_multidiscrete_as_tuple(): # 1D multi-discrete space = MultiDiscrete([3, 4, 5]) assert space.shape == (3,) assert space[0] == Discrete(3) assert space[0:1] == MultiDiscrete([3]...
67
2,507
gym
tests/spaces/test_tuple.py
.py
import numpy as np import pytest import gym.spaces from gym.spaces import Box, Dict, Discrete, MultiBinary, Tuple from gym.utils.env_checker import data_equivalence def test_sequence_inheritance(): """The gym Tuple space inherits from abc.Sequences, this test checks all functions work""" spaces = [Discrete(5...
110
3,035
gym
tests/spaces/test_text.py
.py
import re import numpy as np import pytest from gym.spaces import Text def test_sample_mask(): space = Text(min_length=1, max_length=5) # Test the sample length sample = space.sample(mask=(3, None)) assert sample in space assert len(sample) == 3 sample = space.sample(mask=None) assert ...
42
1,091
gym
tests/utils/test_env_checker.py
.py
"""Tests that the `env_checker` runs as expects and all errors are possible.""" import re import warnings from typing import Tuple, Union import numpy as np import pytest import gym from gym import spaces from gym.core import ObsType from gym.utils.env_checker import ( check_env, check_reset_options, chec...
263
9,325
gym
tests/utils/test_play.py
.py
from functools import partial from itertools import product from typing import Callable import numpy as np import pygame import pytest from pygame import KEYDOWN, KEYUP, QUIT, event from pygame.event import Event import gym from gym.utils.play import MissingKeysToAction, PlayableGame, play from tests.testing_env impo...
210
6,763
gym
tests/utils/test_save_video.py
.py
import os import shutil import numpy as np import gym from gym.utils.save_video import capped_cubic_video_schedule, save_video def test_record_video_using_default_trigger(): env = gym.make( "CartPole-v1", render_mode="rgb_array_list", disable_env_checker=True ) env.reset() step_starting_ind...
118
3,573
gym
tests/utils/test_seeding.py
.py
import pickle from gym import error from gym.utils import seeding def test_invalid_seeds(): for seed in [-1, "test"]: try: seeding.np_random(seed) except error.Error: pass else: assert False, f"Invalid seed {seed} passed validation" def test_valid_see...
31
721
gym
tests/utils/test_step_api_compatibility.py
.py
import numpy as np import pytest from gym.utils.env_checker import data_equivalence from gym.utils.step_api_compatibility import ( convert_to_done_step_api, convert_to_terminated_truncated_step_api, ) @pytest.mark.parametrize( "is_vector_env, done_returns, expected_terminated, expected_truncated", ( ...
170
6,019
gym
tests/utils/test_passive_env_checker.py
.py
import re import warnings from typing import Dict, Union import numpy as np import pytest import gym from gym import spaces from gym.utils.passive_env_checker import ( check_action_space, check_obs, check_observation_space, env_render_passive_checker, env_reset_passive_checker, env_step_passiv...
459
17,819
gym
tests/envs/test_envs.py
.py
import pickle import warnings import numpy as np import pytest import gym from gym.envs.registration import EnvSpec from gym.logger import warn from gym.utils.env_checker import check_env, data_equivalence from tests.envs.utils import ( all_testing_env_specs, all_testing_initialised_envs, assert_equals, )...
201
7,474
gym
tests/envs/utils.py
.py
"""Finds all the specs that we can test with""" from typing import List, Optional import numpy as np import gym from gym import error, logger from gym.envs.registration import EnvSpec def try_make_env(env_spec: EnvSpec) -> Optional[gym.Env]: """Tries to make the environment showing if it is possible. Warni...
89
2,770
gym
tests/envs/test_env_implementation.py
.py
from typing import Optional import numpy as np import pytest import gym from gym.envs.box2d import BipedalWalker from gym.envs.box2d.lunar_lander import demo_heuristic_lander from gym.envs.toy_text import TaxiEnv from gym.envs.toy_text.frozen_lake import generate_random_map def test_lunar_lander_heuristics(): "...
216
7,592
gym
tests/envs/test_compatibility.py
.py
import sys from typing import Any, Dict, Optional, Tuple import numpy as np import gym from gym.spaces import Discrete from gym.wrappers.compatibility import EnvCompatibility, LegacyEnv class LegacyEnvExplicit(LegacyEnv, gym.Env): """Legacy env that explicitly implements the old API.""" observation_space =...
131
3,885
gym
tests/envs/utils_envs.py
.py
import gym class RegisterDuringMakeEnv(gym.Env): """Used in `test_registration.py` to check if `env.make` can import and register an env""" def __init__(self): self.action_space = gym.spaces.Discrete(1) self.observation_space = gym.spaces.Discrete(1) class ArgumentEnv(gym.Env): observat...
50
1,382
gym
tests/envs/test_action_dim_check.py
.py
import numpy as np import pytest import gym from gym import spaces from gym.envs.registration import EnvSpec from tests.envs.utils import all_testing_initialised_envs, mujoco_testing_env_specs @pytest.mark.parametrize( "env_spec", mujoco_testing_env_specs, ids=[env_spec.id for env_spec in mujoco_testing_...
137
4,045
gym
tests/envs/test_register.py
.py
"""Tests that `gym.register` works as expected.""" import re from typing import Optional import pytest import gym @pytest.fixture(scope="function") def register_testing_envs(): """Registers testing environments.""" namespace = "MyAwesomeNamespace" versioned_name = "MyAwesomeVersionedEnv" unversioned...
199
6,631
gym
tests/envs/test_make.py
.py
"""Tests that gym.make works as expected.""" import re import warnings from copy import deepcopy import numpy as np import pytest import gym from gym.envs.classic_control import cartpole from gym.wrappers import AutoResetWrapper, HumanRendering, OrderEnforcing, TimeLimit from gym.wrappers.env_checker import PassiveE...
311
10,418
gym
tests/envs/test_spec.py
.py
"""Tests that gym.spec works as expected.""" import re import pytest import gym def test_spec(): spec = gym.spec("CartPole-v1") assert spec.id == "CartPole-v1" assert spec is gym.envs.registry["CartPole-v1"] def test_spec_kwargs(): map_name_value = "8x8" env = gym.make("FrozenLake-v1", map_na...
93
2,694
gym
tests/envs/test_mujoco.py
.py
import numpy as np import pytest import gym from gym import envs from gym.envs.registration import EnvSpec from tests.envs.utils import mujoco_testing_env_specs EPS = 1e-6 def verify_environments_match( old_env_id: str, new_env_id: str, seed: int = 1, num_actions: int = 1000 ): """Verifies with two environm...
123
4,833
OpenVoice
setup.py
.py
from setuptools import setup, find_packages setup(name='MyShell-OpenVoice', version='0.0.0', description='Instant voice cloning by MyShell.', long_description=open('README.md').read().strip(), long_description_content_type='text/markdown', keywords=[ 'text-to-speech', ...
46
1,481
OpenVoice
openvoice/se_extractor.py
.py
import os import glob import torch import hashlib import librosa import base64 from glob import glob import numpy as np from pydub import AudioSegment from faster_whisper import WhisperModel import hashlib import base64 import librosa from whisper_timestamped.transcribe import get_audio_tensor, get_vad_segments model_...
154
5,145
OpenVoice
openvoice/commons.py
.py
import math import torch from torch.nn import functional as F def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std) def get_padding(kernel_size, dilation=1): return int((kernel_size * dilation - dilation) / 2) ...
161
4,956
OpenVoice
openvoice/utils.py
.py
import re import json import numpy as np def get_hparams_from_file(config_path): with open(config_path, "r", encoding="utf-8") as f: data = f.read() config = json.loads(data) hparams = HParams(**config) return hparams class HParams: def __init__(self, **kwargs): for k, v in kwarg...
194
5,776
OpenVoice
openvoice/models.py
.py
import math import torch from torch import nn from torch.nn import functional as F from openvoice import commons from openvoice import modules from openvoice import attentions from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from openvoice...
500
16,801
OpenVoice
openvoice/attentions.py
.py
import math import torch from torch import nn from torch.nn import functional as F from openvoice import commons import logging logger = logging.getLogger(__name__) class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = ...
466
16,360
OpenVoice
openvoice/mel_processing.py
.py
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C) def dynamic_range_decompr...
183
6,098
OpenVoice
openvoice/modules.py
.py
import math import torch from torch import nn from torch.nn import functional as F from torch.nn import Conv1d from torch.nn.utils import weight_norm, remove_weight_norm from openvoice import commons from openvoice.commons import init_weights, get_padding from openvoice.transforms import piecewise_rational_quadratic_...
599
19,010
OpenVoice
openvoice/transforms.py
.py
import torch from torch.nn import functional as F import numpy as np DEFAULT_MIN_BIN_WIDTH = 1e-3 DEFAULT_MIN_BIN_HEIGHT = 1e-3 DEFAULT_MIN_DERIVATIVE = 1e-3 def piecewise_rational_quadratic_transform( inputs, unnormalized_widths, unnormalized_heights, unnormalized_derivatives, inverse=False, ...
210
7,253
OpenVoice
openvoice/openvoice_app.py
.py
import os import torch import argparse import gradio as gr from zipfile import ZipFile import langid from openvoice import se_extractor from openvoice.api import BaseSpeakerTTS, ToneColorConverter parser = argparse.ArgumentParser() parser.add_argument("--share", action='store_true', default=False, help="make link publ...
276
11,625
OpenVoice
openvoice/api.py
.py
import torch import numpy as np import re import soundfile from openvoice import utils from openvoice import commons import os import librosa from openvoice.text import text_to_sequence from openvoice.mel_processing import spectrogram_torch from openvoice.models import SynthesizerTrn class OpenVoiceBaseClass(object):...
203
7,823
OpenVoice
openvoice/text/mandarin.py
.py
import os import sys import re from pypinyin import lazy_pinyin, BOPOMOFO import jieba import cn2an import logging # List of (Latin alphabet, bopomofo) pairs: _latin_to_bopomofo = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ ('a', 'ㄟˉ'), ('b', 'ㄅㄧˋ'), ('c', 'ㄙㄧˉ'), ('d', 'ㄉㄧˋ'), ('e'...
327
7,717
OpenVoice
openvoice/text/cleaners.py
.py
import re from openvoice.text.english import english_to_lazy_ipa, english_to_ipa2, english_to_lazy_ipa2 from openvoice.text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo, chinese_to_romaji, chinese_to_lazy_ipa, chinese_to_ipa, chinese_to_ipa2 def cjke_cleaners2(text): text = re.sub(r'\[...
16
846
OpenVoice
openvoice/text/symbols.py
.py
''' Defines the set of symbols used in text input to the model. ''' # japanese_cleaners # _pad = '_' # _punctuation = ',.!?-' # _letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧ↓↑ ' '''# japanese_cleaners2 _pad = '_' _punctuation = ',.!?-~…' _letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧʦ↓↑ ' ''' '''# korean_...
88
2,588
OpenVoice
openvoice/text/__init__.py
.py
""" from https://github.com/keithito/tacotron """ from openvoice.text import cleaners from openvoice.text.symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} def text_to_sequence(text,...
80
2,757
OpenVoice
openvoice/text/english.py
.py
""" from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use...
189
5,559
pytorch-image-models
inference.py
.py
#!/usr/bin/env python3 """PyTorch Inference Script An example inference script that outputs top-k class ids for images in a folder into a csv. Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman) """ import argparse import json import logging import os import time from contextlib import su...
390
17,861
pytorch-image-models
train.py
.py
#!/usr/bin/env python3 """ ImageNet Training Script This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet training results with some of the latest networks and training techniques. It favours canonical PyTorch and standard Python style over trying to be able to 'do it al...
1,534
73,502
pytorch-image-models
benchmark.py
.py
#!/usr/bin/env python3 """ Model Benchmark Script An inference and train step benchmark script for timm models. Hacked together by Ross Wightman (https://github.com/rwightman) """ import argparse import csv import json import logging import time from collections import OrderedDict from contextlib import suppress from...
693
28,381