<commit_before>import csv
import re

from libqtile.widget import base

sensors_mapping = {
    'fan_speed': 'fan.speed',
    'perf': 'pstate',
    'temp': 'temperature.gpu',
}


class NvidiaSensors(base.ThreadPoolText):
    """Displays temperature, fan speed and performance level Nvidia GPU."""

    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        (
            'format', '{temp}°C',
            'Display string format. Three options available:  '
            '``{temp}`` - temperature, ``{fan_speed}`` and ``{perf}`` - '
            'performance level'
        ),
        ('foreground_alert', 'ff0000', 'Foreground colour alert'),
        (
            'gpu_bus_id', '',
            "GPU's Bus ID, ex: ``01:00.0``. If leave empty will display all "
            "available GPU's"
        ),
        ('update_interval', 2, 'Update interval in seconds.'),
        (
            'threshold',
            70,
            'If the current temperature value is above, '
            'then change to foreground_alert colour'
        ),
    ]

    def __init__(self, **config):
        base.ThreadPoolText.__init__(self, '', **config)
        self.add_defaults(NvidiaSensors.defaults)
        self.foreground_normal = self.foreground

    def _get_sensors_data(self, command):
        return csv.reader(
            self.call_process(
                command, shell=True
            ).strip().replace(' ', '').split('\n')
        )

    def poll(self):
        sensors = [sensor for sensor in re.findall('{(.+?)}', self.format)]
        bus_id = f'-i {self.gpu_bus_id}' if self.gpu_bus_id else ''
        command = 'nvidia-smi {} --query-gpu={} --format=csv,noheader'.format(
            bus_id, ",".join(sensors_mapping[sensor] for sensor in sensors)
        )
        sensors_data = [
            dict(zip(sensors, gpu))
            for gpu in self._get_sensors_data(command)
        ]
        for gpu in sensors_data:
            if gpu.get('temp') and int(gpu['temp']) > self.threshold:
                self.foreground = self.foreground_alert
        return ' - '.join([self.format.format(**gpu) for gpu in sensors_data])<commit_msg>NvidiaSensors: Add check for correct sensors names in format string, small refactoring<commit_after>import csv
import re

from libqtile.widget import base

sensors_mapping = {
    'fan_speed': 'fan.speed',
    'perf': 'pstate',
    'temp': 'temperature.gpu',
}


def _all_sensors_names_correct(sensors):
    return all(map(lambda x: x in sensors_mapping, sensors))


class NvidiaSensors(base.ThreadPoolText):
    """Displays temperature, fan speed and performance level Nvidia GPU."""

    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        (
            'format', '{temp}°C',
            'Display string format. Three options available:  '
            '``{temp}`` - temperature, ``{fan_speed}`` and ``{perf}`` - '
            'performance level'
        ),
        ('foreground_alert', 'ff0000', 'Foreground colour alert'),
        (
            'gpu_bus_id', '',
            "GPU's Bus ID, ex: ``01:00.0``. If leave empty will display all "
            "available GPU's"
        ),
        ('update_interval', 2, 'Update interval in seconds.'),
        (
            'threshold',
            70,
            'If the current temperature value is above, '
            'then change to foreground_alert colour'
        ),
    ]

    def __init__(self, **config):
        base.ThreadPoolText.__init__(self, '', **config)
        self.add_defaults(NvidiaSensors.defaults)
        self.foreground_normal = self.foreground

    def _get_sensors_data(self, command):
        return csv.reader(
            self.call_process(
                command, shell=True
            ).strip().replace(' ', '').split('\n')
        )

    def _parse_format_string(self):
        return {sensor for sensor in re.findall('{(.+?)}', self.format)}

    def poll(self):
        sensors = self._parse_format_string()
        if not _all_sensors_names_correct(sensors):
            return 'Wrong sensor name'
        bus_id = f'-i {self.gpu_bus_id}' if self.gpu_bus_id else ''
        command = 'nvidia-smi {} --query-gpu={} --format=csv,noheader'.format(
            bus_id, ",".join(sensors_mapping[sensor] for sensor in sensors)
        )
        try:
            sensors_data = [
                dict(zip(sensors, gpu))
                for gpu in self._get_sensors_data(command)
            ]
            for gpu in sensors_data:
                if gpu.get('temp') and int(gpu['temp']) > self.threshold:
                    self.foreground = self.foreground_alert
            return ' - '.join(
                [self.format.format(**gpu) for gpu in sensors_data]
            )
        except Exception:
            return None
{'fraction_non_alphanumeric': 0.12874816523380164, 'fraction_numerical': 0.0050325015726567415, 'mean_word_length': 2.0994152046783627, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, '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': '5879519', 'n_tokens_mistral': 1440, 'n_tokens_neox': 1364, 'n_words': 336}