Use ulid_now instead of ulid_at_timestamp if no timestamp is passed (#104226)

* Use ulid_now instead of ulid_at_timestamp if no timestamp is passed

ulid_now is slightly faster than ulid_at_timestamp

* tweak usage
pull/104236/head
J. Nick Koston 2023-11-19 21:27:24 -06:00 committed by GitHub
parent 6ef194f992
commit cc31d77205
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 27 additions and 16 deletions

View File

@ -320,7 +320,7 @@ class Pipeline:
wake_word_entity: str | None wake_word_entity: str | None
wake_word_id: str | None wake_word_id: str | None
id: str = field(default_factory=ulid_util.ulid) id: str = field(default_factory=ulid_util.ulid_now)
@classmethod @classmethod
def from_json(cls, data: dict[str, Any]) -> Pipeline: def from_json(cls, data: dict[str, Any]) -> Pipeline:
@ -482,7 +482,7 @@ class PipelineRun:
wake_word_settings: WakeWordSettings | None = None wake_word_settings: WakeWordSettings | None = None
audio_settings: AudioSettings = field(default_factory=AudioSettings) audio_settings: AudioSettings = field(default_factory=AudioSettings)
id: str = field(default_factory=ulid_util.ulid) id: str = field(default_factory=ulid_util.ulid_now)
stt_provider: stt.SpeechToTextEntity | stt.Provider = field(init=False, repr=False) stt_provider: stt.SpeechToTextEntity | stt.Provider = field(init=False, repr=False)
tts_engine: str = field(init=False, repr=False) tts_engine: str = field(init=False, repr=False)
tts_options: dict | None = field(init=False, default=None) tts_options: dict | None = field(init=False, default=None)
@ -1476,7 +1476,7 @@ class PipelineStorageCollection(
@callback @callback
def _get_suggested_id(self, info: dict) -> str: def _get_suggested_id(self, info: dict) -> str:
"""Suggest an ID based on the config.""" """Suggest an ID based on the config."""
return ulid_util.ulid() return ulid_util.ulid_now()
async def _update_data(self, item: Pipeline, update_data: dict) -> Pipeline: async def _update_data(self, item: Pipeline, update_data: dict) -> Pipeline:
"""Return a new updated item.""" """Return a new updated item."""
@ -1664,7 +1664,7 @@ class DeviceAudioQueue:
queue: asyncio.Queue[bytes | None] queue: asyncio.Queue[bytes | None]
"""Queue of audio chunks (None = stop signal)""" """Queue of audio chunks (None = stop signal)"""
id: str = field(default_factory=ulid_util.ulid) id: str = field(default_factory=ulid_util.ulid_now)
"""Unique id to ensure the correct audio queue is cleaned up in websocket API.""" """Unique id to ensure the correct audio queue is cleaned up in websocket API."""
overflow: bool = False overflow: bool = False

View File

@ -88,7 +88,7 @@ class GoogleGenerativeAIAgent(conversation.AbstractConversationAgent):
conversation_id = user_input.conversation_id conversation_id = user_input.conversation_id
messages = self.history[conversation_id] messages = self.history[conversation_id]
else: else:
conversation_id = ulid.ulid() conversation_id = ulid.ulid_now()
messages = [] messages = []
try: try:

View File

@ -141,7 +141,7 @@ class OpenAIAgent(conversation.AbstractConversationAgent):
conversation_id = user_input.conversation_id conversation_id = user_input.conversation_id
messages = self.history[conversation_id] messages = self.history[conversation_id]
else: else:
conversation_id = ulid.ulid() conversation_id = ulid.ulid_now()
try: try:
prompt = self._async_generate_prompt(raw_prompt) prompt = self._async_generate_prompt(raw_prompt)
except TemplateError as err: except TemplateError as err:

View File

@ -38,7 +38,7 @@ class DatasetEntry:
tlv: str tlv: str
created: datetime = dataclasses.field(default_factory=dt_util.utcnow) created: datetime = dataclasses.field(default_factory=dt_util.utcnow)
id: str = dataclasses.field(default_factory=ulid_util.ulid) id: str = dataclasses.field(default_factory=ulid_util.ulid_now)
@property @property
def channel(self) -> int | None: def channel(self) -> int | None:

View File

@ -37,7 +37,7 @@ from homeassistant.components.assist_pipeline.vad import (
) )
from homeassistant.const import __version__ from homeassistant.const import __version__
from homeassistant.core import Context, HomeAssistant from homeassistant.core import Context, HomeAssistant
from homeassistant.util.ulid import ulid from homeassistant.util.ulid import ulid_now
from .const import CHANNELS, DOMAIN, RATE, RTP_AUDIO_SETTINGS, WIDTH from .const import CHANNELS, DOMAIN, RATE, RTP_AUDIO_SETTINGS, WIDTH
@ -219,7 +219,7 @@ class PipelineRtpDatagramProtocol(RtpDatagramProtocol):
) -> None: ) -> None:
"""Forward audio to pipeline STT and handle TTS.""" """Forward audio to pipeline STT and handle TTS."""
if self._session_id is None: if self._session_id is None:
self._session_id = ulid() self._session_id = ulid_now()
# Play listening tone at the start of each cycle # Play listening tone at the start of each cycle
if self.listening_tone_enabled: if self.listening_tone_enabled:

View File

@ -91,7 +91,7 @@ from .util.async_ import (
from .util.json import JsonObjectType from .util.json import JsonObjectType
from .util.read_only_dict import ReadOnlyDict from .util.read_only_dict import ReadOnlyDict
from .util.timeout import TimeoutManager from .util.timeout import TimeoutManager
from .util.ulid import ulid, ulid_at_time from .util.ulid import ulid_at_time, ulid_now
from .util.unit_system import ( from .util.unit_system import (
_CONF_UNIT_SYSTEM_IMPERIAL, _CONF_UNIT_SYSTEM_IMPERIAL,
_CONF_UNIT_SYSTEM_US_CUSTOMARY, _CONF_UNIT_SYSTEM_US_CUSTOMARY,
@ -930,7 +930,7 @@ class Context:
id: str | None = None, # pylint: disable=redefined-builtin id: str | None = None, # pylint: disable=redefined-builtin
) -> None: ) -> None:
"""Init the context.""" """Init the context."""
self.id = id or ulid() self.id = id or ulid_now()
self.user_id = user_id self.user_id = user_id
self.parent_id = parent_id self.parent_id = parent_id
self.origin_event: Event | None = None self.origin_event: Event | None = None

View File

@ -1,11 +1,22 @@
"""Helpers to generate ulids.""" """Helpers to generate ulids."""
from __future__ import annotations from __future__ import annotations
import time from ulid_transform import (
bytes_to_ulid,
ulid_at_time,
ulid_hex,
ulid_now,
ulid_to_bytes,
)
from ulid_transform import bytes_to_ulid, ulid_at_time, ulid_hex, ulid_to_bytes __all__ = [
"ulid",
__all__ = ["ulid", "ulid_hex", "ulid_at_time", "ulid_to_bytes", "bytes_to_ulid"] "ulid_hex",
"ulid_at_time",
"ulid_to_bytes",
"bytes_to_ulid",
"ulid_now",
]
def ulid(timestamp: float | None = None) -> str: def ulid(timestamp: float | None = None) -> str:
@ -25,4 +36,4 @@ def ulid(timestamp: float | None = None) -> str:
import ulid import ulid
ulid.parse(ulid_util.ulid()) ulid.parse(ulid_util.ulid())
""" """
return ulid_at_time(timestamp or time.time()) return ulid_now() if timestamp is None else ulid_at_time(timestamp)