Skip to content

Commit

Permalink
add function clamp
Browse files Browse the repository at this point in the history
  • Loading branch information
tatsumoto-ren committed Apr 14, 2024
1 parent 5dfc839 commit 5059142
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 23 deletions.
30 changes: 15 additions & 15 deletions helpers/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
import requests
from requests import RequestException

try:
from .misc import clamp
except ImportError:
from misc import clamp


@dataclasses.dataclass(frozen=True)
class FileUrlData:
Expand Down Expand Up @@ -38,12 +43,7 @@ class AudioManagerException(RequestException):
exception: Optional[Exception] = None

def describe_short(self) -> str:
return str(
self.exception.__class__.__name__
if self.exception
else
self.response.status_code
)
return str(self.exception.__class__.__name__ if self.exception else self.response.status_code)


class AudioSettingsProtocol(Protocol):
Expand All @@ -69,20 +69,20 @@ class AudioManagerHttpClient:
}

def __init__(
self,
audio_settings: AudioSettingsProtocol,
progress_hook: Optional[anki.httpclient.ProgressCallback] = None
self,
audio_settings: AudioSettingsProtocol,
progress_hook: Optional[anki.httpclient.ProgressCallback] = None,
) -> None:
self._audio_settings = audio_settings
self._client = anki.httpclient.HttpClient(progress_hook)

def _get_with_timeout(self, url: str, timeout: int) -> requests.Response:
# Set timeout
self._client.timeout = min(max(timeout, 2), 99)
self._client.timeout = clamp(min_val=2, val=timeout, max_val=99)
return self._client.get(url, headers=self.headers.copy())

def _get_with_retry(self, url: str, timeout: int, attempts: int) -> requests.Response:
for _attempt in range(min(max(0, attempts - 1), 99)):
for _attempt in range(clamp(min_val=0, val=attempts - 1, max_val=99)):
try:
return self._get_with_timeout(url, timeout)
except requests.Timeout:
Expand All @@ -106,14 +106,14 @@ def download(self, file: Union[AudioSourceConfig, FileUrlData]) -> bytes:
except OSError as ex:
raise AudioManagerException(
file,
f'{file.url} download failed with {ex.__class__.__name__}',
exception=ex
f"{file.url} download failed with {ex.__class__.__name__}",
exception=ex,
)
if response.status_code != requests.codes.ok:
raise AudioManagerException(
file,
f'{file.url} download failed with return code {response.status_code}',
response=response
f"{file.url} download failed with return code {response.status_code}",
response=response,
)
return self._client.stream_content(response)

Expand Down
4 changes: 4 additions & 0 deletions helpers/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@

def strip_html_and_media(text: str) -> str:
return html_to_text_line(mw.col.media.strip(text)) if text else text


def clamp(min_val: int, val: int, max_val: int) -> int:
return max(min_val, min(val, max_val))
22 changes: 14 additions & 8 deletions widgets/audio_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@

from aqt.qt import *


try:
from .table import ExpandingTableWidget, CellContent, TableRow
from ..helpers.audio_manager import AudioSourceConfig, normalize_filename
from ..helpers.misc import clamp
except ImportError:
from table import ExpandingTableWidget, CellContent, TableRow
from helpers.audio_manager import AudioSourceConfig, normalize_filename
from helpers.misc import clamp


class SourceEnableCheckbox(QCheckBox):
Expand Down Expand Up @@ -96,7 +99,10 @@ def move_current_row(offset: int):
current_row = self.currentRow()
current_source_copy = pack_back(self.getRowCellContents(current_row))
self.removeRow(current_row)
self.addSource(current_source_copy, index=max(0, min(current_row + offset, self.rowCount() - 1)))
self.addSource(
current_source_copy,
index=clamp(min_val=0, val=current_row + offset, max_val=self.rowCount() - 1),
)

action = QAction("Move row down", self)
qconnect(action.triggered, lambda: move_current_row(1))
Expand All @@ -120,15 +126,15 @@ def isCellFilled(self, cell: CellContent) -> bool:
return isinstance(cell, QCheckBox) and cell.isChecked() or super().isCellFilled(cell)

def addSource(self, source: AudioSourceConfig, index: int = None):
self.addRow((checkbox := SourceEnableCheckbox(), source.name, source.url,), index=index)
self.addRow((checkbox := SourceEnableCheckbox(), source.name, source.url), index=index)
# The checkbox widget has to notify the table widget when its state changes.
# Otherwise, the table will not automatically add/remove rows.
qconnect(checkbox.stateChanged, lambda checked: self.onCellChanged(self.currentRow()))
checkbox.setChecked(source.enabled)

def addEmptyLastRow(self):
""" Redefine this method. """
return self.addSource(AudioSourceConfig(True, "", "", ), index=self.rowCount())
"""Redefine this method."""
return self.addSource(AudioSourceConfig(True, "", ""), index=self.rowCount())

def iterateConfigs(self) -> Iterable[AudioSourceConfig]:
"""
Expand Down Expand Up @@ -189,10 +195,10 @@ def initUI(self):
layout.addWidget(self.table)

# example rows
self.table.addSource(AudioSourceConfig(True, 'NHK1', '/test/nhk/1.json', ))
self.table.addSource(AudioSourceConfig(False, 'NHK2', '/test/nhk/2.json', ))
self.table.addSource(AudioSourceConfig(True, 'NHK3', '/test/nhk/3.json', ))
self.table.addSource(AudioSourceConfig(False, 'NHK4', '/test/nhk/4.json', ))
self.table.addSource(AudioSourceConfig(True, "NHK1", "/test/nhk/1.json"))
self.table.addSource(AudioSourceConfig(False, "NHK2", "/test/nhk/2.json"))
self.table.addSource(AudioSourceConfig(True, "NHK3", "/test/nhk/3.json"))
self.table.addSource(AudioSourceConfig(False, "NHK4", "/test/nhk/4.json"))


def main():
Expand Down

0 comments on commit 5059142

Please sign in to comment.