Skip to content

Commit

Permalink
formatted
Browse files Browse the repository at this point in the history
  • Loading branch information
mbsantiago committed May 9, 2024
1 parent 3e1d1b9 commit 9e4df0b
Show file tree
Hide file tree
Showing 71 changed files with 174 additions and 515 deletions.
4 changes: 1 addition & 3 deletions src/soundevent/arrays/dimensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,9 +493,7 @@ def get_dim_step(
return attrs[DimAttrs.step.value]

if not estimate_step:
raise ValueError(
f"Step size not found in the '{dim}' dimension attributes."
)
raise ValueError(f"Step size not found in the '{dim}' dimension attributes.")

return estimate_dim_step(
coord.data,
Expand Down
18 changes: 4 additions & 14 deletions src/soundevent/arrays/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@
from numpy.typing import DTypeLike
from xarray.core.types import InterpOptions

from soundevent.arrays.dimensions import (
create_range_dim,
get_dim_range,
get_dim_step,
)
from soundevent.arrays.dimensions import create_range_dim, get_dim_range, get_dim_step

__all__ = [
"center",
Expand Down Expand Up @@ -92,9 +88,7 @@ def crop_dim(
stop = current_stop

if start > stop:
raise ValueError(
f"Start value {start} must be less than stop value {stop}"
)
raise ValueError(f"Start value {start} must be less than stop value {stop}")

if start < current_start or stop > current_stop:
raise ValueError(
Expand Down Expand Up @@ -180,9 +174,7 @@ def extend_dim(
stop = current_stop

if start > stop:
raise ValueError(
f"Start value {start} must be less than stop value {stop}"
)
raise ValueError(f"Start value {start} must be less than stop value {stop}")

step = get_dim_step(arr, dim)

Expand Down Expand Up @@ -312,9 +304,7 @@ def set_value_at_pos(
start, stop = get_dim_range(array, dim)

if coord < start or coord > stop:
raise KeyError(
f"Position {coord} is outside the range of dimension {dim}."
)
raise KeyError(f"Position {coord} is outside the range of dimension {dim}.")

index = array.indexes[dim].get_slice_bound(coord, "right")
indexer[dims[dim]] = index - 1
Expand Down
3 changes: 1 addition & 2 deletions src/soundevent/audio/chunks.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,7 @@ def _read_chunk(riff: BinaryIO) -> Optional[Chunk]:

if chunk_id in CHUNKS_WITH_SUBCHUNKS:
chunk.subchunks = {
subchunk.chunk_id: subchunk
for subchunk in _get_subchunks(riff, size - 4)
subchunk.chunk_id: subchunk for subchunk in _get_subchunks(riff, size - 4)
}
else:
riff.seek(size, os.SEEK_CUR)
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/audio/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ def _get_filter(
order: int = 5,
) -> np.ndarray:
if low_freq is None and high_freq is None:
raise ValueError(
"At least one of low_freq and high_freq must be specified."
)
raise ValueError("At least one of low_freq and high_freq must be specified.")

if low_freq is None:
# Low pass filter
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/audio/media_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,7 @@ def get_media_info(path: PathLike) -> MediaInfo:
# chunk is the size of the data subchunk divided by the number
# of channels and the bit depth.
data_chunk = chunk.subchunks["data"]
samples = (
8 * data_chunk.size // (fmt_info.channels * fmt_info.bit_depth)
)
samples = 8 * data_chunk.size // (fmt_info.channels * fmt_info.bit_depth)
duration = samples / fmt_info.samplerate

return MediaInfo(
Expand Down
8 changes: 2 additions & 6 deletions src/soundevent/audio/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ def pcen_core(
raise ValueError(f"eps={eps} must be strictly positive")

if time_constant <= 0:
raise ValueError(
f"time_constant={time_constant} must be strictly positive"
)
raise ValueError(f"time_constant={time_constant} must be strictly positive")

Check warning on line 123 in src/soundevent/audio/spectrum.py

View check run for this annotation

Codecov / codecov/patch

src/soundevent/audio/spectrum.py#L123

Added line #L123 was not covered by tests

if b is None:
t_frames = time_constant * sr / float(hop_length)
Expand All @@ -146,9 +144,7 @@ def pcen_core(
if max_size == 1:
ref = S
elif S.ndim == 1:
raise ValueError(
"Max-filtering cannot be applied to 1-dimensional input"
)
raise ValueError("Max-filtering cannot be applied to 1-dimensional input")

Check warning on line 147 in src/soundevent/audio/spectrum.py

View check run for this annotation

Codecov / codecov/patch

src/soundevent/audio/spectrum.py#L147

Added line #L147 was not covered by tests
else:
if max_axis is None:
if S.ndim != 2:
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/data/annotation_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,4 @@ class AnnotationSet(BaseModel):
default_factory=list,
repr=False,
)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
8 changes: 2 additions & 6 deletions src/soundevent/data/annotation_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,11 @@ class StatusBadge(BaseModel):

state: AnnotationState
owner: Optional[User] = None
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)


class AnnotationTask(BaseModel):
uuid: UUID = Field(default_factory=uuid4, repr=False)
clip: Clip
status_badges: List[StatusBadge] = Field(default_factory=list)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
4 changes: 1 addition & 3 deletions src/soundevent/data/clip_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,4 @@ class ClipAnnotation(BaseModel):
sequences: List[SequenceAnnotation] = Field(default_factory=list)
tags: List[Tag] = Field(default_factory=list)
notes: List[Note] = Field(default_factory=list)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
8 changes: 2 additions & 6 deletions src/soundevent/data/clip_evaluations.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,13 @@ def _check_matches(self):
}

match_targets = [
match.target.uuid
for match in self.matches
if match.target is not None
match.target.uuid for match in self.matches if match.target is not None
]

match_targets_set = set(match_targets)

match_sources = [
match.source.uuid
for match in self.matches
if match.source is not None
match.source.uuid for match in self.matches if match.source is not None
]

match_sources_set = set(match_sources)
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/data/evaluations.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ class Evaluation(BaseModel):
"""Evaluation Class."""

uuid: UUID = Field(default_factory=uuid4, repr=False)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
evaluation_task: str
clip_evaluations: Sequence[ClipEvaluation] = Field(default_factory=list)
metrics: Sequence[Feature] = Field(default_factory=list)
Expand Down
34 changes: 9 additions & 25 deletions src/soundevent/data/geometries.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,7 @@ def _validate_time_interval(cls, v: List[Time]) -> List[Time]:
after the end time).
"""
if len(v) != 2:
raise ValueError(
"The time interval must have exactly two time stamps."
)
raise ValueError("The time interval must have exactly two time stamps.")

if v[0] > v[1]:
raise ValueError("The start time must be before the end time.")
Expand Down Expand Up @@ -325,9 +323,7 @@ def _validate_coordinates(cls, v: List[float]) -> List[float]:
raise ValueError("The time must be positive.")

if frequency < 0 or frequency > MAX_FREQUENCY:
raise ValueError(
f"The frequency must be between 0 and {MAX_FREQUENCY}."
)
raise ValueError(f"The frequency must be between 0 and {MAX_FREQUENCY}.")

return v

Expand Down Expand Up @@ -473,8 +469,7 @@ def _validate_coordinates(

if frequency < 0 or frequency > MAX_FREQUENCY:
raise ValueError(
f"The frequency must be between 0 and "
f"{MAX_FREQUENCY}."
f"The frequency must be between 0 and " f"{MAX_FREQUENCY}."
)

return v
Expand Down Expand Up @@ -532,9 +527,7 @@ def _validate_coordinates(cls, v: List[float]) -> List[float]:
negative or the frequency is outside the valid range).
"""
if len(v) != 4:
raise ValueError(
"The bounding box must have exactly four coordinates."
)
raise ValueError("The bounding box must have exactly four coordinates.")

start_time, low_freq, end_time, high_freq = v

Expand All @@ -558,9 +551,7 @@ def _validate_coordinates(cls, v: List[float]) -> List[float]:
raise ValueError("The start time must be before the end time.")

if low_freq > high_freq:
raise ValueError(
"The start frequency must be before the end frequency."
)
raise ValueError("The start frequency must be before the end frequency.")

return v

Expand Down Expand Up @@ -771,28 +762,23 @@ def _validate_coordinates(
negative or the frequency is outside the valid range).
"""
if len(v) < 1:
raise ValueError(
"The multipolygon must have at least one polygon."
)
raise ValueError("The multipolygon must have at least one polygon.")

Check warning on line 765 in src/soundevent/data/geometries.py

View check run for this annotation

Codecov / codecov/patch

src/soundevent/data/geometries.py#L765

Added line #L765 was not covered by tests

for polygon in v:
if len(polygon) < 1:
raise ValueError("Each polygon must have at least one ring.")

for ring in polygon:
if len(ring) < 3:
raise ValueError(
"Each ring must have at least three points."
)
raise ValueError("Each ring must have at least three points.")

Check warning on line 773 in src/soundevent/data/geometries.py

View check run for this annotation

Codecov / codecov/patch

src/soundevent/data/geometries.py#L773

Added line #L773 was not covered by tests

for time, frequency in ring:
if time < 0:
raise ValueError("The time must be positive.")

if frequency < 0 or frequency > MAX_FREQUENCY:
raise ValueError(
f"The frequency must be between 0 and "
f"{MAX_FREQUENCY}."
f"The frequency must be between 0 and " f"{MAX_FREQUENCY}."
)

return v
Expand Down Expand Up @@ -921,6 +907,4 @@ def geometry_validate(
from_attributes=mode == "attributes",
)
except ValidationError as error:
raise ValueError(
f"Object {obj} is not a valid {geom_type}."
) from error
raise ValueError(f"Object {obj} is not a valid {geom_type}.") from error
4 changes: 1 addition & 3 deletions src/soundevent/data/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ class Note(BaseModel):
message: str
created_by: Optional[User] = None
is_issue: bool = False
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)

def __hash__(self):
"""Hash the Note object."""
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/data/prediction_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,4 @@ class PredictionSet(BaseModel):

uuid: UUID = Field(default_factory=uuid4)
clip_predictions: List[ClipPrediction] = Field(default_factory=list)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
4 changes: 1 addition & 3 deletions src/soundevent/data/recording_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,4 @@
class RecordingSet(BaseModel):
uuid: UUID = Field(default_factory=uuid4)
recordings: List[Recording] = Field(default_factory=list, repr=False)
created_on: datetime.datetime = Field(
default_factory=datetime.datetime.now
)
created_on: datetime.datetime = Field(default_factory=datetime.datetime.now)
5 changes: 1 addition & 4 deletions src/soundevent/data/recordings.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,7 @@ def from_file(
Recording
The recording object.
"""
from soundevent.audio.media_info import (
compute_md5_checksum,
get_media_info,
)
from soundevent.audio.media_info import compute_md5_checksum, get_media_info

media_info = get_media_info(path)

Expand Down
19 changes: 4 additions & 15 deletions src/soundevent/evaluation/affinity.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
"""Measures of affinity between sound events geometries."""

from soundevent import data
from soundevent.geometry import (
buffer_geometry,
compute_bounds,
geometry_to_shapely,
)
from soundevent.geometry import buffer_geometry, compute_bounds, geometry_to_shapely

__all__ = [
"compute_affinity",
Expand Down Expand Up @@ -88,10 +84,7 @@ def compute_affinity(
geometry1 = _prepare_geometry(geometry1, time_buffer, freq_buffer)
geometry2 = _prepare_geometry(geometry2, time_buffer, freq_buffer)

if (
geometry1.type in TIME_GEOMETRY_TYPES
or geometry2.type in TIME_GEOMETRY_TYPES
):
if geometry1.type in TIME_GEOMETRY_TYPES or geometry2.type in TIME_GEOMETRY_TYPES:
return compute_affinity_in_time(geometry1, geometry2)

shp1 = geometry_to_shapely(geometry1)
Expand All @@ -114,12 +107,8 @@ def compute_affinity_in_time(
start_time1, _, end_time1, _ = compute_bounds(geometry1)
start_time2, _, end_time2, _ = compute_bounds(geometry2)

intersection = max(
0, min(end_time1, end_time2) - max(start_time1, start_time2)
)
union = (
(end_time1 - start_time1) + (end_time2 - start_time2) - intersection
)
intersection = max(0, min(end_time1, end_time2) - max(start_time1, start_time2))
union = (end_time1 - start_time1) + (end_time2 - start_time2) - intersection

if union == 0:
return 0
Expand Down
12 changes: 3 additions & 9 deletions src/soundevent/evaluation/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ def balanced_accuracy(
y_score: np.ndarray,
) -> float:
num_classes = y_score.shape[1]
y_true_array = np.array(
[y if y is not None else num_classes for y in y_true]
)
y_true_array = np.array([y if y is not None else num_classes for y in y_true])
y_score = np.c_[y_score, 1 - y_score.sum(axis=1, keepdims=True)]
y_pred = y_score.argmax(axis=1)
return metrics.balanced_accuracy_score(
Expand All @@ -59,9 +57,7 @@ def accuracy(
y_score: np.ndarray,
) -> float:
num_classes = y_score.shape[1]
y_true_array = np.array(
[y if y is not None else num_classes for y in y_true]
)
y_true_array = np.array([y if y is not None else num_classes for y in y_true])
y_score = np.c_[y_score, 1 - y_score.sum(axis=1, keepdims=True)]
y_pred = y_score.argmax(axis=1)
return metrics.accuracy_score( # type: ignore
Expand All @@ -75,9 +71,7 @@ def top_3_accuracy(
y_score: np.ndarray,
) -> float:
num_classes = y_score.shape[1]
y_true_array = np.array(
[y if y is not None else num_classes for y in y_true]
)
y_true_array = np.array([y if y is not None else num_classes for y in y_true])
y_score = np.c_[y_score, 1 - y_score.sum(axis=1, keepdims=True)]
return metrics.top_k_accuracy_score( # type: ignore
y_true=y_true_array,
Expand Down
4 changes: 1 addition & 3 deletions src/soundevent/evaluation/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
from soundevent.evaluation.tasks.sound_event_classification import (
sound_event_classification,
)
from soundevent.evaluation.tasks.sound_event_detection import (
sound_event_detection,
)
from soundevent.evaluation.tasks.sound_event_detection import sound_event_detection

__all__ = [
"clip_classification",
Expand Down
Loading

0 comments on commit 9e4df0b

Please sign in to comment.