use pyupgrade to update syntax (#4)

Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com>
This commit is contained in:
Cameron Clough 2024-02-26 17:45:32 +00:00 committed by GitHub
parent 3f9e8176d1
commit 8489ac3c5a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 34 additions and 33 deletions

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -1,4 +1,3 @@
import dataclasses
import aiortc

View File

@ -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")

View File

@ -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

View File

@ -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()