index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
47,958 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 119,120 | 74,240 | conjunction | Condition | 140,142 | 120,142 | @dataclass(frozen=True)
class Condition:
"""This encompasses an expression to evaluate to a logical result."""
def evaluate(self, **kwargs) -> ConditionState:
"""Used to evaluate if a condition is met.
Returns:
ConditionState: The evaluation result of the condition.
"""
... | @dataclass(frozen=True)
class Condition:
"""This encompasses an expression to evaluate to a logical result."""
def evaluate(self, **kwargs) -> ConditionState:
"""Used to evaluate if a condition is met.
Returns:
ConditionState: The evaluation result of the condition.
"""
... | return CompoundCondition(self, other, operator=ConditionOperator.CONJUNCTION)
| """Resolve conditions as A AND B.
The bit AND operator has been overloaded to call this method.
>>> condition = DependeeActorCondition("leader")
>>> condition.evaluate(actor_ids={"leader"})
<ConditionState.TRUE: 4>
>>> conjunction = condition & LiteralCondition(Condition... | 4 | 1,729 | 24 | 1,753 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,959 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 415,416 | 388,452 | evaluate | ConditionTrigger | 416,439 | 416,439 | @dataclass(frozen=True)
class ConditionTrigger(Condition):
"""This condition is a trigger that assumes an untriggered constant state and then turns to the other state permanently
on the inner condition becoming TRUE. There is also an option to delay response to the the inner condition by a number
of seconds... | @dataclass(frozen=True)
class ConditionTrigger(Condition):
"""This condition is a trigger that assumes an untriggered constant state and then turns to the other state permanently
on the inner condition becoming TRUE. There is also an option to delay response to the the inner condition by a number
of seconds... | time = kwargs[ConditionRequires.time.name]
key = "met_time"
result = self.untriggered_state
met_time = getattr(self, key, -1)
if met_time == -1:
if self.inner_condition.evaluate(**kwargs):
object.__setattr__(self, key, time)
time = 0
... | time = kwargs[ConditionRequires.time.name]
key = "met_time"
result = self.untriggered_state
met_time = getattr(self, key, -1)
if met_time == -1:
if self.inner_condition.evaluate(**kwargs):
object.__setattr__(self, key, time)
time = 0
... | 61 | 439 | 242 | 681 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,960 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 306,307 | 299,320 | evaluate | DependeeActorCondition | 307,312 | 307,312 | @dataclass(frozen=True)
class DependeeActorCondition(Condition):
"""This condition should be true if the given actor exists."""
actor_id: str
"""The id of an actor in the simulation that needs to exist for this condition to be true."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY ... | @dataclass(frozen=True)
class DependeeActorCondition(Condition):
"""This condition should be true if the given actor exists."""
actor_id: str
"""The id of an actor in the simulation that needs to exist for this condition to be true."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY ... | actor_ids = kwargs[self.requires.name]
if self.actor_id in actor_ids:
return ConditionState.TRUE
return ConditionState.FALSE
| actor_ids = kwargs[self.requires.name]
if self.actor_id in actor_ids:
return ConditionState.TRUE
return ConditionState.FALSE
| 11 | 147 | 50 | 197 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,961 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 363,364 | 347,388 | evaluate | ExpireTrigger | 364,377 | 364,377 | @dataclass(frozen=True)
class ExpireTrigger(Condition):
"""This condition allows for expiration after a given time."""
inner_condition: Condition
"""The inner condition to delay."""
time: float
"""The simulation time when this trigger becomes expired."""
expired_state: ConditionState = Condit... | @dataclass(frozen=True)
class ExpireTrigger(Condition):
"""This condition allows for expiration after a given time."""
inner_condition: Condition
"""The inner condition to delay."""
time: float
"""The simulation time when this trigger becomes expired."""
expired_state: ConditionState = Condit... | time = kwargs[ConditionRequires.time.name]
if self.relative:
key = "met"
met_time = getattr(self, key, -1)
if met_time == -1:
object.__setattr__(self, key, time)
time = 0
else:
time -= met_time
if tim... | time = kwargs[ConditionRequires.time.name]
if self.relative:
key = "met"
met_time = getattr(self, key, -1)
if met_time == -1:
object.__setattr__(self, key, time)
time = 0
else:
time -= met_time
if tim... | 35 | 255 | 133 | 388 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,962 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 272,274 | 262,277 | requires | LiteralCondition | 274,277 | 274,277 | @dataclass(frozen=True)
class LiteralCondition(Condition):
"""This condition evaluates as a literal without considering evaluation parameters."""
literal: ConditionState
"""The literal value of this condition."""
def evaluate(self, **kwargs) -> ConditionState:
return self.literal
@propert... | @dataclass(frozen=True)
class LiteralCondition(Condition):
"""This condition evaluates as a literal without considering evaluation parameters."""
literal: ConditionState
"""The literal value of this condition."""
def evaluate(self, **kwargs) -> ConditionState:
return self.literal
@propert... | return ConditionRequires.none
| return ConditionRequires.none
| 2 | 103 | 13 | 116 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,963 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 330,331 | 320,347 | evaluate | NegatedCondition | 331,336 | 331,336 | @dataclass(frozen=True)
class NegatedCondition(Condition):
"""This condition negates the inner condition to flip between TRUE and FALSE.
Note\\: This erases temporal values EXPIRED and BEFORE.
"""
inner_condition: Condition
"""The inner condition to negate."""
def evaluate(self, **kwargs) -> ... | @dataclass(frozen=True)
class NegatedCondition(Condition):
"""This condition negates the inner condition to flip between TRUE and FALSE.
Note\\: This erases temporal values EXPIRED and BEFORE.
"""
inner_condition: Condition
"""The inner condition to negate."""
def evaluate(self, **kwargs) -> ... | result = self.inner_condition.evaluate(**kwargs)
if ConditionState.TRUE in result:
return ConditionState.FALSE
return ConditionState.TRUE
| result = self.inner_condition.evaluate(**kwargs)
if ConditionState.TRUE in result:
return ConditionState.FALSE
return ConditionState.TRUE
| 11 | 198 | 46 | 244 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,964 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 456,457 | 452,474 | evaluate | OffRoadCondition | 457,469 | 457,469 | @dataclass(frozen=True)
class OffRoadCondition(SubjectCondition):
"""This condition is true if the subject is on road."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY @property
def requires(self) -> ConditionRequires:
return ConditionRequires.current_actor_road_status
| @dataclass(frozen=True)
class OffRoadCondition(SubjectCondition):
"""This condition is true if the subject is on road."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY @property
def requires(self) -> ConditionRequires:
return ConditionRequires.current_actor_road_status
| current_actor_road_status = kwargs[self.requires.name]
if (
current_actor_road_status.road is None
and not current_actor_road_status.off_road
):
return ConditionState.BEFORE
return (
ConditionState.TRUE
if current_actor_road_sta... | current_actor_road_status = kwargs[self.requires.name]
if (
current_actor_road_status.road is None
and not current_actor_road_status.off_road
):
return ConditionState.BEFORE
return (
ConditionState.TRUE
if current_actor_road_sta... | 22 | 95 | 113 | 208 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,965 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 244,245 | 240,259 | evaluate | SubjectCondition | 252,254 | 245,254 | @dataclass(frozen=True)
class SubjectCondition(Condition):
"""This condition assumes that there is a subject involved."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY @property
def requires(self) -> ConditionRequires:
return ConditionRequires.current_actor_state
| @dataclass(frozen=True)
class SubjectCondition(Condition):
"""This condition assumes that there is a subject involved."""
def evaluate(self, **kwargs) -> ConditionState:
"""Used to evaluate if a condition is met.
Args:
actor_info: Information about the currently relevant actor.
... | raise NotImplementedError()
| """Used to evaluate if a condition is met.
Args:
actor_info: Information about the currently relevant actor.
Returns:
ConditionState: The evaluation result of the condition.
"""
raise NotImplementedError()
| 2 | 140 | 12 | 152 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,966 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 286,287 | 277,299 | evaluate | TimeWindowCondition | 287,294 | 287,294 | @dataclass(frozen=True)
class TimeWindowCondition(Condition):
"""This condition should be true in the given simulation time window."""
start: float
"""The starting simulation time before which this condition becomes false."""
end: float
"""The ending simulation time as of which this condition becom... | @dataclass(frozen=True)
class TimeWindowCondition(Condition):
"""This condition should be true in the given simulation time window."""
start: float
"""The starting simulation time before which this condition becomes false."""
end: float
"""The ending simulation time as of which this condition becom... | time = kwargs[ConditionRequires.time.name]
if self.start <= time < self.end or self.end == sys.maxsize:
return ConditionState.TRUE
elif time > self.end:
return ConditionState.EXPIRED
return ConditionState.BEFORE
| time = kwargs[ConditionRequires.time.name]
if self.start <= time < self.end or self.end == sys.maxsize:
return ConditionState.TRUE
elif time > self.end:
return ConditionState.EXPIRED
return ConditionState.BEFORE
| 23 | 129 | 80 | 209 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,967 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 503,504 | 493,521 | evaluate | VehicleSpeedCondition | 504,511 | 504,511 | @dataclass(frozen=True)
class VehicleSpeedCondition(SubjectCondition):
"""This condition is true if the subject has a speed between low and high."""
low: float
"""The lowest speed allowed."""
high: float
"""The highest speed allowed."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUN... | @dataclass(frozen=True)
class VehicleSpeedCondition(SubjectCondition):
"""This condition is true if the subject has a speed between low and high."""
low: float
"""The lowest speed allowed."""
high: float
"""The highest speed allowed."""
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUN... | vehicle_state = kwargs[self.requires.name]
return (
ConditionState.TRUE
if self.low <= vehicle_state.speed <= self.high
else ConditionState.FALSE
)
| vehicle_state = kwargs[self.requires.name]
return (
ConditionState.TRUE
if self.low <= vehicle_state.speed <= self.high
else ConditionState.FALSE
)
| 15 | 192 | 61 | 253 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,968 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/condition.py | 480,481 | 474,493 | evaluate | VehicleTypeCondition | 481,488 | 481,488 | @dataclass(frozen=True)
class VehicleTypeCondition(SubjectCondition):
"""This condition is true if the subject is of the given vehicle types."""
vehicle_type: str
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY @property
def requires(self) -> ConditionRequires:
return Conditi... | @dataclass(frozen=True)
class VehicleTypeCondition(SubjectCondition):
"""This condition is true if the subject is of the given vehicle types."""
vehicle_type: str
def evaluate(self, **kwargs) -> ConditionState:
FILL_FUNC_BODY @property
def requires(self) -> ConditionRequires:
return Conditi... | current_actor_state = kwargs[self.requires.name]
return (
ConditionState.TRUE
if current_actor_state.vehicle_config_type == self.vehicle_type
else ConditionState.FALSE
)
| current_actor_state = kwargs[self.requires.name]
return (
ConditionState.TRUE
if current_actor_state.vehicle_config_type == self.vehicle_type
else ConditionState.FALSE
)
| 13 | 105 | 71 | 176 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,969 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/distribution.py | 37,38 | 28,42 | sample | Distribution | 39,42 | 38,42 | @dataclass(frozen=True)
class Distribution:
"""A gaussian distribution used for randomized parameters."""
mean: float
"""The mean value of the gaussian distribution."""
sigma: float
"""The sigma value of the gaussian distribution."""
def sample(self):
FILL_FUNC_BODY | @dataclass(frozen=True)
class Distribution:
"""A gaussian distribution used for randomized parameters."""
mean: float
"""The mean value of the gaussian distribution."""
sigma: float
"""The sigma value of the gaussian distribution."""
def sample(self):
"""The next sample from the distri... | return random.gauss(self.mean, self.sigma)
| """The next sample from the distribution."""
return random.gauss(self.mean, self.sigma)
| 3 | 95 | 21 | 116 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,970 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/distribution.py | 55,56 | 42,58 | sample | UniformDistribution | 57,58 | 56,58 | @dataclass
class UniformDistribution:
"""A uniform distribution, return a random number N
such that a <= N <= b for a <= b and b <= N <= a for b < a.
"""
a: float
b: float
def __post_init__(self):
if self.b < self.a:
self.a, self.b = self.b, self.a
def sample(self):
FI... | @dataclass
class UniformDistribution:
"""A uniform distribution, return a random number N
such that a <= N <= b for a <= b and b <= N <= a for b < a.
"""
a: float
b: float
def __post_init__(self):
if self.b < self.a:
self.a, self.b = self.b, self.a
def sample(self):
... | return random.uniform(self.a, self.b)
| """Get the next sample."""
return random.uniform(self.a, self.b)
| 3 | 127 | 16 | 143 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,971 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/route.py | 41,42 | 32,53 | to_edge | JunctionEdgeIDResolver | 45,53 | 42,53 | @dataclass(frozen=True)
class JunctionEdgeIDResolver:
"""A utility for resolving a junction connection edge"""
start_edge_id: str
start_lane_index: int
end_edge_id: str
end_lane_index: int
def to_edge(self, sumo_road_network) -> str:
FILL_FUNC_BODY | @dataclass(frozen=True)
class JunctionEdgeIDResolver:
"""A utility for resolving a junction connection edge"""
start_edge_id: str
start_lane_index: int
end_edge_id: str
end_lane_index: int
def to_edge(self, sumo_road_network) -> str:
"""Queries the road network to see if there is a jun... | return sumo_road_network.get_edge_in_junction(
self.start_edge_id,
self.start_lane_index,
self.end_edge_id,
self.end_lane_index,
)
| """Queries the road network to see if there is a junction edge between the two
given edges.
"""
return sumo_road_network.get_edge_in_junction(
self.start_edge_id,
self.start_lane_index,
self.end_edge_id,
self.end_lane_index,
)
| 7 | 130 | 74 | 204 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,972 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/route.py | 100,102 | 53,112 | roads | Route | 103,105 | 102,105 | @dataclass(frozen=True)
class Route:
"""A route is represented by begin and end road IDs, with an optional list of
intermediary road IDs. When an intermediary is not specified the router will
decide what it should be.
"""
## road, lane index, offset
begin: Tuple[str, int, Any]
"""The (road,... | @dataclass(frozen=True)
class Route:
"""A route is represented by begin and end road IDs, with an optional list of
intermediary road IDs. When an intermediary is not specified the router will
decide what it should be.
"""
## road, lane index, offset
begin: Tuple[str, int, Any]
"""The (road,... | return (self.begin[0],) + self.via + (self.end[0],)
| """All roads that are used within this route."""
return (self.begin[0],) + self.via + (self.end[0],)
| 6 | 545 | 27 | 572 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,973 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/standard_metadata.py | 71,73 | 29,78 | _hash_id | StandardMetadata | 73,75 | 73,75 | class StandardMetadata(Mapping):
"""Metadata that does not have direct influence on the simulation."""
def __init__(
self,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
if metadata is None:
metadata = {}
self._standard_metadata = tuple(
(
... | class StandardMetadata(Mapping):
"""Metadata that does not have direct influence on the simulation."""
def __init__(
self,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
if metadata is None:
metadata = {}
self._standard_metadata = tuple(
(
... | return hash(frozenset(self._standard_metadata))
| return hash(frozenset(self._standard_metadata))
| 2 | 395 | 19 | 414 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,974 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/traffic.py | 56,58 | 31,73 | id | Flow | 59,64 | 58,64 | @dataclass(frozen=True)
class Flow:
"""A route with an actor type emitted at a given rate."""
route: Union[RandomRoute, Route]
"""The route for the actor to attempt to follow."""
rate: float
"""Vehicles per hour."""
begin: float = 0
"""Start time in seconds."""
# XXX: Defaults to 1 hour... | @dataclass(frozen=True)
class Flow:
"""A route with an actor type emitted at a given rate."""
route: Union[RandomRoute, Route]
"""The route for the actor to attempt to follow."""
rate: float
"""Vehicles per hour."""
begin: float = 0
"""Start time in seconds."""
# XXX: Defaults to 1 hour... | return "{}-{}".format(
self.route.id,
str(hash(self))[:6],
)
| """The unique id of this flow."""
return "{}-{}".format(
self.route.id,
str(hash(self))[:6],
)
| 5 | 427 | 38 | 465 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,975 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/traffic.py | 103,105 | 73,117 | id | Trip | 106,108 | 105,108 | @dataclass(frozen=True)
class Trip:
"""A route with a single actor type with name and unique id."""
vehicle_name: str
"""The name of the vehicle. It must be unique. """
route: Union[RandomRoute, Route]
"""The route for the actor to attempt to follow."""
vehicle_type: str = "passenger"
"""Th... | @dataclass(frozen=True)
class Trip:
"""A route with a single actor type with name and unique id."""
vehicle_name: str
"""The name of the vehicle. It must be unique. """
route: Union[RandomRoute, Route]
"""The route for the actor to attempt to follow."""
vehicle_type: str = "passenger"
"""Th... | return self.vehicle_name
| """The unique id of this trip."""
return self.vehicle_name
| 2 | 390 | 13 | 403 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,976 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/traffic_model.py | 44,45 | 32,77 | keep_snake_case | _SumoParams | 45,48 | 45,48 | class _SumoParams(collections_abc.Mapping):
"""For some Sumo params (e.g. LaneChangingModel) the arguments are in title case
with a given prefix. Subclassing this class allows for an automatic way to map
between PEP8-compatible naming and Sumo's.
"""
def __init__(
self, prefix, whitelist=[]... | class _SumoParams(collections_abc.Mapping):
"""For some Sumo params (e.g. LaneChangingModel) the arguments are in title case
with a given prefix. Subclassing this class allows for an automatic way to map
between PEP8-compatible naming and Sumo's.
"""
def __init__(
self, prefix, whitelist=[]... | w = word[0].upper() + word[1:]
return "".join(x or "_" for x in w.split("_"))
| w = word[0].upper() + word[1:]
return "".join(x or "_" for x in w.split("_"))
| 13 | 475 | 39 | 514 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,977 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/zone.py | 243,244 | 214,263 | to_geometry | ConfigurableZone | 245,263 | 244,263 | @dataclass(frozen=True)
class ConfigurableZone(Zone):
"""A descriptor for a zone with user-defined geometry."""
ext_coordinates: List[Tuple[float, float]]
"""external coordinates of the polygon
< 2 points provided: error
= 2 points provided: generates a box using these two points as diagonal
> ... | @dataclass(frozen=True)
class ConfigurableZone(Zone):
"""A descriptor for a zone with user-defined geometry."""
ext_coordinates: List[Tuple[float, float]]
"""external coordinates of the polygon
< 2 points provided: error
= 2 points provided: generates a box using these two points as diagonal
> ... | poly = None
if (
len(self.ext_coordinates) == 2
): # if user only specified two points, create a box
x_min = min(self.ext_coordinates[0][0], self.ext_coordinates[1][0])
x_max = max(self.ext_coordinates[0][0], self.ext_coordinates[1][0])
y_min = mi... | """Generate a polygon according to given coordinates"""
poly = None
if (
len(self.ext_coordinates) == 2
): # if user only specified two points, create a box
x_min = min(self.ext_coordinates[0][0], self.ext_coordinates[1][0])
x_max = max(self.ext_coord... | 66 | 362 | 270 | 632 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,978 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/zone.py | 73,74 | 54,190 | to_geometry | MapZone | 75,190 | 74,190 | @dataclass(frozen=True)
class MapZone(Zone):
"""A descriptor that defines a capture area."""
start: Tuple[str, int, float]
"""The (road_id, lane_index, offset) details of the starting location.
road_id:
The starting road by name.
lane_index:
The lane index from the rightmost lane.
... | @dataclass(frozen=True)
class MapZone(Zone):
"""A descriptor that defines a capture area."""
start: Tuple[str, int, float]
"""The (road_id, lane_index, offset) details of the starting location.
road_id:
The starting road by name.
lane_index:
The lane index from the rightmost lane.
... |
assert (
road_map is not None
), f"{self.__class__.__name__} requires a road map to resolve geometry."
def resolve_offset(offset, geometry_length, lane_length):
if offset == "base":
return 0
# push off of end of lane
elif offset =... | """Generates a map zone over a stretch of the given lanes."""
assert (
road_map is not None
), f"{self.__class__.__name__} requires a road map to resolve geometry."
def resolve_offset(offset, geometry_length, lane_length):
if offset == "base":
re... | 355 | 228 | 1,427 | 1,655 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,979 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/zone.py | 202,203 | 190,214 | to_geometry | PositionalZone | 204,214 | 203,214 | @dataclass(frozen=True)
class PositionalZone(Zone):
"""A descriptor that defines a capture area at a specific XY location."""
# center point
pos: Tuple[float, float]
"""A (x,y) position of the zone in the scenario."""
size: Tuple[float, float]
"""The (length, width) dimensions of the zone."""
... | @dataclass(frozen=True)
class PositionalZone(Zone):
"""A descriptor that defines a capture area at a specific XY location."""
# center point
pos: Tuple[float, float]
"""A (x,y) position of the zone in the scenario."""
size: Tuple[float, float]
"""The (length, width) dimensions of the zone."""
... | w, h = self.size
x, y = self.pos[:2]
p0 = (-w / 2, -h / 2) # min
p1 = (w / 2, h / 2) # max
poly = Polygon([p0, (p0[0], p1[1]), p1, (p1[0], p0[1])])
if self.rotation is not None:
poly = shapely_rotate(poly, self.rotation, use_radians=True)
return shap... | """Generates a box zone at the given position."""
w, h = self.size
x, y = self.pos[:2]
p0 = (-w / 2, -h / 2) # min
p1 = (w / 2, h / 2) # max
poly = Polygon([p0, (p0[0], p1[1]), p1, (p1[0], p0[1])])
if self.rotation is not None:
poly = shapely_rotate(... | 50 | 177 | 166 | 343 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,980 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sstypes/zone.py | 49,50 | 45,54 | to_geometry | Zone | 51,54 | 50,54 | @dataclass(frozen=True)
class Zone:
"""The base for a descriptor that defines a capture area."""
def to_geometry(self, road_map: Optional[RoadMap] = None) -> Polygon:
FILL_FUNC_BODY | @dataclass(frozen=True)
class Zone:
"""The base for a descriptor that defines a capture area."""
def to_geometry(self, road_map: Optional[RoadMap] = None) -> Polygon:
"""Generates the geometry from this zone."""
FILL_FUNC_BODY | raise NotImplementedError
| """Generates the geometry from this zone."""
raise NotImplementedError
| 2 | 79 | 13 | 92 | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | # MIT License
#
# Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
47,981 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/sstudio/sumo2mesh.py | 26,27 | 1,43 | generate_glb_from_sumo_file | 28,33 | 27,33 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | map_spec = MapSpec(sumo_net_file)
road_network = SumoRoadNetwork.from_spec(map_spec)
road_network.to_glb(out_glb_dir)
| """Creates a geometry file from a sumo map file."""
map_spec = MapSpec(sumo_net_file)
road_network = SumoRoadNetwork.from_spec(map_spec)
road_network.to_glb(out_glb_dir)
| 7 | 578 | 61 | 639 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | |
47,982 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/visdom/visdom_client.py | 96,97 | 40,157 | _vis_sim_obs | VisdomClient | 97,125 | 97,125 | class VisdomClient:
"""A client for handling connection to a Visdom server."""
def __init__(self, hostname="http://localhost", port=8097):
self._log = logging.getLogger(self.__class__.__name__)
self._port = port
self._hostname = hostname
self._visdom_obs_queue = self._build_visd... | class VisdomClient:
"""A client for handling connection to a Visdom server."""
def __init__(self, hostname="http://localhost", port=8097):
self._log = logging.getLogger(self.__class__.__name__)
self._port = port
self._hostname = hostname
self._visdom_obs_queue = self._build_visd... | vis_images = defaultdict(list)
for agent_id, agent_obs in self._flatten_obs(sim_obs):
# Visdom image format: Channel x Height x Width
drivable_area = getattr(agent_obs, "drivable_area_grid_map", None)
if drivable_area is not None:
image = drivable_are... | vis_images = defaultdict(list)
for agent_id, agent_obs in self._flatten_obs(sim_obs):
# Visdom image format: Channel x Height x Width
drivable_area = getattr(agent_obs, "drivable_area_grid_map", None)
if drivable_area is not None:
image = drivable_are... | 93 | 1,048 | 423 | 1,471 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,983 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/waymo/gen_sumo_map.py | 115,116 | 35,181 | generate | SumoMapGenerator | 121,181 | 116,181 | class SumoMapGenerator:
"""Extracts the map information from a Waymo Motion Dataset scenario
and generates a SUMO network file.
"""
def __init__(self):
self.nodes_root = None
self.edges_root = None
@staticmethod
def _read_map_data(path: str, scenario_id: str) -> Dict:
s... | class SumoMapGenerator:
"""Extracts the map information from a Waymo Motion Dataset scenario
and generates a SUMO network file.
"""
def __init__(self):
self.nodes_root = None
self.edges_root = None
@staticmethod
def _read_map_data(path: str, scenario_id: str) -> Dict:
s... | edge_counter = SumoMapGenerator._make_counter()
node_counter = SumoMapGenerator._make_counter()
self.nodes_root = ET.Element("nodes")
self.edges_root = ET.Element("edges")
map_features = SumoMapGenerator._read_map_data(path, scenario_id)
base_dir = Path(__file__).absolut... | """
Args:
path (str): Absolute path to the TFRecord file.
scenario_id (str): ID of the scenario to be converted.
"""
edge_counter = SumoMapGenerator._make_counter()
node_counter = SumoMapGenerator._make_counter()
self.nodes_root = ET.Element("nodes... | 134 | 840 | 758 | 1,598 | # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,984 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/zoo/agent_spec.py | 96,97 | 31,134 | build_agent | AgentSpec | 98,134 | 97,134 | @dataclass
class AgentSpec(object):
"""A configuration that is used by SMARTS environments.
.. code-block:: python
agent_spec = AgentSpec(
interface=AgentInterface.from_type(AgentType.Laner),
agent_params={"agent_function": lambda _: "keep_lane"},
agent_builder=Agen... | @dataclass
class AgentSpec(object):
"""A configuration that is used by SMARTS environments.
.. code-block:: python
agent_spec = AgentSpec(
interface=AgentInterface.from_type(AgentType.Laner),
agent_params={"agent_function": lambda _: "keep_lane"},
agent_builder=Agen... | if self.agent_builder is None:
raise ValueError("Can't build agent, no agent builder was supplied")
if not callable(self.agent_builder):
raise ValueError(
f"""agent_builder: {self.agent_builder} is not callable
Use a combination of agent_params and agent_builder ... | """Construct an Agent from the AgentSpec configuration."""
if self.agent_builder is None:
raise ValueError("Can't build agent, no agent builder was supplied")
if not callable(self.agent_builder):
raise ValueError(
f"""agent_builder: {self.agent_builder} i... | 132 | 741 | 412 | 1,153 | # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,985 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/smarts/zoo/registry.py | 53,54 | 1,98 | make | 68,79 | 54,79 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
from smarts.zoo.agent_spec import AgentSpec
agent_spec = agent_registry.make(locator, **kwargs)
assert isinstance(
agent_spec, AgentSpec
), f"Expected make to produce an instance of AgentSpec, got: {agent_spec}"
return agent_spec
| """Create an AgentSpec from the given locator.
In order to load a registered AgentSpec it needs to be reachable from a
directory contained in the PYTHONPATH.
Args:
locator:
A string in the format of 'path.to.file:locator-name' where the path
is in the form `{PYTHONPATH}... | 25 | 950 | 92 | 1,042 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | |
47,986 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/evaluation/metrics/collision/collision_data_parse.py | 15,16 | 9,39 | run_evaluation | CollisionEvaluation | 16,25 | 16,25 | class CollisionEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.agent_name_list = agent_name_list
def run_evaluation(self):
FILL_FUNC_BODY def collision_result(self, j... | class CollisionEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.agent_name_list = agent_name_list
def run_evaluation(self):
FILL_FUNC_BODY def collision_result(self, j... | scenario_agents_data = get_scenario_agents_data(
self.scenarios_data_path, self.agent_name_list
)
collision_score = {}
for scenario_name, data in scenario_agents_data.items():
agent_result = self.collision_result(data)
collision_score[scenario_name] = ... | scenario_agents_data = get_scenario_agents_data(
self.scenarios_data_path, self.agent_name_list
)
collision_score = {}
for scenario_name, data in scenario_agents_data.items():
agent_result = self.collision_result(data)
collision_score[scenario_name] = ... | 23 | 303 | 136 | 439 | from collections import defaultdict
from zoo.evaluation.metrics.utils import (
get_scenario_agents_data,
save_evaluation_result_to_json,
)
class CollisionEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.... | from collections import defaultdict
from zoo.evaluation.metrics.utils import (
get_scenario_agents_data,
save_evaluation_result_to_json,
)
class CollisionEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.... |
47,988 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/evaluation/metrics/diversity/utils.py | 155,156 | 139,160 | GetPoint | Circle | 156,160 | 156,160 | class Circle:
def __init__(self, t0, t1, t2):
a = CountPointDist(t0, t1)
b = CountPointDist(t1, t2)
c = CountPointDist(t0, t2)
tarea = math.fabs(Cross(MinusPoint(t0, t1), MinusPoint(t1, t2)) / 2)
self.r = a * b * c / tarea / 4
c1 = (t0.x * t0.x + t0.y * t0.y - t1.x * ... | class Circle:
def __init__(self, t0, t1, t2):
a = CountPointDist(t0, t1)
b = CountPointDist(t1, t2)
c = CountPointDist(t0, t2)
tarea = math.fabs(Cross(MinusPoint(t0, t1), MinusPoint(t1, t2)) / 2)
self.r = a * b * c / tarea / 4
c1 = (t0.x * t0.x + t0.y * t0.y - t1.x * ... | return self.cx + math.cos(theta) * self.r, self.cy + math.sin(theta) * self.r
# end geometry functions
| return self.cx + math.cos(theta) * self.r, self.cy + math.sin(theta) * self.r
# end geometry functions
| 15 | 418 | 44 | 462 | import math
import warnings
import numpy as np
warnings.filterwarnings("ignore")
eps = 1e-6
max_time_diff = 8
max_dist_diff = 30
vehicle_w = 0.3
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __init__(self, m, n):
self.m = m
self.n = n
def A... | import math
import warnings
import numpy as np
warnings.filterwarnings("ignore")
eps = 1e-6
max_time_diff = 8
max_dist_diff = 30
vehicle_w = 0.3
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __init__(self, m, n):
self.m = m
self.n = n
def A... |
47,990 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/evaluation/metrics/offroad/offroad_data_parse.py | 23,24 | 7,38 | offroad_result | OffroadEvaluation | 24,38 | 24,38 | class OffroadEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.agent_name_list = agent_name_list
def run_evaluation(self):
scenario_agents_data = get_scenario_agen... | class OffroadEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.agent_name_list = agent_name_list
def run_evaluation(self):
scenario_agents_data = get_scenario_agen... | offroad_data_list = []
offroad_result_dict = {}
for json_data in json_curve_list:
offroad_data_list.append(json_data["off_road"])
for i, offroad_list in enumerate(offroad_data_list):
offroad_result_dict[self.agent_name_list[i]] = []
for index, offroad_... | offroad_data_list = []
offroad_result_dict = {}
for json_data in json_curve_list:
offroad_data_list.append(json_data["off_road"])
for i, offroad_list in enumerate(offroad_data_list):
offroad_result_dict[self.agent_name_list[i]] = []
for index, offroad_... | 45 | 241 | 233 | 474 | from zoo.evaluation.metrics.utils import (
get_scenario_agents_data,
save_evaluation_result_to_json,
)
class OffroadEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.... | from zoo.evaluation.metrics.utils import (
get_scenario_agents_data,
save_evaluation_result_to_json,
)
class OffroadEvaluation:
def __init__(self, scenarios_data_path, result_path, agent_name_list):
self.scenarios_data_path = scenarios_data_path
self.result_path = result_path
self.... |
47,991 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/evaluation/metrics/run_evaluation.py | 9,17 | 1,68 | run_all_evaluation | 17,34 | 17,34 | import argparse
from zoo.evaluation.metrics.collision.collision_data_parse import CollisionEvaluation
from zoo.evaluation.metrics.diversity.diversity_evaluation import DiversityEvaluation
from zoo.evaluation.metrics.kinematics.kinematics_evaluation import KinematicsEvaluation
from zoo.evaluation.metrics.offroad.offroa... | import argparse
from zoo.evaluation.metrics.collision.collision_data_parse import CollisionEvaluation
from zoo.evaluation.metrics.diversity.diversity_evaluation import DiversityEvaluation
from zoo.evaluation.metrics.kinematics.kinematics_evaluation import KinematicsEvaluation
from zoo.evaluation.metrics.offroad.offroa... | evaluation_items = {
"diversity": DiversityEvaluation(
scenario_path, diversity_path, agent_group, agent_name_list
),
"offroad": OffroadEvaluation(scenario_path, json_file_path, agent_name_list),
"collision": CollisionEvaluation(
scenario_path, json_file_path,... | evaluation_items = {
"diversity": DiversityEvaluation(
scenario_path, diversity_path, agent_group, agent_name_list
),
"offroad": OffroadEvaluation(scenario_path, json_file_path, agent_name_list),
"collision": CollisionEvaluation(
scenario_path, json_file_path,... | 35 | 520 | 199 | 719 | import argparse
from zoo.evaluation.metrics.collision.collision_data_parse import CollisionEvaluation
from zoo.evaluation.metrics.diversity.diversity_evaluation import DiversityEvaluation
from zoo.evaluation.metrics.kinematics.kinematics_evaluation import KinematicsEvaluation
from zoo.evaluation.metrics.offroad.offroa... | import argparse
from zoo.evaluation.metrics.collision.collision_data_parse import CollisionEvaluation
from zoo.evaluation.metrics.diversity.diversity_evaluation import DiversityEvaluation
from zoo.evaluation.metrics.kinematics.kinematics_evaluation import KinematicsEvaluation
from zoo.evaluation.metrics.offroad.offroa... | |
47,992 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/evaluation/metrics/utils.py | 7,8 | 1,81 | get_evaluation_result | 8,26 | 8,26 | import csv
import json
import os
from pathlib import Path
def get_evaluation_result(_data, evaluation_result, evaluation_type):
FILL_FUNC_BODYdef map_agent_to_json_file(agent_names, all_json_file):
json_file_dict = {}
for json_file in all_json_file:
file_name = os.path.basename(json_file)
cand... | import csv
import json
import os
from pathlib import Path
def get_evaluation_result(_data, evaluation_result, evaluation_type):
FILL_FUNC_BODYdef map_agent_to_json_file(agent_names, all_json_file):
json_file_dict = {}
for json_file in all_json_file:
file_name = os.path.basename(json_file)
cand... | for agent_name, value in _data.items():
if value:
if "pass" in evaluation_result and agent_name in evaluation_result["pass"]:
evaluation_result["pass"].remove(agent_name)
if agent_name in evaluation_result["fail"]:
evaluation_result["fail"][agent_name]... | for agent_name, value in _data.items():
if value:
if "pass" in evaluation_result and agent_name in evaluation_result["pass"]:
evaluation_result["pass"].remove(agent_name)
if agent_name in evaluation_result["fail"]:
evaluation_result["fail"][agent_name]... | 48 | 823 | 220 | 1,043 | import csv
import json
import os
from pathlib import Path
def get_evaluation_result(_data, evaluation_result, evaluation_type):
FILL_FUNC_BODYdef map_agent_to_json_file(agent_names, all_json_file):
json_file_dict = {}
for json_file in all_json_file:
file_name = os.path.basename(json_file)
cand... | import csv
import json
import os
from pathlib import Path
def get_evaluation_result(_data, evaluation_result, evaluation_type):
FILL_FUNC_BODYdef map_agent_to_json_file(agent_names, all_json_file):
json_file_dict = {}
for json_file in all_json_file:
file_name = os.path.basename(json_file)
cand... | |
47,993 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/chase_via_points_agent.py | 52,53 | 1,74 | _nearest_waypoint | 53,74 | 53,74 | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
... | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
... | cur_point_index = ((np.intp(1e10), np.intp(1e10)), None)
if points.shape == (0,):
return cur_point_index
assert len(matrix.shape) == 3
assert matrix.shape[2] == 2
assert len(points.shape) == 2
assert points.shape[1] == 2
points_expanded = np.expand_dims(points, (1, 2))
diff = ... | cur_point_index = ((np.intp(1e10), np.intp(1e10)), None)
if points.shape == (0,):
return cur_point_index
assert len(matrix.shape) == 3
assert matrix.shape[2] == 2
assert len(points.shape) == 2
assert points.shape[1] == 2
points_expanded = np.expand_dims(points, (1, 2))
diff = ... | 69 | 783 | 290 | 1,073 | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
... | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
... | |
47,994 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/chase_via_points_agent.py | 9,10 | 8,52 | act | ChaseViaPointsAgent | 10,52 | 10,52 | class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODY | class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODY | assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
"cannot be empty or None. Enable waypoint paths in agent interface."
)
lane_change_dist = 80
# Truncate all paths to be of the same length
min_len = min(lane_change_dist, min(map(len... | assert obs.waypoint_paths, (
f"Waypoint paths = {obs.waypoint_paths}; "
"cannot be empty or None. Enable waypoint paths in agent interface."
)
lane_change_dist = 80
# Truncate all paths to be of the same length
min_len = min(lane_change_dist, min(map(len... | 190 | 34 | 712 | 746 | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODYdef _nearest_waypoint(matrix: np.ndarray, points: np.ndarray, radius: float = 2... | import numpy as np
from smarts.core.agent import Agent
from smarts.core.observations import Observation
from smarts.core.sensors import LANE_ID_CONSTANT
class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODYdef _nearest_waypoint(matrix: np.ndarray, points: np.ndarray, radius: float = 2... |
47,995 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/cross-rl-agent/cross_rl_agent/agent.py | 31,32 | 1,60 | init_tensorflow | 32,39 | 32,39 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | configProto = tf.compat.v1.ConfigProto()
configProto.gpu_options.allow_growth = True
# reset tensorflow graph
tf.compat.v1.reset_default_graph()
return configProto
| configProto = tf.compat.v1.ConfigProto()
configProto.gpu_options.allow_growth = True
# reset tensorflow graph
tf.compat.v1.reset_default_graph()
return configProto
| 13 | 709 | 68 | 777 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | |
47,996 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/cross-rl-agent/cross_rl_agent/agent.py | 57,58 | 39,60 | act | RLAgent | 58,60 | 58,60 | class RLAgent(Agent):
def __init__(self, load_path, policy_name):
configProto = init_tensorflow()
model_name = policy_name
self.actor = SocMtActorNetwork(name="actor")
critic_1 = SocMtCriticNetwork(name="critic_1")
critic_2 = SocMtCriticNetwork(name="critic_2")
saver ... | class RLAgent(Agent):
def __init__(self, load_path, policy_name):
configProto = init_tensorflow()
model_name = policy_name
self.actor = SocMtActorNetwork(name="actor")
critic_1 = SocMtCriticNetwork(name="critic_1")
critic_2 = SocMtCriticNetwork(name="critic_2")
saver ... | action = self.actor.get_action_noise(self.sess, state, rate=-1)
return action
| action = self.actor.get_action_noise(self.sess, state, rate=-1)
return action
| 7 | 248 | 32 | 280 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,997 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/cross-rl-agent/cross_rl_agent/train/prioritized_replay.py | 220,221 | 128,269 | fill_buffer | Buffer | 221,251 | 221,251 | class Buffer(object):
"""
This SumTree code is modified version of:
https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py
"""
def __init__(self, capacity, pretrain_length):
"""
Remember that our tree is composed of a sum tree that contains the priority scores at his leaf... | class Buffer(object):
"""
This SumTree code is modified version of:
https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py
"""
def __init__(self, capacity, pretrain_length):
"""
Remember that our tree is composed of a sum tree that contains the priority scores at his leaf... | print("Starting to fill buffer...")
print("Using random mode")
observations = env.reset()
state = observations[AGENT_ID]
for i in range(self.pretrain_length):
if i % 500 == 0:
print(i, "experiences stored")
random_action = np.array([rando... | print("Starting to fill buffer...")
print("Using random mode")
observations = env.reset()
state = observations[AGENT_ID]
for i in range(self.pretrain_length):
if i % 500 == 0:
print(i, "experiences stored")
random_action = np.array([rando... | 93 | 1,399 | 302 | 1,701 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,998 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/cross-rl-agent/cross_rl_agent/train/prioritized_replay.py | 62,63 | 28,128 | update | SumTree | 63,86 | 63,86 | class SumTree(object):
"""
This SumTree code is modified version of Morvan Zhou:
https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/blob/master/contents/5.2_Prioritized_Replay_DQN/RL_brain.py"""
data_pointer = 0
# initialise tree with all nodes = 0 and data with all values =0
... | class SumTree(object):
"""
This SumTree code is modified version of Morvan Zhou:
https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/blob/master/contents/5.2_Prioritized_Replay_DQN/RL_brain.py"""
data_pointer = 0
# initialise tree with all nodes = 0 and data with all values =0
... | # change = new priority - former priority score
change = priority - self.tree[tree_index]
self.tree[tree_index] = priority
# then propagate the change through the tree // update whole tree
while tree_index != 0:
r"""
Here we want to access the... | # change = new priority - former priority score
change = priority - self.tree[tree_index]
self.tree[tree_index] = priority
# then propagate the change through the tree // update whole tree
while tree_index != 0:
r"""
Here we want to access the... | 118 | 795 | 257 | 1,052 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
47,999 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/cross-rl-agent/cross_rl_agent/train/utils.py | 41,42 | 1,68 | OU | 42,48 | 42,48 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # noise = np.ones(action_dim) * mu
noise = theta * (mu - action) + sigma * np.random.randn(1)
# noise = noise + d_noise
return noise
| # noise = np.ones(action_dim) * mu
noise = theta * (mu - action) + sigma * np.random.randn(1)
# noise = noise + d_noise
return noise
| 25 | 938 | 62 | 1,000 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | |
48,000 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/human_in_the_loop.py | 46,47 | 15,76 | on_press | HumanKeyboardAgent | 53,66 | 47,66 | class HumanKeyboardAgent(Agent):
def __init__(self):
# initialize the keyboard listener
self.listener = Listener(on_press=self.on_press)
self.listener.start()
# Parameters for the human-keyboard agent
# you need to change them to suit the scenario
# These values work... | class HumanKeyboardAgent(Agent):
def __init__(self):
# initialize the keyboard listener
self.listener = Listener(on_press=self.on_press)
self.listener.start()
# Parameters for the human-keyboard agent
# you need to change them to suit the scenario
# These values work... | if key == Key.up:
self.throttle = min(self.throttle + self.INC_THROT, self.MAX_THROTTLE)
elif key == Key.alt_l:
self.brake = min(self.brake + 10.0 * self.INC_THROT, self.MAX_BRAKE)
elif key == Key.right:
self.steering_angle = min(
self.steering... | """To control, use the keys:
Up: to increase the throttle
Left Alt: to increase the brake
Left: to decrease the steering angle
Right: to increase the steering angle
"""
if key == Key.up:
self.throttle = min(self.throttle + self.INC_THROT, self.MAX_THRO... | 46 | 515 | 204 | 719 | """
This examples runs the human-keyboard Agent, which allows you to control and monitor input devices.
NOTE: You will need to install [extras] to run this example. `pip install -e .[extras]`
"""
try:
from pynput.keyboard import Key, Listener
except ImportError:
raise ImportError("pynput dependency is missing... | """
This examples runs the human-keyboard Agent, which allows you to control and monitor input devices.
NOTE: You will need to install [extras] to run this example. `pip install -e .[extras]`
"""
try:
from pynput.keyboard import Key, Listener
except ImportError:
raise ImportError("pynput dependency is missing... |
48,001 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/keep_lane_agent.py | 5,6 | 4,7 | act | KeepLaneAgent | 6,7 | 6,7 | class KeepLaneAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | class KeepLaneAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | return "keep_lane"
| return "keep_lane"
| 2 | 28 | 10 | 38 | from smarts.core.agent import Agent
class KeepLaneAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | from smarts.core.agent import Agent
class KeepLaneAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY |
48,002 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/keep_left_with_speed_agent.py | 8,9 | 4,10 | act | KeepLeftWithSpeedAgent | 9,10 | 9,10 | class KeepLeftWithSpeedAgent(Agent):
def __init__(self, speed) -> None:
self._speed = speed
def act(self, obs):
FILL_FUNC_BODY | class KeepLeftWithSpeedAgent(Agent):
def __init__(self, speed) -> None:
self._speed = speed
def act(self, obs):
FILL_FUNC_BODY | return self._speed, 0
| return self._speed, 0
| 3 | 51 | 10 | 61 | from smarts.core.agent import Agent
class KeepLeftWithSpeedAgent(Agent):
def __init__(self, speed) -> None:
self._speed = speed
def act(self, obs):
FILL_FUNC_BODY | from smarts.core.agent import Agent
class KeepLeftWithSpeedAgent(Agent):
def __init__(self, speed) -> None:
self._speed = speed
def act(self, obs):
FILL_FUNC_BODY |
48,003 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/primitive_agents.py | 78,79 | 1,99 | trajectory_tracking_entrypoint | 79,87 | 79,87 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | return AgentSpec(
interface=AgentInterface.from_type(
AgentType.Tracker, max_episode_steps=max_episode_steps
),
agent_builder=TrackingAgent,
)
| return AgentSpec(
interface=AgentInterface.from_type(
AgentType.Tracker, max_episode_steps=max_episode_steps
),
agent_builder=TrackingAgent,
)
| 8 | 909 | 64 | 973 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | |
48,004 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/primitive_agents.py | 26,27 | 25,43 | act | ChaseViaPointsAgent | 27,43 | 27,43 | class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODY | class ChaseViaPointsAgent(Agent):
def act(self, obs: Observation):
FILL_FUNC_BODY | if (
len(obs.via_data.near_via_points) < 1
or obs.ego_vehicle_state.road_id != obs.via_data.near_via_points[0].road_id
):
return (obs.waypoint_paths[0][0].speed_limit, 0)
nearest = obs.via_data.near_via_points[0]
if nearest.lane_index == obs.ego_vehic... | if (
len(obs.via_data.near_via_points) < 1
or obs.ego_vehicle_state.road_id != obs.via_data.near_via_points[0].road_id
):
return (obs.waypoint_paths[0][0].speed_limit, 0)
nearest = obs.via_data.near_via_points[0]
if nearest.lane_index == obs.ego_vehic... | 34 | 34 | 207 | 241 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... |
48,005 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/primitive_agents.py | 11,12 | 10,16 | act | RandomLanerAgent | 12,16 | 12,16 | class RandomLanerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | class RandomLanerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | val = ["keep_lane", "slow_down", "change_lane_left", "change_lane_right"]
return random.choice(val)
| val = ["keep_lane", "slow_down", "change_lane_left", "change_lane_right"]
return random.choice(val)
| 8 | 29 | 46 | 75 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODYdef rla_entrypoint(*, max_episode_... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODYdef rla_entrypoint(*, max_episode_... |
48,006 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/primitive_agents.py | 88,89 | 87,92 | act | StandardLaneFollowerAgent | 89,92 | 89,92 | class StandardLaneFollowerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | class StandardLaneFollowerAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | return (obs["waypoint_paths"]["speed_limit"][0][0], 0)
| return (obs["waypoint_paths"]["speed_limit"][0][0], 0)
| 3 | 30 | 29 | 59 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... |
48,007 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/primitive_agents.py | 55,56 | 54,78 | act | TrackingAgent | 56,78 | 56,78 | class TrackingAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | class TrackingAgent(Agent):
def act(self, obs):
FILL_FUNC_BODY | lane_index = 0
num_trajectory_points = min([10, len(obs.waypoint_paths[lane_index])])
# Desired speed is in m/s
desired_speed = 50 / 3.6
trajectory = [
[
obs.waypoint_paths[lane_index][i].pos[0]
for i in range(num_trajectory_points)
... | lane_index = 0
num_trajectory_points = min([10, len(obs.waypoint_paths[lane_index])])
# Desired speed is in m/s
desired_speed = 50 / 3.6
trajectory = [
[
obs.waypoint_paths[lane_index][i].pos[0]
for i in range(num_trajectory_points)
... | 50 | 27 | 238 | 265 | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... | import importlib
import random
from typing import Optional
from smarts.core.agent_interface import AgentInterface, AgentType
from smarts.core.observations import Observation
from smarts.zoo import Agent, AgentSpec
class RandomLanerAgent(Agent):
def act(self, obs):
val = ["keep_lane", "slow_down", "change... |
48,008 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/replay_agent.py | 51,52 | 15,72 | act | ReplayAgent | 52,72 | 52,72 | class ReplayAgent(Agent):
"""A helper agent that wraps another agent to allow replay of the agent inputs and actions
Look at `examples/replay/README.md` on how to use this agent."""
def __init__(self, save_directory, id, read: bool, internal_spec: AgentSpec):
import smarts.core
if smarts.c... | class ReplayAgent(Agent):
"""A helper agent that wraps another agent to allow replay of the agent inputs and actions
Look at `examples/replay/README.md` on how to use this agent."""
def __init__(self, save_directory, id, read: bool, internal_spec: AgentSpec):
import smarts.core
if smarts.c... | if self._read:
base_action = self._base_agent.act(obs)
try:
action = pickle.load(self._file)
assert action == base_action
except AssertionError as e:
self._logger.debug("The Base Agent's action and new action don't match")
... | if self._read:
base_action = self._base_agent.act(obs)
try:
action = pickle.load(self._file)
assert action == base_action
except AssertionError as e:
self._logger.debug("The Base Agent's action and new action don't match")
... | 60 | 404 | 193 | 597 | """
This file contains an agent used for replaying an agent.
"""
import logging
import os
import pickle
from pathlib import Path
from smarts.core.agent import Agent
from smarts.zoo.agent_spec import AgentSpec
agent_index = 0
class ReplayAgent(Agent):
"""A helper agent that wraps another agent to allow replay of... | """
This file contains an agent used for replaying an agent.
"""
import logging
import os
import pickle
from pathlib import Path
from smarts.core.agent import Agent
from smarts.zoo.agent_spec import AgentSpec
agent_index = 0
class ReplayAgent(Agent):
"""A helper agent that wraps another agent to allow replay of... |
48,009 | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS | /home/hieuvd/dung_repo/raw/stars_03/huawei-noah_SMARTS/SMARTS/zoo/policies/waypoint_tracking_agent.py | 10,11 | 6,64 | act | WaypointTrackingAgent | 11,64 | 11,64 | class WaypointTrackingAgent(Agent):
def __init__(self):
self.waypoint_path = []
def act(self, obs):
FILL_FUNC_BODY | class WaypointTrackingAgent(Agent):
def __init__(self):
self.waypoint_path = []
def act(self, obs):
FILL_FUNC_BODY |
current_lane = obs.ego_vehicle_state.lane_index
# Desired speed is in m/s
desired_speed = 10
wp_index = 0
num_lanes = 0
for path in obs.waypoint_paths:
num_lanes = max(num_lanes, path[0].lane_index + 1)
# This is when there are waypoint paths that c... |
current_lane = obs.ego_vehicle_state.lane_index
# Desired speed is in m/s
desired_speed = 10
wp_index = 0
num_lanes = 0
for path in obs.waypoint_paths:
num_lanes = max(num_lanes, path[0].lane_index + 1)
# This is when there are waypoint paths that c... | 155 | 48 | 694 | 742 | from smarts.core.agent import Agent
MIN_WAYPOINTS = 10
class WaypointTrackingAgent(Agent):
def __init__(self):
self.waypoint_path = []
def act(self, obs):
FILL_FUNC_BODY | from smarts.core.agent import Agent
MIN_WAYPOINTS = 10
class WaypointTrackingAgent(Agent):
def __init__(self):
self.waypoint_path = []
def act(self, obs):
FILL_FUNC_BODY |
48,021 | /home/hieuvd/dung_repo/raw/stars_03/hysts_pytorch_image_classification/pytorch_image_classification | /home/hieuvd/dung_repo/raw/stars_03/hysts_pytorch_image_classification/pytorch_image_classification/pytorch_image_classification/utils/metric_logger.py | 5,6 | 1,16 | reset | AverageMeter | 6,11 | 6,11 | class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, num):
self.val = val
self.sum += val * num
self.count += num
self.avg = self.sum / self.count
| class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, num):
self.val = val
self.sum += val * num
self.count += num
self.avg = self.sum / self.count
| self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
| self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
| 12 | 87 | 35 | 122 | class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, num):
self.val = val
self.sum += val * num
self.count += num
self.avg = self.sum / self.count
| class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, num):
self.val = val
self.sum += val * num
self.count += num
self.avg = self.sum / self.count
|
48,314 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/eval/prompt-loop.py | 9,10 | 1,43 | main | 10,31 | 10,31 | import argparse
import sys
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
from tqdm import tqdm
from model_loader import *
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model", type=str, required=Tru... | import argparse
import sys
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
from tqdm import tqdm
from model_loader import *
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model", type=str, required=Tru... | tokenizer = AutoTokenizer.from_pretrained(
args.model, model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
model = load_model_and_apply_patches(args.model, args)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, pad_token_id=tokeni... | tokenizer = AutoTokenizer.from_pretrained(
args.model, model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
model = load_model_and_apply_patches(args.model, args)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, pad_token_id=tokeni... | 56 | 238 | 335 | 573 | import argparse
import sys
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
from tqdm import tqdm
from model_loader import *
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model", type=str, required=Tru... | import argparse
import sys
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
from tqdm import tqdm
from model_loader import *
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model", type=str, required=Tru... | |
48,315 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/paper/mmlu-average.py | 5,6 | 1,14 | main | 6,10 | 6,10 | import argparse
import numpy
import json
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("file", type=str)
main(args.parse_args()) | import argparse
import numpy
import json
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("file", type=str)
main(args.parse_args()) | obj = json.load(open(args.file, "r", encoding="utf-8"))
results = [result["acc"] for result in obj["results"].values()]
print(numpy.average(results))
| obj = json.load(open(args.file, "r", encoding="utf-8"))
results = [result["acc"] for result in obj["results"].values()]
print(numpy.average(results))
| 13 | 72 | 61 | 133 | import argparse
import numpy
import json
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("file", type=str)
main(args.parse_args()) | import argparse
import numpy
import json
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("file", type=str)
main(args.parse_args()) | |
48,316 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/paper/plot.py | 5,6 | 1,33 | main | 6,25 | 6,25 | import argparse
import matplotlib.pyplot as plt
import pandas as pd
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("csv", type=str)
args.add_argument("--xmin", type=int, default=0)
args.add_argument("--xmax", type=int, default=131072)
arg... | import argparse
import matplotlib.pyplot as plt
import pandas as pd
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("csv", type=str)
args.add_argument("--xmin", type=int, default=0)
args.add_argument("--xmax", type=int, default=131072)
arg... | data = pd.read_csv(args.csv)
fig, ax = plt.subplots(figsize=(10,5))
x_data = [float(x) for x in data.columns[1:]]
for row in data.values:
label = row[0].replace("NousResearch/", "")
ax.plot(x_data, [float(x) for x in row[1:]], label=label)
ax.set_xlabel("Context Window")
ax.set... | data = pd.read_csv(args.csv)
fig, ax = plt.subplots(figsize=(10,5))
x_data = [float(x) for x in data.columns[1:]]
for row in data.values:
label = row[0].replace("NousResearch/", "")
ax.plot(x_data, [float(x) for x in row[1:]], label=label)
ax.set_xlabel("Context Window")
ax.set... | 48 | 172 | 250 | 422 | import argparse
import matplotlib.pyplot as plt
import pandas as pd
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("csv", type=str)
args.add_argument("--xmin", type=int, default=0)
args.add_argument("--xmax", type=int, default=131072)
arg... | import argparse
import matplotlib.pyplot as plt
import pandas as pd
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("csv", type=str)
args.add_argument("--xmin", type=int, default=0)
args.add_argument("--xmax", type=int, default=131072)
arg... | |
48,317 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/FalconDynamicPartNTKScaledRotaryEmbedding.py | 12,13 | 1,111 | find_correction_range | 13,17 | 13,17 | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... | low = math.floor(find_correction_factor(low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_factor(high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) #Clamp values just in case
| low = math.floor(find_correction_factor(low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_factor(high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) #Clamp values just in case
| 22 | 1,750 | 90 | 1,840 | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... | |
48,318 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/FalconDynamicPartNTKScaledRotaryEmbedding.py | 55,61 | 28,111 | cos_sin | FalconDynamicPartNTKScaledRotaryEmbedding | 61,107 | 61,107 | class FalconDynamicPartNTKScaledRotaryEmbedding(torch.nn.Module):
"""Implementation of RotaryEmbedding from GPT-NeoX.
This implementation is design to operate on queries and keys that are compatible with
[batch_size, n_heads_per_partition, seq_len, head_dim] (e.g. MinGPTAttention format).
"""
def _... | class FalconDynamicPartNTKScaledRotaryEmbedding(torch.nn.Module):
"""Implementation of RotaryEmbedding from GPT-NeoX.
This implementation is design to operate on queries and keys that are compatible with
[batch_size, n_heads_per_partition, seq_len, head_dim] (e.g. MinGPTAttention format).
"""
def _... | if seq_len != self.seq_len_cached:
self.seq_len_cached = seq_len
if seq_len >= self.max_position_embeddings:
#Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
#Do not change unless there is a good reason for doi... | if seq_len != self.seq_len_cached:
self.seq_len_cached = seq_len
if seq_len >= self.max_position_embeddings:
#Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
#Do not change unless there is a good reason for doi... | 211 | 506 | 901 | 1,407 | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... | import torch
import math
# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
def find_correction_factor(nu... |
48,319 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/GPTNeoXDynamicScaledRotaryEmbedding.py | 19,20 | 3,32 | forward | GPTNeoXDynamicScaledRotaryEmbedding | 20,32 | 20,32 | class GPTNeoXDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, device=None):
super().__init__()
self.max_position_embeddings = max_position_embeddings
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
... | class GPTNeoXDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, device=None):
super().__init__()
self.max_position_embeddings = max_position_embeddings
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | 89 | 358 | 326 | 684 | import torch
class GPTNeoXDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, device=None):
super().__init__()
self.max_position_embeddings = max_position_embeddings
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device)... | import torch
class GPTNeoXDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, device=None):
super().__init__()
self.max_position_embeddings = max_position_embeddings
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device)... |
48,320 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/GPTNeoXNTKScaledRotaryEmbedding.py | 19,20 | 3,31 | forward | GPTNeoXNTKScaledRotaryEmbedding | 20,31 | 20,31 | class GPTNeoXNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.reg... | class GPTNeoXNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.reg... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | 84 | 362 | 307 | 669 | import torch
class GPTNeoXNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
... | import torch
class GPTNeoXNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
... |
48,321 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaDynamicPartNTKScaledRotaryEmbedding.py | 5,6 | 1,118 | find_correction_factor | 6,10 | 6,10 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_factor(
low_rot, dim, base, max_position_embeddings... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_factor(
low_rot, dim, base, max_position_embeddings... | # Inverse dim formula to find number of rotations
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
| # Inverse dim formula to find number of rotations
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
| 19 | 1,839 | 58 | 1,897 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_factor(
low_rot, dim, base, max_position_embeddings... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_factor(
low_rot, dim, base, max_position_embeddings... | |
48,322 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaDynamicPartNTKScaledRotaryEmbedding.py | 81,82 | 31,118 | ntk | LlamaDynamicPartNTKScaledRotaryEmbedding | 82,118 | 82,118 | class LlamaDynamicPartNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, original_max_position_embeddings=2048, base=10000, ntk_factor=1, extrapolation_factor=1, finetuned=False, device=None):
super().__init__()
self.dim = dim
self.base = base
... | class LlamaDynamicPartNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, original_max_position_embeddings=2048, base=10000, ntk_factor=1, extrapolation_factor=1, finetuned=False, device=None):
super().__init__()
self.dim = dim
self.base = base
... |
# Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
# Do not change unless there is a good reason for doing so!
beta_0 = 1.25
beta_1 = 0.75
gamma_0 = 16
gamma_1 = 2
# Three RoPE extrapolation/interpolation methods
... |
# Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
# Do not change unless there is a good reason for doing so!
beta_0 = 1.25
beta_1 = 0.75
gamma_0 = 16
gamma_1 = 2
# Three RoPE extrapolation/interpolation methods
... | 167 | 926 | 630 | 1,556 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
# Inverse dim formula to find number of rotations
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
def find_correction_range(low_rot, high_rot... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
# Inverse dim formula to find number of rotations
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
def find_correction_range(low_rot, high_rot... |
48,323 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaDynamicScaledRotaryEmbedding.py | 24,25 | 4,45 | forward | LlamaDynamicScaledRotaryEmbedding | 25,45 | 25,45 | class LlamaDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, ntk=False, device=None):
super().__init__()
self.ntk = ntk
self.base = base
self.dim = dim
self.max_position_embeddings = max_position_embeddings
... | class LlamaDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, ntk=False, device=None):
super().__init__()
self.ntk = ntk
self.base = base
self.dim = dim
self.max_position_embeddings = max_position_embeddings
... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
if self.ntk:
base = s... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
if self.ntk:
base = s... | 130 | 429 | 517 | 946 | import math
import torch
class LlamaDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, ntk=False, device=None):
super().__init__()
self.ntk = ntk
self.base = base
self.dim = dim
self.max_position_embeddings = max_... | import math
import torch
class LlamaDynamicScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, ntk=False, device=None):
super().__init__()
self.ntk = ntk
self.base = base
self.dim = dim
self.max_position_embeddings = max_... |
48,324 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaDynamicYaRNScaledRotaryEmbedding.py | 9,10 | 1,92 | find_correction_range | 10,16 | 10,16 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | low = math.floor(find_correction_dim(
low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_dim(
high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) # Clamp values just in case
| low = math.floor(find_correction_dim(
low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_dim(
high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) # Clamp values just in case
| 25 | 1,583 | 97 | 1,680 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | |
48,325 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaDynamicYaRNScaledRotaryEmbedding.py | 61,62 | 29,92 | forward | LlamaDynamicYaRNScaledRotaryEmbedding | 62,81 | 62,81 | class LlamaDynamicYaRNScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
super().__init__()
self.dim = dim
... | class LlamaDynamicYaRNScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
super().__init__()
self.dim = dim
... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
self.yarn(seq_len / self.original_ma... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
self.yarn(seq_len / self.original_ma... | 98 | 897 | 412 | 1,309 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... |
48,326 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaLinearScaledRotaryEmbedding.py | 21,22 | 3,37 | forward | LlamaLinearScaledRotaryEmbedding | 22,37 | 22,37 | class LlamaLinearScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, device=None):
super().__init__()
self.scale = scale
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.register_buffer("... | class LlamaLinearScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, device=None):
super().__init__()
self.scale = scale
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.register_buffer("... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | 93 | 403 | 373 | 776 | import torch
class LlamaLinearScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, device=None):
super().__init__()
self.scale = scale
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.reg... | import torch
class LlamaLinearScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, device=None):
super().__init__()
self.scale = scale
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.reg... |
48,327 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaNTKScaledRotaryEmbedding.py | 20,21 | 3,35 | forward | LlamaNTKScaledRotaryEmbedding | 21,35 | 21,35 | class LlamaNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.... | class LlamaNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
self.... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | 90 | 405 | 364 | 769 | import torch
class LlamaNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))... | import torch
class LlamaNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, alpha=1, device=None):
super().__init__()
base = base * alpha ** (dim / (dim-2))
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))... |
48,328 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaPartNTKScaledRotaryEmbedding.py | 7,8 | 1,79 | find_correction_range | 8,12 | 8,12 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... | low = math.floor(find_correction_factor(low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_factor(high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) #Clamp values just in case
| low = math.floor(find_correction_factor(low_rot, dim, base, max_position_embeddings))
high = math.ceil(find_correction_factor(high_rot, dim, base, max_position_embeddings))
return max(low, 0), min(high, dim-1) #Clamp values just in case
| 22 | 1,529 | 90 | 1,619 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... | |
48,329 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaPartNTKScaledRotaryEmbedding.py | 64,65 | 23,79 | forward | LlamaPartNTKScaledRotaryEmbedding | 65,79 | 65,79 | class LlamaPartNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, ntk_factor=1, extrapolation_factor=1, original_max_position_embeddings=2048, device=None):
super().__init__()
#Interpolation constants found experimentally fo... | class LlamaPartNTKScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, ntk_factor=1, extrapolation_factor=1, original_max_position_embeddings=2048, device=None):
super().__init__()
#Interpolation constants found experimentally fo... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cac... | 90 | 904 | 365 | 1,269 | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... | import torch
import math
def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
def find_correction_range(low_rot, high_rot, dim, ... |
48,331 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaYaRNScaledRotaryEmbedding.py | 5,6 | 1,85 | find_correction_dim | 6,9 | 6,9 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_... | return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotations
| return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotations
| 18 | 1,511 | 53 | 1,564 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
FILL_FUNC_BODYdef find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
low = math.floor(find_correction_... | |
48,332 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/LlamaYaRNScaledRotaryEmbedding.py | 56,57 | 29,85 | forward | LlamaYaRNScaledRotaryEmbedding | 57,74 | 57,74 | class LlamaYaRNScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
super().__init__()
self.dim = dim... | class LlamaYaRNScaledRotaryEmbedding(torch.nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
super().__init__()
self.dim = dim... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_ca... | # x: [bs, num_attention_heads, seq_len, head_size]
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
if seq_len > self.max_seq_len_cached:
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_ca... | 94 | 811 | 383 | 1,194 | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... | import torch
import math
# Inverse dim formula to find dim based on number of rotations
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
# Find dim range bounds based on rotati... |
48,339 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 591,601 | 582,648 | forward | LlamaDecoderLayer | 614,648 | 601,648 | class LlamaDecoderLayer(nn.Module):
def __init__(self, config: LlamaConfig):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = LlamaAttention(config=config)
self.mlp = LlamaMLP(config)
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.... | class LlamaDecoderLayer(nn.Module):
def __init__(self, config: LlamaConfig):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = LlamaAttention(config=config)
self.mlp = LlamaMLP(config)
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.... |
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids... | """
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large nega... | 59 | 554 | 315 | 869 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,341 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 1098,1112 | 1067,1185 | forward | LlamaForSequenceClassification | 1112,1185 | 1112,1185 | @add_start_docstrings(
"""
The LLaMa Model transformer with a sequence classification head on top (linear layer).
[`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
(e.g. GPT-2) do.
Since it does classification on the last token, it req... | @add_start_docstrings(
"""
The LLaMa Model transformer with a sequence classification head on top (linear layer).
[`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
(e.g. GPT-2) do.
Since it does classification on the last token, it req... | r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
... | r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
... | 246 | 608 | 1,034 | 1,642 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,342 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 384,385 | 373,406 | forward | LlamaMLP | 385,406 | 385,406 | class LlamaMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self... | class LlamaMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self... | if self.config.pretraining_tp > 1:
slice = self.intermediate_size // self.config.pretraining_tp
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
down_proj_slices = self.down_proj.weight.split(sli... | if self.config.pretraining_tp > 1:
slice = self.intermediate_size // self.config.pretraining_tp
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
down_proj_slices = self.down_proj.weight.split(sli... | 68 | 192 | 374 | 566 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,343 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 787,801 | 756,904 | forward | LlamaModel | 801,904 | 801,904 | @add_start_docstrings(
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
LLAMA_START_DOCSTRING,
)
class LlamaModel(LlamaPreTrainedModel):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
Args:
... | @add_start_docstrings(
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
LLAMA_START_DOCSTRING,
)
class LlamaModel(LlamaPreTrainedModel):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
Args:
... | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None e... | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None e... | 298 | 575 | 1,199 | 1,774 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,344 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 676,677 | 665,692 | _init_weights | LlamaPreTrainedModel | 677,687 | 677,687 | @add_start_docstrings(
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
LLAMA_START_DOCSTRING,
)
class LlamaPreTrainedModel(PreTrainedModel):
config_class = LlamaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["... | @add_start_docstrings(
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
LLAMA_START_DOCSTRING,
)
class LlamaPreTrainedModel(PreTrainedModel):
config_class = LlamaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["... | std = self.config.initializer_range
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0,... | std = self.config.initializer_range
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0,... | 25 | 194 | 143 | 337 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,345 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/modeling_llama_together_yarn.py | 87,88 | 74,92 | forward | LlamaRMSNorm | 88,92 | 88,92 | class LlamaRMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
LlamaRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.register_buffer(
"variance_epsilon",
torch.t... | class LlamaRMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
LlamaRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.register_buffer(
"variance_epsilon",
torch.t... | return rmsnorm_func(hidden_states, self.weight, self.variance_epsilon)
# Inverse dim formula to find dim based on number of rotations
| return rmsnorm_func(hidden_states, self.weight, self.variance_epsilon)
# Inverse dim formula to find dim based on number of rotations
| 16 | 137 | 45 | 182 | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... |
48,346 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/scaled_rope/patch.py | 73,74 | 1,82 | patch_llama_for_rerope | 74,82 | 74,82 | import torch
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(
each.self_attn.head_dim, device=eac... | import torch
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(
each.self_attn.head_dim, device=eac... | from .LlamaReRoPE import forward_with_rerope
for each in model.model.layers:
def forward(*args, **kwargs):
return forward_with_rerope(each.self_attn, *args, **kwargs)
each.self_attn.training_length = int(training_length)
each.self_attn.window = int(window)
# each.sel... | from .LlamaReRoPE import forward_with_rerope
for each in model.model.layers:
def forward(*args, **kwargs):
return forward_with_rerope(each.self_attn, *args, **kwargs)
each.self_attn.training_length = int(training_length)
each.self_attn.window = int(window)
# each.sel... | 25 | 1,539 | 118 | 1,657 | import torch
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(
each.self_attn.head_dim, device=eac... | import torch
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(
each.self_attn.head_dim, device=eac... | |
48,347 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/tokenization.py | 9,10 | 1,89 | main | 10,75 | 10,75 | from itertools import chain
from functools import reduce
import multiprocessing
import argparse
from typing import List
from datasets import concatenate_datasets, load_dataset, load_from_disk
from transformers import AutoTokenizer
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentP... | from itertools import chain
from functools import reduce
import multiprocessing
import argparse
from typing import List
from datasets import concatenate_datasets, load_dataset, load_from_disk
from transformers import AutoTokenizer
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentP... | if args.dataset is None or len(args.dataset[0]) == 0:
raise RuntimeError("No datasets provided")
datasets = args.dataset[0]
splits = [x.split(",")[1] if len(x.split(",")) == 2 else "" for x in datasets]
datasets = [x.split(",")[0] for x in datasets]
tokenizer = AutoTokenizer.from_pretraine... | if args.dataset is None or len(args.dataset[0]) == 0:
raise RuntimeError("No datasets provided")
datasets = args.dataset[0]
splits = [x.split(",")[1] if len(x.split(",")) == 2 else "" for x in datasets]
datasets = [x.split(",")[0] for x in datasets]
tokenizer = AutoTokenizer.from_pretraine... | 255 | 326 | 894 | 1,220 | from itertools import chain
from functools import reduce
import multiprocessing
import argparse
from typing import List
from datasets import concatenate_datasets, load_dataset, load_from_disk
from transformers import AutoTokenizer
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentP... | from itertools import chain
from functools import reduce
import multiprocessing
import argparse
from typing import List
from datasets import concatenate_datasets, load_dataset, load_from_disk
from transformers import AutoTokenizer
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentP... | |
48,348 | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn | /home/hieuvd/dung_repo/raw/stars_03/jquesnelle_yarn/yarn/truncate.py | 4,5 | 1,23 | main | 5,15 | 5,15 | import argparse
from datasets import load_dataset
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("truncate", type=int)
args.add_argument("output", type=str)
args.add_argument("--num-proc", type=int, default=32)
args.add_argument("--datase... | import argparse
from datasets import load_dataset
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("truncate", type=int)
args.add_argument("output", type=str)
args.add_argument("--num-proc", type=int, default=32)
args.add_argument("--datase... | dataset = load_dataset(args.dataset, split="train")
def truncate(sample):
sample["input_ids"] = sample["input_ids"][0:args.truncate]
sample["labels"] = sample["labels"][0:args.truncate]
sample["attention_mask"] = sample["attention_mask"][0:args.truncate]
return sample
dataset... | dataset = load_dataset(args.dataset, split="train")
def truncate(sample):
sample["input_ids"] = sample["input_ids"][0:args.truncate]
sample["labels"] = sample["labels"][0:args.truncate]
sample["attention_mask"] = sample["attention_mask"][0:args.truncate]
return sample
dataset... | 23 | 157 | 152 | 309 | import argparse
from datasets import load_dataset
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("truncate", type=int)
args.add_argument("output", type=str)
args.add_argument("--num-proc", type=int, default=32)
args.add_argument("--datase... | import argparse
from datasets import load_dataset
def main(args):
FILL_FUNC_BODYif __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("truncate", type=int)
args.add_argument("output", type=str)
args.add_argument("--num-proc", type=int, default=32)
args.add_argument("--datase... | |
48,515 | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py/kartograph/geometry/point.py | 10,11 | 3,33 | project | Point | 11,15 | 11,15 | class Point():
""" base class for points, used by line and bbox """
def __init__(self, x, y):
self.x = x
self.y = y
def project(self, proj):
FILL_FUNC_BODY """emulate python's container types"""
def __len__(self):
return 2
def __getitem__(self, k):
pt = (self.x,... | class Point():
""" base class for points, used by line and bbox """
def __init__(self, x, y):
self.x = x
self.y = y
def project(self, proj):
FILL_FUNC_BODY """emulate python's container types"""
def __len__(self):
return 2
def __getitem__(self, k):
pt = (self.x,... | (x, y) = proj.project(self.x, self.y)
self.x = x
self.y = y
| (x, y) = proj.project(self.x, self.y)
self.x = x
self.y = y
| 11 | 200 | 40 | 240 |
class Point():
""" base class for points, used by line and bbox """
def __init__(self, x, y):
self.x = x
self.y = y
def project(self, proj):
FILL_FUNC_BODY """emulate python's container types"""
def __len__(self):
return 2
def __getitem__(self, k):
pt = (self.... |
class Point():
""" base class for points, used by line and bbox """
def __init__(self, x, y):
self.x = x
self.y = y
def project(self, proj):
FILL_FUNC_BODY """emulate python's container types"""
def __len__(self):
return 2
def __getitem__(self, k):
pt = (self.... |
48,516 | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py/kartograph/layersource/layersource.py | 14,15 | 7,27 | find_source | LayerSource | 15,27 | 15,27 | class LayerSource:
"""
base class for layer source data providers (e.g. shapefiles)
"""
def get_features(self, filter=None, bbox=None, ignore_holes=False, charset='utf-8'):
raise NotImplementedError()
def find_source(self, src):
FILL_FUNC_BODY | class LayerSource:
"""
base class for layer source data providers (e.g. shapefiles)
"""
def get_features(self, filter=None, bbox=None, ignore_holes=False, charset='utf-8'):
raise NotImplementedError()
def find_source(self, src):
FILL_FUNC_BODY | if not os.path.exists(src) and 'KARTOGRAPH_DATA' in os.environ:
# try
paths = os.environ['KARTOGRAPH_DATA'].split(os.pathsep)
for path in paths:
if path[:-1] != os.sep and src[0] != os.sep:
path = path + os.sep
if os.path.ex... | if not os.path.exists(src) and 'KARTOGRAPH_DATA' in os.environ:
# try
paths = os.environ['KARTOGRAPH_DATA'].split(os.pathsep)
for path in paths:
if path[:-1] != os.sep and src[0] != os.sep:
path = path + os.sep
if os.path.ex... | 52 | 94 | 168 | 262 |
import os.path
import os
from kartograph.errors import *
class LayerSource:
"""
base class for layer source data providers (e.g. shapefiles)
"""
def get_features(self, filter=None, bbox=None, ignore_holes=False, charset='utf-8'):
raise NotImplementedError()
def find_source(self, src):
FI... |
import os.path
import os
from kartograph.errors import *
class LayerSource:
"""
base class for layer source data providers (e.g. shapefiles)
"""
def get_features(self, filter=None, bbox=None, ignore_holes=False, charset='utf-8'):
raise NotImplementedError()
def find_source(self, src):
FI... |
48,517 | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py/kartograph/simplify/distance.py | 3,4 | 1,44 | simplify_distance | 12,44 | 4,44 |
def simplify_distance(points, dist):
FILL_FUNC_BODY |
def simplify_distance(points, dist):
"""
simplifies a line segment using a very simple algorithm that checks the distance
to the last non-deleted point. the algorithm operates on line segments.
in order to preserve topology of the original polygons the algorithm
- never removes the first or the l... | dist_sq = dist * dist
n = len(points)
kept = []
deleted = 0
if n < 4:
return points
for i in range(0, n):
pt = points[i]
if i == 0 or i == n - 1:
# never remove first or last point of line
pt.simplified = True
lpt = pt
kep... | """
simplifies a line segment using a very simple algorithm that checks the distance
to the last non-deleted point. the algorithm operates on line segments.
in order to preserve topology of the original polygons the algorithm
- never removes the first or the last point of a line segment
- flags... | 138 | 112 | 340 | 452 |
def simplify_distance(points, dist):
FILL_FUNC_BODY |
def simplify_distance(points, dist):
"""
simplifies a line segment using a very simple algorithm that checks the distance
to the last non-deleted point. the algorithm operates on line segments.
in order to preserve topology of the original polygons the algorithm
- never removes the first or the l... | |
48,518 | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py/kartograph/simplify/douglas_peucker.py | 55,56 | 1,73 | _min_distance | 60,67 | 56,67 |
def simplify_douglas_peucker(points, epsilon):
"""
simplifies a line segment using the Douglas-Peucker algorithm.
taken from
http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm#Pseudocode
in order to preserve topology of the original polygons the algorithm
- never re... |
def simplify_douglas_peucker(points, epsilon):
"""
simplifies a line segment using the Douglas-Peucker algorithm.
taken from
http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm#Pseudocode
in order to preserve topology of the original polygons the algorithm
- never re... | d = _dist(x1, y1, x2, y2)
u = (x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1) / (d * d)
x = x1 + u * (x2 - x1)
y = y1 + u * (y2 - y1)
return _dist(x, y, x3, y3)
| """
the perpendicular distance from a point (x3,y3) to the line from (x1,y1) to (x2,y2)
taken from http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
"""
d = _dist(x1, y1, x2, y2)
u = (x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1) / (d * d)
x = x1 + u * (x2 - x1)
y = y1 + u * (y2 -... | 50 | 705 | 117 | 822 |
def simplify_douglas_peucker(points, epsilon):
"""
simplifies a line segment using the Douglas-Peucker algorithm.
taken from
http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm#Pseudocode
in order to preserve topology of the original polygons the algorithm
- never re... |
def simplify_douglas_peucker(points, epsilon):
"""
simplifies a line segment using the Douglas-Peucker algorithm.
taken from
http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm#Pseudocode
in order to preserve topology of the original polygons the algorithm
- never re... | |
48,519 | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py | /home/hieuvd/dung_repo/raw/stars_03/kartograph_kartograph.py/kartograph.py/kartograph/simplify/visvalingam.py | 3,4 | 1,78 | simplify_visvalingam_whyatt | 8,71 | 4,71 |
def simplify_visvalingam_whyatt(points, tolerance):
FILL_FUNC_BODYdef _tri_area(x1, y1, x2, y2, x3, y3):
"""
computes the area of a triangle given by three points
implementation taken from:
http://www.btinternet.com/~se16/hgb/triangle.htm
"""
return abs((x2*y1-x1*y2)+(x3*y2-x2*y3)+(x1*y3-x3*y1... |
def simplify_visvalingam_whyatt(points, tolerance):
""" Visvalingam-Whyatt simplification
implementation borrowed from @migurski:
https://github.com/migurski/Bloch/blob/master/Bloch/__init__.py#L133
"""
FILL_FUNC_BODYdef _tri_area(x1, y1, x2, y2, x3, y3):
"""
computes the area of a triangle gi... | if len(points) < 3:
return
if points[1].simplified:
return
min_area = tolerance ** 2
pts = range(len(points)) # pts stores an index of all non-deleted points
while len(pts) > 4:
preserved, popped = set(), []
areas = []
for i in range(1, len(pts) - 1):
... | """ Visvalingam-Whyatt simplification
implementation borrowed from @migurski:
https://github.com/migurski/Bloch/blob/master/Bloch/__init__.py#L133
"""
if len(points) < 3:
return
if points[1].simplified:
return
min_area = tolerance ** 2
pts = range(len(points)) # pts st... | 235 | 213 | 601 | 814 |
def simplify_visvalingam_whyatt(points, tolerance):
FILL_FUNC_BODYdef _tri_area(x1, y1, x2, y2, x3, y3):
"""
computes the area of a triangle given by three points
implementation taken from:
http://www.btinternet.com/~se16/hgb/triangle.htm
"""
return abs((x2*y1-x1*y2)+(x3*y2-x2*y3)+(x1*y3-x3*y1... |
def simplify_visvalingam_whyatt(points, tolerance):
""" Visvalingam-Whyatt simplification
implementation borrowed from @migurski:
https://github.com/migurski/Bloch/blob/master/Bloch/__init__.py#L133
"""
FILL_FUNC_BODYdef _tri_area(x1, y1, x2, y2, x3, y3):
"""
computes the area of a triangle gi... | |
48,544 | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit/setup.py | 44,45 | 1,114 | create_readme | 45,73 | 45,73 | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2019/12/15
"""
语音处理工具箱。
生成whl格式安装包:python setup.py bdist_wheel
直接上传pypi:python setup.py sdist upload
用twine上传pypi:
生成安装包:python setup.py sdist
上传安装包:twine upload [package path]
注意:需要在home目录下建立.pypirc配置文件,文件内容格式:
[distutils]
index-servers=pypi
[p... | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2019/12/15
"""
语音处理工具箱。
生成whl格式安装包:python setup.py bdist_wheel
直接上传pypi:python setup.py sdist upload
用twine上传pypi:
生成安装包:python setup.py sdist
上传安装包:twine upload [package path]
注意:需要在home目录下建立.pypirc配置文件,文件内容格式:
[distutils]
index-servers=pypi
[p... | from ttskit import sdk_api
from ttskit import cli_api
from ttskit import web_api
from ttskit import http_server
from ttskit import encoder
from ttskit import mellotron
from ttskit import waveglow
from ttskit import melgan
from ttskit import resource
import ttskit
version_doc ... | from ttskit import sdk_api
from ttskit import cli_api
from ttskit import web_api
from ttskit import http_server
from ttskit import encoder
from ttskit import mellotron
from ttskit import waveglow
from ttskit import melgan
from ttskit import resource
import ttskit
version_doc ... | 78 | 1,027 | 316 | 1,343 | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2019/12/15
"""
语音处理工具箱。
生成whl格式安装包:python setup.py bdist_wheel
直接上传pypi:python setup.py sdist upload
用twine上传pypi:
生成安装包:python setup.py sdist
上传安装包:twine upload [package path]
注意:需要在home目录下建立.pypirc配置文件,文件内容格式:
[distutils]
index-servers=pypi
[p... | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2019/12/15
"""
语音处理工具箱。
生成whl格式安装包:python setup.py bdist_wheel
直接上传pypi:python setup.py sdist upload
用twine上传pypi:
生成安装包:python setup.py sdist
上传安装包:twine upload [package path]
注意:需要在home目录下建立.pypirc配置文件,文件内容格式:
[distutils]
index-servers=pypi
[p... | |
48,545 | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit/test.py | 15,16 | 1,82 | test_sdk_api | 16,28 | 16,28 | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/2/23
"""
test
"""
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(Path(__file__).stem)
def test_sdk_api():
FILL_FUNC_BODYdef test_cli_api():
from ttskit import cli_api
args ... | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/2/23
"""
test
"""
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(Path(__file__).stem)
def test_sdk_api():
FILL_FUNC_BODYdef test_cli_api():
from ttskit import cli_api
args ... | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '_'
from ttskit import sdk_api
text = '初始化。'
wav = sdk_api.tts_sdk(text, speaker='biaobei', audio='24', processes=0)
text = '欢迎使用语音合成工具箱这是二十个字的文本。' * 5
wav = sdk_api.tts_sdk(text, speaker='biaobei', audio='24', processes=0)
| import os
os.environ['CUDA_VISIBLE_DEVICES'] = '_'
from ttskit import sdk_api
text = '初始化。'
wav = sdk_api.tts_sdk(text, speaker='biaobei', audio='24', processes=0)
text = '欢迎使用语音合成工具箱这是二十个字的文本。' * 5
wav = sdk_api.tts_sdk(text, speaker='biaobei', audio='24', processes=0)
| 29 | 690 | 159 | 849 | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/2/23
"""
test
"""
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(Path(__file__).stem)
def test_sdk_api():
FILL_FUNC_BODYdef test_cli_api():
from ttskit import cli_api
args ... | #!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/2/23
"""
test
"""
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(Path(__file__).stem)
def test_sdk_api():
FILL_FUNC_BODYdef test_cli_api():
from ttskit import cli_api
args ... | |
48,546 | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit/ttskit/encoder/data_objects/random_cycler.py | 18,19 | 3,38 | sample | RandomCycler | 19,35 | 19,35 | class RandomCycler:
"""
Creates an internal copy of a sequence and allows access to its items in a constrained random
order. For a source sequence of n items and one or several consecutive queries of a total
of m items, the following guarantees hold (one implies the other):
- Each item will be... | class RandomCycler:
"""
Creates an internal copy of a sequence and allows access to its items in a constrained random
order. For a source sequence of n items and one or several consecutive queries of a total
of m items, the following guarantees hold (one implies the other):
- Each item will be... | shuffle = lambda l: random.sample(l, len(l))
out = []
while count > 0:
if count >= len(self.all_items):
out.extend(shuffle(list(self.all_items)))
count -= len(self.all_items)
continue
n = min(count, len(self.next_it... | shuffle = lambda l: random.sample(l, len(l))
out = []
while count > 0:
if count >= len(self.all_items):
out.extend(shuffle(list(self.all_items)))
count -= len(self.all_items)
continue
n = min(count, len(self.next_it... | 42 | 230 | 186 | 416 | import random
class RandomCycler:
"""
Creates an internal copy of a sequence and allows access to its items in a constrained random
order. For a source sequence of n items and one or several consecutive queries of a total
of m items, the following guarantees hold (one implies the other):
- Ea... | import random
class RandomCycler:
"""
Creates an internal copy of a sequence and allows access to its items in a constrained random
order. For a source sequence of n items and one or several consecutive queries of a total
of m items, the following guarantees hold (one implies the other):
- Ea... |
48,547 | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit/ttskit/mellotron/text/cmudict.py | 45,46 | 1,66 | _parse_cmudict | 46,60 | 46,60 | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... | cmudict = {}
for line in file:
if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"):
parts = line.split(' ')
word = re.sub(_alt_re, '', parts[0])
pronunciation = _get_pronunciation(parts[1])
if pronunciation:
if word in cmudict:
cmudict[word].append(p... | cmudict = {}
for line in file:
if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"):
parts = line.split(' ')
word = re.sub(_alt_re, '', parts[0])
pronunciation = _get_pronunciation(parts[1])
if pronunciation:
if word in cmudict:
cmudict[word].append(p... | 46 | 738 | 162 | 900 | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... | |
48,548 | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit | /home/hieuvd/dung_repo/raw/stars_03/kuangdd_ttskit/ttskit/ttskit/mellotron/text/cmudict.py | 36,37 | 19,42 | lookup | CMUDict | 38,42 | 37,42 | class CMUDict:
'''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict'''
def __init__(self, file_or_path, keep_ambiguous=True):
if isinstance(file_or_path, str):
with open(file_or_path, encoding='latin-1') as f:
entries = _parse_cmudict(f)
else:
entries = _pars... | class CMUDict:
'''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict'''
def __init__(self, file_or_path, keep_ambiguous=True):
if isinstance(file_or_path, str):
with open(file_or_path, encoding='latin-1') as f:
entries = _parse_cmudict(f)
else:
entries = _pars... | return self._entries.get(word.upper())
| '''Returns list of ARPAbet pronunciations of the given word.'''
return self._entries.get(word.upper())
| 2 | 239 | 21 | 260 | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... | """ from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E... |
48,660 | /home/hieuvd/dung_repo/raw/stars_03/linouk23_youtube_uploader_selenium/youtube_uploader_selenium | /home/hieuvd/dung_repo/raw/stars_03/linouk23_youtube_uploader_selenium/youtube_uploader_selenium/upload.py | 6,10 | 1,28 | main | 10,15 | 10,15 | import argparse
from youtube_uploader_selenium import YouTubeUploader
from typing import Optional
def main(video_path: str,
metadata_path: Optional[str] = None,
thumbnail_path: Optional[str] = None,
profile_path: Optional[str] = None):
FILL_FUNC_BODYif __name__ == "__main__":
parser = a... | import argparse
from youtube_uploader_selenium import YouTubeUploader
from typing import Optional
def main(video_path: str,
metadata_path: Optional[str] = None,
thumbnail_path: Optional[str] = None,
profile_path: Optional[str] = None):
FILL_FUNC_BODYif __name__ == "__main__":
parser = a... | uploader = YouTubeUploader(video_path, metadata_path, thumbnail_path, profile_path)
was_video_uploaded, video_id = uploader.upload()
assert was_video_uploaded
| uploader = YouTubeUploader(video_path, metadata_path, thumbnail_path, profile_path)
was_video_uploaded, video_id = uploader.upload()
assert was_video_uploaded
| 12 | 245 | 60 | 305 | import argparse
from youtube_uploader_selenium import YouTubeUploader
from typing import Optional
def main(video_path: str,
metadata_path: Optional[str] = None,
thumbnail_path: Optional[str] = None,
profile_path: Optional[str] = None):
FILL_FUNC_BODYif __name__ == "__main__":
parser = a... | import argparse
from youtube_uploader_selenium import YouTubeUploader
from typing import Optional
def main(video_path: str,
metadata_path: Optional[str] = None,
thumbnail_path: Optional[str] = None,
profile_path: Optional[str] = None):
FILL_FUNC_BODYif __name__ == "__main__":
parser = a... | |
48,740 | /home/hieuvd/dung_repo/raw/stars_03/m1guelpf_yt-whisper/yt-whisper | /home/hieuvd/dung_repo/raw/stars_03/m1guelpf_yt-whisper/yt-whisper/yt_whisper/cli.py | 11,12 | 1,91 | main | 12,66 | 12,66 | import os
import whisper
from whisper.tokenizer import LANGUAGES, TO_LANGUAGE_CODE
import argparse
import warnings
import yt_dlp
from .utils import slugify, str2bool, write_srt, write_vtt
import tempfile
def main():
FILL_FUNC_BODYdef get_audio(urls):
temp_dir = tempfile.gettempdir()
ydl = yt_dlp.YoutubeDL({
... | import os
import whisper
from whisper.tokenizer import LANGUAGES, TO_LANGUAGE_CODE
import argparse
import warnings
import yt_dlp
from .utils import slugify, str2bool, write_srt, write_vtt
import tempfile
def main():
FILL_FUNC_BODYdef get_audio(urls):
temp_dir = tempfile.gettempdir()
ydl = yt_dlp.YoutubeDL({
... | parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("video", nargs="+", type=str,
help="video URLs to transcribe")
parser.add_argument("--model", default="small",
choices=whisper.available_model... | parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("video", nargs="+", type=str,
help="video URLs to transcribe")
parser.add_argument("--model", default="small",
choices=whisper.available_model... | 200 | 331 | 906 | 1,237 | import os
import whisper
from whisper.tokenizer import LANGUAGES, TO_LANGUAGE_CODE
import argparse
import warnings
import yt_dlp
from .utils import slugify, str2bool, write_srt, write_vtt
import tempfile
def main():
FILL_FUNC_BODYdef get_audio(urls):
temp_dir = tempfile.gettempdir()
ydl = yt_dlp.YoutubeDL({
... | import os
import whisper
from whisper.tokenizer import LANGUAGES, TO_LANGUAGE_CODE
import argparse
import warnings
import yt_dlp
from .utils import slugify, str2bool, write_srt, write_vtt
import tempfile
def main():
FILL_FUNC_BODYdef get_audio(urls):
temp_dir = tempfile.gettempdir()
ydl = yt_dlp.YoutubeDL({
... | |
48,741 | /home/hieuvd/dung_repo/raw/stars_03/m1guelpf_yt-whisper/yt-whisper | /home/hieuvd/dung_repo/raw/stars_03/m1guelpf_yt-whisper/yt-whisper/yt_whisper/utils.py | 29,30 | 1,82 | break_line | 30,45 | 30,45 | from typing import Iterator, TextIO
def str2bool(string):
str2val = {"True": True, "False": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(
f"Expected one of {set(str2val.keys())}, got {string}")
def format_timestamp(seconds: float, always_include_... | from typing import Iterator, TextIO
def str2bool(string):
str2val = {"True": True, "False": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(
f"Expected one of {set(str2val.keys())}, got {string}")
def format_timestamp(seconds: float, always_include_... | break_index = min(len(line)//2, length) # split evenly or at maximum length
# work backwards from that guess to split between words
# if break_index <= 1, we've hit the beginning of the string and can't split
while break_index > 1:
if line[break_index - 1] == " ":
break # break at s... | break_index = min(len(line)//2, length) # split evenly or at maximum length
# work backwards from that guess to split between words
# if break_index <= 1, we've hit the beginning of the string and can't split
while break_index > 1:
if line[break_index - 1] == " ":
break # break at s... | 81 | 802 | 177 | 979 | from typing import Iterator, TextIO
def str2bool(string):
str2val = {"True": True, "False": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(
f"Expected one of {set(str2val.keys())}, got {string}")
def format_timestamp(seconds: float, always_include_... | from typing import Iterator, TextIO
def str2bool(string):
str2val = {"True": True, "False": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(
f"Expected one of {set(str2val.keys())}, got {string}")
def format_timestamp(seconds: float, always_include_... | |
48,742 | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked/crosslinked/logger.py | 52,53 | 1,94 | setup_debug_logger | 53,65 | 53,65 | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... | debug_output_string = "{} %(message)s".format(highlight('DEBUG', fg='purple'))
formatter = logging.Formatter(debug_output_string)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(formatter)
root_logger = logging.getLogger()
root_logger.propagate = False
root_logg... | debug_output_string = "{} %(message)s".format(highlight('DEBUG', fg='purple'))
formatter = logging.Formatter(debug_output_string)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(formatter)
root_logger = logging.getLogger()
root_logger.propagate = False
root_logg... | 22 | 756 | 140 | 896 | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... | |
48,743 | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked/crosslinked/logger.py | 34,36 | 20,39 | fail | Log | 36,39 | 36,39 | class Log:
# Quick log class for CLI output
@staticmethod
def info(msg):
print(' '.join([highlight('[*]', 'bold', 'blue'), msg]))
@staticmethod
def success(msg):
print(' '.join([highlight('[+]', 'bold', 'green'), msg]))
@staticmethod
def warn(msg):
print(' '.join([h... | class Log:
# Quick log class for CLI output
@staticmethod
def info(msg):
print(' '.join([highlight('[*]', 'bold', 'blue'), msg]))
@staticmethod
def success(msg):
print(' '.join([highlight('[+]', 'bold', 'green'), msg]))
@staticmethod
def warn(msg):
print(' '.join([h... | print(' '.join([highlight('[-]', 'bold', 'red'), msg]))
| print(' '.join([highlight('[-]', 'bold', 'red'), msg]))
| 5 | 137 | 25 | 162 | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... | import os
import sys
import logging
STYLE = {'None': '0',
'bold': '1'
}
FG = {'None': '',
'gray': ';30',
'red': ';31',
'green': ';32',
'yellow': ';33',
'blue': ';34',
'purple': ';35',
'cyan': ';36'
}
class Log:
# Quick log class for CLI output
... |
48,745 | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked/crosslinked/search.py | 94,95 | 40,133 | parse_linkedin_title | CrossLinked | 95,101 | 95,101 | class CrossLinked:
def __init__(self, search_engine, target, timeout, conn_timeout=3, proxies=[], jitter=0):
self.results = []
self.url = {'google': 'https://www.google.com/search?q=site:linkedin.com/in+"{}"&num=100&start={}',
'bing': 'http://www.bing.com/search?q="{}"+site:linke... | class CrossLinked:
def __init__(self, search_engine, target, timeout, conn_timeout=3, proxies=[], jitter=0):
self.results = []
self.url = {'google': 'https://www.google.com/search?q=site:linkedin.com/in+"{}"&num=100&start={}',
'bing': 'http://www.bing.com/search?q="{}"+site:linke... | try:
title = data.split("-")[1].split('https:')[0]
return title.split("...")[0].split("|")[0].strip()
except:
return 'N/A'
| try:
title = data.split("-")[1].split('https:')[0]
return title.split("...")[0].split("|")[0].strip()
except:
return 'N/A'
| 9 | 1,043 | 64 | 1,107 | import logging
import requests
import threading
from time import sleep
from random import choice
from bs4 import BeautifulSoup
from unidecode import unidecode
from urllib.parse import urlparse
from crosslinked.logger import Log
from datetime import datetime, timedelta
from urllib3 import disable_warnings, exceptions
d... | import logging
import requests
import threading
from time import sleep
from random import choice
from bs4 import BeautifulSoup
from unidecode import unidecode
from urllib.parse import urlparse
from crosslinked.logger import Log
from datetime import datetime, timedelta
from urllib3 import disable_warnings, exceptions
d... |
48,746 | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked/crosslinked/search.py | 25,26 | 18,40 | run | Timer | 26,35 | 26,35 | class Timer(threading.Thread):
def __init__(self, timeout):
threading.Thread.__init__(self)
self.start_time = None
self.running = None
self.timeout = timeout
def run(self):
FILL_FUNC_BODY def stop(self):
logging.debug("Thread Timer: Stopped")
self.running = Fa... | class Timer(threading.Thread):
def __init__(self, timeout):
threading.Thread.__init__(self)
self.start_time = None
self.running = None
self.timeout = timeout
def run(self):
FILL_FUNC_BODY def stop(self):
logging.debug("Thread Timer: Stopped")
self.running = Fa... | self.running = True
self.start_time = datetime.now()
logging.debug("Thread Timer: Started")
while self.running:
if (datetime.now() - self.start_time) > timedelta(seconds=self.timeout):
self.stop()
sleep(0.05)
| self.running = True
self.start_time = datetime.now()
logging.debug("Thread Timer: Started")
while self.running:
if (datetime.now() - self.start_time) > timedelta(seconds=self.timeout):
self.stop()
sleep(0.05)
| 19 | 101 | 91 | 192 | import logging
import requests
import threading
from time import sleep
from random import choice
from bs4 import BeautifulSoup
from unidecode import unidecode
from urllib.parse import urlparse
from crosslinked.logger import Log
from datetime import datetime, timedelta
from urllib3 import disable_warnings, exceptions
d... | import logging
import requests
import threading
from time import sleep
from random import choice
from bs4 import BeautifulSoup
from unidecode import unidecode
from urllib.parse import urlparse
from crosslinked.logger import Log
from datetime import datetime, timedelta
from urllib3 import disable_warnings, exceptions
d... |
48,747 | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked | /home/hieuvd/dung_repo/raw/stars_03/m8sec_CrossLinked/CrossLinked/crosslinked/utils.py | 18,19 | 1,24 | file_exists | 19,24 | 19,24 | from os import path
from crosslinked.logger import Log
def delimiter2list(value, delim=","):
return value.split(delim) if value else []
def delimiter2dict(value, delim_one=";", delim_two=":"):
x = {}
for item in value.split(delim_one):
if item:
sp = item.split(delim_two)
... | from os import path
from crosslinked.logger import Log
def delimiter2list(value, delim=","):
return value.split(delim) if value else []
def delimiter2dict(value, delim_one=";", delim_two=":"):
x = {}
for item in value.split(delim_one):
if item:
sp = item.split(delim_two)
... | if path.exists(filename):
return [line.strip() for line in open(filename)] if contents else filename
Log.warn("Input file not found: {}".format(filename))
exit(1)
| if path.exists(filename):
return [line.strip() for line in open(filename)] if contents else filename
Log.warn("Input file not found: {}".format(filename))
exit(1)
| 18 | 161 | 57 | 218 | from os import path
from crosslinked.logger import Log
def delimiter2list(value, delim=","):
return value.split(delim) if value else []
def delimiter2dict(value, delim_one=";", delim_two=":"):
x = {}
for item in value.split(delim_one):
if item:
sp = item.split(delim_two)
... | from os import path
from crosslinked.logger import Log
def delimiter2list(value, delim=","):
return value.split(delim) if value else []
def delimiter2dict(value, delim_one=";", delim_two=":"):
x = {}
for item in value.split(delim_one):
if item:
sp = item.split(delim_two)
... | |
48,760 | /home/hieuvd/dung_repo/raw/stars_03/miguelgrinberg_flask-celery-example/flask-celery-example | /home/hieuvd/dung_repo/raw/stars_03/miguelgrinberg_flask-celery-example/flask-celery-example/app.py | 45,47 | 1,130 | long_task | 48,66 | 47,66 | import os
import random
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from flask_mail import Mail, Message
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Flask-Mail configuration
app.config['MAIL_SERVER'] = ... | import os
import random
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from flask_mail import Mail, Message
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Flask-Mail configuration
app.config['MAIL_SERVER'] = ... | verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking']
adjective = ['master', 'radiant', 'silent', 'harmonic', 'fast']
noun = ['solar array', 'particle reshaper', 'cosmic ray', 'orbiter', 'bit']
message = ''
total = random.randint(10, 50)
for i in range(total):
if not mess... | """Background task that runs a long function with progress reports."""
verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking']
adjective = ['master', 'radiant', 'silent', 'harmonic', 'fast']
noun = ['solar array', 'particle reshaper', 'cosmic ray', 'orbiter', 'bit']
message = ''
to... | 68 | 1,087 | 264 | 1,351 | import os
import random
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from flask_mail import Mail, Message
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Flask-Mail configuration
app.config['MAIL_SERVER'] = ... | import os
import random
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from flask_mail import Mail, Message
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Flask-Mail configuration
app.config['MAIL_SERVER'] = ... | |
48,797 | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink/broadlink/alarm.py | 17,18 | 6,44 | get_sensors_status | S1C | 19,44 | 18,44 | class S1C(Device):
"""Controls a Broadlink S1C."""
TYPE = "S1C"
_SENSORS_TYPES = {
0x31: "Door Sensor",
0x91: "Key Fob",
0x21: "Motion Sensor",
}
def get_sensors_status(self) -> dict:
FILL_FUNC_BODY | class S1C(Device):
"""Controls a Broadlink S1C."""
TYPE = "S1C"
_SENSORS_TYPES = {
0x31: "Door Sensor",
0x91: "Key Fob",
0x21: "Motion Sensor",
}
def get_sensors_status(self) -> dict:
"""Return the state of the sensors."""
FILL_FUNC_BODY | packet = bytearray(16)
packet[0] = 0x06
response = self.send_packet(0x6A, packet)
e.check_error(response[0x22:0x24])
payload = self.decrypt(response[0x38:])
count = payload[0x4]
sensor_data = payload[0x6:]
sensors = [
bytearray(sensor_data[i * ... | """Return the state of the sensors."""
packet = bytearray(16)
packet[0] = 0x06
response = self.send_packet(0x6A, packet)
e.check_error(response[0x22:0x24])
payload = self.decrypt(response[0x38:])
count = payload[0x4]
sensor_data = payload[0x6:]
sen... | 66 | 121 | 304 | 425 | """Support for alarm kits."""
from . import exceptions as e
from .device import Device
class S1C(Device):
"""Controls a Broadlink S1C."""
TYPE = "S1C"
_SENSORS_TYPES = {
0x31: "Door Sensor",
0x91: "Key Fob",
0x21: "Motion Sensor",
}
def get_sensors_status(self) -> dict:
... | """Support for alarm kits."""
from . import exceptions as e
from .device import Device
class S1C(Device):
"""Controls a Broadlink S1C."""
TYPE = "S1C"
_SENSORS_TYPES = {
0x31: "Door Sensor",
0x91: "Key Fob",
0x21: "Motion Sensor",
}
def get_sensors_status(self) -> dict:
... |
48,800 | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink/broadlink/cover.py | 14,15 | 9,62 | _send | dooya | 16,29 | 15,29 | class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
FILL_FUNC_BODY def open(self) -> int:
"""Open the curtain."""
return self._send(0x01)
def close(self) -> int:
"""Close the curtain."""
... | class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
"""Send a packet to the device."""
FILL_FUNC_BODY def open(self) -> int:
"""Open the curtain."""
return self._send(0x01)
def close(self) -> i... | packet = bytearray(16)
packet[0x00] = 0x09
packet[0x02] = 0xBB
packet[0x03] = command
packet[0x04] = attribute
packet[0x09] = 0xFA
packet[0x0A] = 0x44
resp = self.send_packet(0x6A, packet)
e.check_error(resp[0x22:0x24])
payload = self.decr... | """Send a packet to the device."""
packet = bytearray(16)
packet[0x00] = 0x09
packet[0x02] = 0xBB
packet[0x03] = command
packet[0x04] = attribute
packet[0x09] = 0xFA
packet[0x0A] = 0x44
resp = self.send_packet(0x6A, packet)
e.check_error(r... | 31 | 370 | 163 | 533 | """Support for covers."""
import time
from typing import Sequence
from . import exceptions as e
from .device import Device
class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
FILL_FUNC_BODY def open(self) -> int:
... | """Support for covers."""
import time
from typing import Sequence
from . import exceptions as e
from .device import Device
class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
"""Send a packet to the device."""
FILL... |
48,801 | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink | /home/hieuvd/dung_repo/raw/stars_03/mjg59_python-broadlink/python-broadlink/broadlink/cover.py | 114,115 | 62,119 | set_percentage | dooya2 | 116,119 | 115,119 | class dooya2(Device):
"""Controls a Dooya curtain motor (version 2)."""
TYPE = "DT360E-2"
def _send(self, operation: int, data: Sequence = b""):
"""Send a command to the device."""
packet = bytearray(12)
packet[0x02] = 0xA5
packet[0x03] = 0xA5
packet[0x04] = 0x5A
... | class dooya2(Device):
"""Controls a Dooya curtain motor (version 2)."""
TYPE = "DT360E-2"
def _send(self, operation: int, data: Sequence = b""):
"""Send a command to the device."""
packet = bytearray(12)
packet[0x02] = 0xA5
packet[0x03] = 0xA5
packet[0x04] = 0x5A
... | self._send(2, [0x00, 0x09, new_percentage])
| """Set the position of the curtain."""
self._send(2, [0x00, 0x09, new_percentage])
| 4 | 631 | 30 | 661 | """Support for covers."""
import time
from typing import Sequence
from . import exceptions as e
from .device import Device
class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
"""Send a packet to the device."""
... | """Support for covers."""
import time
from typing import Sequence
from . import exceptions as e
from .device import Device
class dooya(Device):
"""Controls a Dooya curtain motor."""
TYPE = "DT360E"
def _send(self, command: int, attribute: int = 0) -> int:
"""Send a packet to the device."""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.