From 8489ac3c5aa0b0e2fec397694f9005e2b5a613e4 Mon Sep 17 00:00:00 2001 From: Cameron Clough Date: Mon, 26 Feb 2024 17:45:32 +0000 Subject: [PATCH] use pyupgrade to update syntax (#4) Co-authored-by: Adeeb Shihadeh --- .pre-commit-config.yaml | 2 +- pyproject.toml | 6 ++++-- teleoprtc/builder.py | 9 ++++----- teleoprtc/info.py | 1 - teleoprtc/stream.py | 35 ++++++++++++++++++----------------- teleoprtc/tracks.py | 8 ++++---- tests/test_integration.py | 6 +++--- 7 files changed, 34 insertions(+), 33 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 62edf45..89e745c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,6 +15,6 @@ repos: hooks: - id: mypy - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.1.6 + rev: v0.2.2 hooks: - id: ruff diff --git a/pyproject.toml b/pyproject.toml index 04bd122..1588270 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,8 +34,10 @@ dev = [ # https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml [tool.ruff] -select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF008", "RUF100", "A", "B", "TID251"] -ignore = ["W292", "E741", "E402", "C408", "ISC003", "B027", "B024"] line-length = 160 target-version="py311" + +[tool.ruff.lint] +select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF008", "RUF100", "A", "B", "TID251"] +ignore = ["W292", "E741", "E402", "C408", "ISC003", "B027", "B024"] flake8-implicit-str-concat.allow-multiline=false diff --git a/teleoprtc/builder.py b/teleoprtc/builder.py index 9ec183e..f659e84 100644 --- a/teleoprtc/builder.py +++ b/teleoprtc/builder.py @@ -1,5 +1,4 @@ import abc -from typing import List, Dict import aiortc @@ -16,9 +15,9 @@ class WebRTCStreamBuilder(abc.ABC): class WebRTCOfferBuilder(WebRTCStreamBuilder): def __init__(self, connection_provider: ConnectionProvider): self.connection_provider = connection_provider - self.requested_camera_types: List[str] = [] + self.requested_camera_types: list[str] = [] self.requested_audio = False - self.audio_tracks: List[aiortc.MediaStreamTrack] = [] + self.audio_tracks: list[aiortc.MediaStreamTrack] = [] self.messaging_enabled = False def offer_to_receive_video_stream(self, camera_type: str): @@ -49,9 +48,9 @@ class WebRTCOfferBuilder(WebRTCStreamBuilder): class WebRTCAnswerBuilder(WebRTCStreamBuilder): def __init__(self, offer_sdp: str): self.offer_sdp = offer_sdp - self.video_tracks: Dict[str, aiortc.MediaStreamTrack] = dict() + self.video_tracks: dict[str, aiortc.MediaStreamTrack] = dict() self.requested_audio = False - self.audio_tracks: List[aiortc.MediaStreamTrack] = [] + self.audio_tracks: list[aiortc.MediaStreamTrack] = [] def offer_to_receive_audio_stream(self): self.requested_audio = True diff --git a/teleoprtc/info.py b/teleoprtc/info.py index b47ec3f..fb786fe 100644 --- a/teleoprtc/info.py +++ b/teleoprtc/info.py @@ -1,4 +1,3 @@ - import dataclasses import aiortc diff --git a/teleoprtc/stream.py b/teleoprtc/stream.py index a928c14..9955067 100644 --- a/teleoprtc/stream.py +++ b/teleoprtc/stream.py @@ -2,7 +2,8 @@ import abc import asyncio import dataclasses import logging -from typing import Callable, Awaitable, Dict, List, Any, Optional +from typing import Any +from collections.abc import Callable, Awaitable import aiortc from aiortc.contrib.media import MediaRelay @@ -13,7 +14,7 @@ from teleoprtc.tracks import parse_video_track_id @dataclasses.dataclass class StreamingOffer: sdp: str - video: List[str] + video: list[str] ConnectionProvider = Callable[[StreamingOffer], Awaitable[aiortc.RTCSessionDescription]] @@ -22,25 +23,25 @@ MessageHandler = Callable[[bytes], Awaitable[None]] class WebRTCBaseStream(abc.ABC): def __init__(self, - consumed_camera_types: List[str], + consumed_camera_types: list[str], consume_audio: bool, - video_producer_tracks: List[aiortc.MediaStreamTrack], - audio_producer_tracks: List[aiortc.MediaStreamTrack], + video_producer_tracks: list[aiortc.MediaStreamTrack], + audio_producer_tracks: list[aiortc.MediaStreamTrack], should_add_data_channel: bool): self.peer_connection = aiortc.RTCPeerConnection() self.media_relay = MediaRelay() self.expected_incoming_camera_types = consumed_camera_types self.expected_incoming_audio = consume_audio - self.expected_number_of_incoming_media: Optional[int] = None + self.expected_number_of_incoming_media: int | None = None - self.incoming_camera_tracks: Dict[str, aiortc.MediaStreamTrack] = dict() - self.incoming_audio_tracks: List[aiortc.MediaStreamTrack] = [] - self.outgoing_video_tracks: List[aiortc.MediaStreamTrack] = video_producer_tracks - self.outgoing_audio_tracks: List[aiortc.MediaStreamTrack] = audio_producer_tracks + self.incoming_camera_tracks: dict[str, aiortc.MediaStreamTrack] = dict() + self.incoming_audio_tracks: list[aiortc.MediaStreamTrack] = [] + self.outgoing_video_tracks: list[aiortc.MediaStreamTrack] = video_producer_tracks + self.outgoing_audio_tracks: list[aiortc.MediaStreamTrack] = audio_producer_tracks self.should_add_data_channel = should_add_data_channel - self.messaging_channel: Optional[aiortc.RTCDataChannel] = None - self.incoming_message_handlers: List[MessageHandler] = [] + self.messaging_channel: aiortc.RTCDataChannel | None = None + self.incoming_message_handlers: list[MessageHandler] = [] self.incoming_media_ready_event = asyncio.Event() self.messaging_channel_ready_event = asyncio.Event() @@ -69,7 +70,7 @@ class WebRTCBaseStream(abc.ABC): if self.expected_incoming_audio: self.peer_connection.addTransceiver("audio", direction="recvonly") - def _find_trackless_transceiver(self, kind: str) -> Optional[aiortc.RTCRtpTransceiver]: + def _find_trackless_transceiver(self, kind: str) -> aiortc.RTCRtpTransceiver | None: transceivers = self.peer_connection.getTransceivers() target_transceiver = None for t in transceivers: @@ -96,7 +97,7 @@ class WebRTCBaseStream(abc.ABC): self.peer_connection.addTrack(track) - def _add_messaging_channel(self, channel: Optional[aiortc.RTCDataChannel] = None): + def _add_messaging_channel(self, channel: aiortc.RTCDataChannel | None = None): if not channel: channel = self.peer_connection.createDataChannel("data", ordered=True) @@ -255,7 +256,7 @@ class WebRTCAnswerStream(WebRTCBaseStream): super().__init__(*args, **kwargs) self.session = session - def _probe_video_codecs(self) -> List[str]: + def _probe_video_codecs(self) -> list[str]: codecs = [] for track in self.outgoing_video_tracks: if hasattr(track, "codec_preference") and track.codec_preference() is not None: @@ -263,14 +264,14 @@ class WebRTCAnswerStream(WebRTCBaseStream): return codecs - def _override_incoming_video_codecs(self, remote_sdp: str, codecs: List[str]) -> str: + def _override_incoming_video_codecs(self, remote_sdp: str, codecs: list[str]) -> str: desc = aiortc.sdp.SessionDescription.parse(remote_sdp) codec_mimes = [f"video/{c}" for c in codecs] for m in desc.media: if m.kind != "video": continue - preferred_codecs: List[aiortc.RTCRtpCodecParameters] = [c for c in m.rtp.codecs if c.mimeType in codec_mimes] + preferred_codecs: list[aiortc.RTCRtpCodecParameters] = [c for c in m.rtp.codecs if c.mimeType in codec_mimes] if len(preferred_codecs) == 0: raise ValueError(f"None of {preferred_codecs} codecs is supported in remote SDP") diff --git a/teleoprtc/tracks.py b/teleoprtc/tracks.py index 96d9c35..7cb2da7 100644 --- a/teleoprtc/tracks.py +++ b/teleoprtc/tracks.py @@ -2,7 +2,7 @@ import asyncio import logging import time import fractions -from typing import Optional, Tuple, Any +from typing import Any import aiortc from aiortc.mediastreams import VIDEO_CLOCK_RATE, VIDEO_TIME_BASE @@ -12,7 +12,7 @@ def video_track_id(camera_type: str, track_id: str) -> str: return f"{camera_type}:{track_id}" -def parse_video_track_id(track_id: str) -> Tuple[str, str]: +def parse_video_track_id(track_id: str) -> tuple[str, str]: parts = track_id.split(":") if len(parts) != 2: raise ValueError(f"Invalid video track id: {track_id}") @@ -35,7 +35,7 @@ class TiciVideoStreamTrack(aiortc.MediaStreamTrack): self._dt: float = dt self._time_base: fractions.Fraction = time_base self._clock_rate: int = clock_rate - self._start: Optional[float] = None + self._start: float | None = None self._logger = logging.getLogger("WebRTCStream") def log_debug(self, msg: Any, *args): @@ -53,7 +53,7 @@ class TiciVideoStreamTrack(aiortc.MediaStreamTrack): return pts - def codec_preference(self) -> Optional[str]: + def codec_preference(self) -> str | None: return None diff --git a/tests/test_integration.py b/tests/test_integration.py index 136ba7c..af61f7b 100755 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -59,7 +59,7 @@ class TestStreamIntegration(unittest.IsolatedAsyncioTestCase): try: async with asyncio.timeout(2): await stream.wait_for_connection() - except asyncio.TimeoutError: + except TimeoutError: self.fail("Timed out waiting for connection") self.assertTrue(stream.is_connected_and_ready) @@ -79,7 +79,7 @@ class TestStreamIntegration(unittest.IsolatedAsyncioTestCase): try: async with asyncio.timeout(1): await track.recv() - except asyncio.TimeoutError: + except TimeoutError: self.fail("Timed out waiting for audio frame") for cam in cameras: @@ -93,7 +93,7 @@ class TestStreamIntegration(unittest.IsolatedAsyncioTestCase): try: async with asyncio.timeout(1): await stream.get_incoming_video_track(cam, False).recv() - except asyncio.TimeoutError: + except TimeoutError: self.fail("Timed out waiting for video frame") await stream.stop()