<commit_before>"""Sensor for monitoring the size of a file."""
from __future__ import annotations

from datetime import datetime, timedelta
import logging
import os
import pathlib

from homeassistant.components.sensor import (
    SensorDeviceClass,
    SensorEntity,
    SensorEntityDescription,
    SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_FILE_PATH, DATA_BYTES, DATA_MEGABYTES
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import (
    CoordinatorEntity,
    DataUpdateCoordinator,
    UpdateFailed,
)
import homeassistant.util.dt as dt_util

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

ICON = "mdi:file"

SENSOR_TYPES = (
    SensorEntityDescription(
        key="file",
        icon=ICON,
        name="Size",
        native_unit_of_measurement=DATA_MEGABYTES,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    SensorEntityDescription(
        key="bytes",
        entity_registry_enabled_default=False,
        icon=ICON,
        name="Size bytes",
        native_unit_of_measurement=DATA_BYTES,
        state_class=SensorStateClass.MEASUREMENT,
        entity_category=EntityCategory.DIAGNOSTIC,
    ),
    SensorEntityDescription(
        key="last_updated",
        entity_registry_enabled_default=False,
        icon=ICON,
        name="Last Updated",
        device_class=SensorDeviceClass.TIMESTAMP,
        state_class=SensorStateClass.MEASUREMENT,
        entity_category=EntityCategory.DIAGNOSTIC,
    ),
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the platform from config entry."""

    path = entry.data[CONF_FILE_PATH]
    get_path = await hass.async_add_executor_job(pathlib.Path, path)
    fullpath = str(get_path.absolute())

    coordinator = FileSizeCoordinator(hass, fullpath)
    await coordinator.async_config_entry_first_refresh()

    async_add_entities(
        FilesizeEntity(description, fullpath, entry.entry_id, coordinator)
        for description in SENSOR_TYPES
    )


class FileSizeCoordinator(DataUpdateCoordinator):
    """Filesize coordinator."""

    def __init__(self, hass: HomeAssistant, path: str) -> None:
        """Initialize filesize coordinator."""
        super().__init__(
            hass,
            _LOGGER,
            name=DOMAIN,
            update_interval=timedelta(seconds=60),
        )
        self._path = path

    async def _async_update_data(self) -> dict[str, float | int | datetime]:
        """Fetch file information."""
        try:
            statinfo = await self.hass.async_add_executor_job(os.stat, self._path)
        except OSError as error:
            raise UpdateFailed(f"Can not retrieve file statistics {error}") from error

        size = statinfo.st_size
        last_updated = datetime.utcfromtimestamp(statinfo.st_mtime).replace(
            tzinfo=dt_util.UTC
        )

        _LOGGER.debug("size %s, last updated %s", size, last_updated)
        data: dict[str, int | float | datetime] = {
            "file": round(size / 1e6, 2),
            "bytes": size,
            "last_updated": last_updated,
        }

        return data


class FilesizeEntity(CoordinatorEntity[FileSizeCoordinator], SensorEntity):
    """Filesize sensor."""

    entity_description: SensorEntityDescription

    def __init__(
        self,
        description: SensorEntityDescription,
        path: str,
        entry_id: str,
        coordinator: FileSizeCoordinator,
    ) -> None:
        """Initialize the Filesize sensor."""
        super().__init__(coordinator)
        base_name = path.split("/")[-1]
        self._attr_name = f"{base_name} {description.name}"
        self._attr_unique_id = (
            entry_id if description.key == "file" else f"{entry_id}-{description.key}"
        )
        self.entity_description = description
        self._attr_device_info = DeviceInfo(
            entry_type=DeviceEntryType.SERVICE,
            identifiers={(DOMAIN, entry_id)},
            name=base_name,
        )<commit_msg>Migrate Filesize to new entity naming style (#75199)<commit_after>"""Sensor for monitoring the size of a file."""
from __future__ import annotations

from datetime import datetime, timedelta
import logging
import os
import pathlib

from homeassistant.components.sensor import (
    SensorDeviceClass,
    SensorEntity,
    SensorEntityDescription,
    SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_FILE_PATH, DATA_BYTES, DATA_MEGABYTES
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import (
    CoordinatorEntity,
    DataUpdateCoordinator,
    UpdateFailed,
)
import homeassistant.util.dt as dt_util

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

ICON = "mdi:file"

SENSOR_TYPES = (
    SensorEntityDescription(
        key="file",
        icon=ICON,
        name="Size",
        native_unit_of_measurement=DATA_MEGABYTES,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    SensorEntityDescription(
        key="bytes",
        entity_registry_enabled_default=False,
        icon=ICON,
        name="Size bytes",
        native_unit_of_measurement=DATA_BYTES,
        state_class=SensorStateClass.MEASUREMENT,
        entity_category=EntityCategory.DIAGNOSTIC,
    ),
    SensorEntityDescription(
        key="last_updated",
        entity_registry_enabled_default=False,
        icon=ICON,
        name="Last Updated",
        device_class=SensorDeviceClass.TIMESTAMP,
        state_class=SensorStateClass.MEASUREMENT,
        entity_category=EntityCategory.DIAGNOSTIC,
    ),
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the platform from config entry."""

    path = entry.data[CONF_FILE_PATH]
    get_path = await hass.async_add_executor_job(pathlib.Path, path)
    fullpath = str(get_path.absolute())

    coordinator = FileSizeCoordinator(hass, fullpath)
    await coordinator.async_config_entry_first_refresh()

    async_add_entities(
        FilesizeEntity(description, fullpath, entry.entry_id, coordinator)
        for description in SENSOR_TYPES
    )


class FileSizeCoordinator(DataUpdateCoordinator):
    """Filesize coordinator."""

    def __init__(self, hass: HomeAssistant, path: str) -> None:
        """Initialize filesize coordinator."""
        super().__init__(
            hass,
            _LOGGER,
            name=DOMAIN,
            update_interval=timedelta(seconds=60),
        )
        self._path = path

    async def _async_update_data(self) -> dict[str, float | int | datetime]:
        """Fetch file information."""
        try:
            statinfo = await self.hass.async_add_executor_job(os.stat, self._path)
        except OSError as error:
            raise UpdateFailed(f"Can not retrieve file statistics {error}") from error

        size = statinfo.st_size
        last_updated = datetime.utcfromtimestamp(statinfo.st_mtime).replace(
            tzinfo=dt_util.UTC
        )

        _LOGGER.debug("size %s, last updated %s", size, last_updated)
        data: dict[str, int | float | datetime] = {
            "file": round(size / 1e6, 2),
            "bytes": size,
            "last_updated": last_updated,
        }

        return data


class FilesizeEntity(CoordinatorEntity[FileSizeCoordinator], SensorEntity):
    """Filesize sensor."""

    entity_description: SensorEntityDescription
    _attr_has_entity_name = True

    def __init__(
        self,
        description: SensorEntityDescription,
        path: str,
        entry_id: str,
        coordinator: FileSizeCoordinator,
    ) -> None:
        """Initialize the Filesize sensor."""
        super().__init__(coordinator)
        base_name = path.split("/")[-1]
        self._attr_name = description.name
        self._attr_unique_id = (
            entry_id if description.key == "file" else f"{entry_id}-{description.key}"
        )
        self.entity_description = description
        self._attr_device_info = DeviceInfo(
            entry_type=DeviceEntryType.SERVICE,
            identifiers={(DOMAIN, entry_id)},
            name=base_name,
        )
{'fraction_non_alphanumeric': 0.0867387592487194, 'fraction_numerical': 0.0019351166761525328, 'mean_word_length': 3.056325023084026, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2547662', 'n_tokens_mistral': 2542, 'n_tokens_neox': 2536, 'n_words': 526}