Пример #1
0
def check_phone(phone):
    if not isinstance(phone, str):
        if 10_000_000_000 <= phone <= 99_999_999_999:
            phone = str(phone)
        else:
            ERR_LOG.error(f"Ошибка в 'номере телефона': '{phone}'")
            raise TypeError("A mistake was made in the phone number")
Пример #2
0
    def first_name(self, new_first_name):
        new_first_name = check.check_first_name(new_first_name)

        if check.is_typo_in_name(self._first_name, new_first_name):
            INFO_LOG.info(f"Изменено имя на '{new_first_name}' у пациента {self}.")
            self._first_name = new_first_name
        else:
            ERR_LOG.error("Не распознана опечатка в first_name.")
            raise AttributeError("A typo is not found")
Пример #3
0
    def document_type(self, new_doc_type):
        new_doc_type = check.check_doc_type(new_doc_type)

        if new_doc_type is self._document[0]:
            INFO_LOG.info(f"Тип документа не изменился у пациента {self}.")
        elif new_doc_type is not self._document[0]:
            INFO_LOG.info(f"Изменён тип документа у пациента {self}.")
            self._document = (new_doc_type, NotImplemented)
        else:
            ERR_LOG.error(f"В типе документа оказалось '{new_doc_type}'")
            raise ValueError("A mistake was made in document type")
Пример #4
0
def check_birth_date(birth_date):
    if isinstance(birth_date, str):
        if not any(symbol.isalpha() for symbol in birth_date):
            result = str(pd.to_datetime(birth_date).date())
            return result
        else:
            ERR_LOG.error(f"Ошибка в 'дате рождения': '{birth_date}'")
            raise ValueError("Invalid Date of Birth")
    else:
        ERR_LOG.error(f"Ошибка в 'дате рождения': '{birth_date}'")
        raise TypeError("A mistake was made in the Date of Birth")
Пример #5
0
    def document_id(self, new_id):
        new_id = check.check_doc_id(self._document[0], new_id)

        if self._document[1] is NotImplemented:
            INFO_LOG.info(f"Был заполнен номер документа: '{new_id}' у пациента {self}.")
            self._document = (self._document[0], new_id)
        elif check.is_typo_in_doc_id(self._document[1], new_id):
            INFO_LOG.info(f"Изменёна опечатка в номере документа на '{new_id}' у пациента {self}.")
            self._document = (self._document[0], new_id)
        else:
            ERR_LOG.error("Не распознана опечатка в document id.")
            raise AttributeError("A typo is not found")
Пример #6
0
def check_doc_id(doc_type, doc_id):
    if isinstance(doc_id, str):
        doc_id = ''.join(filter(str.isdigit, doc_id))

        if doc_type and len(doc_id) == 9:
            return f"{doc_id[:2]} {doc_id[2:]}"
        elif doc_type is None and len(doc_id) == 10:
            return f"{doc_id[:4]} {doc_id[4:]}"
        elif not doc_type and len(doc_id) == 10:
            return f"{doc_id[:2]} {doc_id[2:4]} {doc_id[4:]}"
        else:
            ERR_LOG.error(f"Ошибка в 'номере документа': '{doc_id}'")
            raise ValueError("Invalid doc id")

    ERR_LOG.error(f"Ошибка в doc_id: '{doc_id}'")
    raise TypeError("A mistake was made in doc number")
Пример #7
0
def check_doc_type(doc_type):
    if isinstance(doc_type, str):
        doc_type = doc_type.lower()
        variants = ["паспорт российский", "заграничный паспорт",
                    "водительское удостоверение, права"]

        result = process.extractOne(doc_type, variants)

        if result[1] < 40:
            doc_type = eng_to_rus(doc_type)
            result = process.extractOne(doc_type, variants)
            if result[1] < 40:
                ERR_LOG.error(f"Низкий показатель: {result[1]}% (Тип документа: '{doc_type}')")
                raise ValueError("Invalid doc type")
        elif result[1] < 60:
            INFO_LOG.warning(f"Низкий показатель: {result[1]}% (Тип документа: '{doc_type}')")

        return get_good_doc_type(result[0])
    else:
        ERR_LOG.error(f"Ошибка в doc_type: '{doc_type}'")
        raise TypeError("A mistake was made in the doc type")
Пример #8
0
    def get_statistical_chart(self):
        num_of_infected = 0
        num_of_recoveries = 0
        num_of_deaths = 0

        for patient in self:
            if patient._status is None:
                num_of_infected += 1
            elif patient._status is True:
                num_of_recoveries += 1
            elif patient._status is False:
                num_of_deaths += 1
            else:
                ERR_LOG.error(f"Неверный статус: {patient}")
                raise ValueError(f"Invalid Patient._status: {patient}")

        values = [num_of_infected, num_of_recoveries, num_of_deaths]
        in_total = num_of_infected + num_of_recoveries + num_of_deaths
        values = [val / in_total * 100 for val in values]

        labels = ["Заражено", "Выздоровело", "Умерло"]
        explode = (0, 0, 0.07)
        fig, ax = plt.subplots()

        ax.pie(values, labels=labels, autopct='%1.1f%%', shadow=True, explode=explode,
               wedgeprops={'lw': 1, 'ls': '--', 'edgecolor': 'k'}, labeldistance=None,
               colors=['darkred', 'forestgreen', 'dimgrey'])

        ax.set_facecolor('oldlace')
        fig.set_figwidth(7.5)
        fig.set_figheight(6)
        fig.set_facecolor('blanchedalmond')

        ax.axis('equal')
        plt.legend()
        plt.title("Статистика по вирусу COVID-19", fontdict={'fontsize': 16})

        fig.savefig("result/chart_covid_19")
Пример #9
0
def check_first_name(first_name):
    if isinstance(first_name, str):
        if first_name.isalpha():
            first_name = first_name.capitalize()

            page = requests.get(f"http://imenator.ru/search/?text={first_name}")
            soup = BeautifulSoup(page.content, "html.parser")
            all_links = soup.find_all(name='a')

            for link in all_links:
                if link.text == first_name:
                    # Commented to pass the tests.
                    # INFO_LOG.info(f"Имя '{first_name}' было найдено в БД!")
                    return first_name
            else:
                INFO_LOG.warning(f"Имя '{first_name}' не было найдено в БД!")
                return first_name
        else:
            ERR_LOG.error(f"Ошибка в 'имени': '{first_name}'")
            raise ValueError("The first name contains invalid characters")
    else:
        ERR_LOG.error(f"Ошибка в 'имени': '{first_name}'")
        raise TypeError("A mistake was made in the first name")
Пример #10
0
def check_last_name(last_name):
    if isinstance(last_name, str):
        if last_name.isalpha():
            last_name = last_name.capitalize()

            page = requests.get(f"http://www.ufolog.ru/names/order/{last_name.lower()}")

            soup = BeautifulSoup(page.content, "html.parser")
            found = soup.find_all(name='span', attrs={'class': 'version-number'})

            if found:
                # Commented to pass the tests.
                # INFO_LOG.info(f"Фамилия '{last_name}' была найдена в БД!")
                pass
            else:
                INFO_LOG.warning(f"Фамилия '{last_name}' не была найдена в БД!")

            return last_name
        else:
            ERR_LOG.error(f"Ошибка в 'фамилии': '{last_name}'")
            raise ValueError("The last name contains invalid characters")
    else:
        ERR_LOG.error(f"Ошибка в 'фамилии': '{last_name}'")
        raise TypeError("A mistake was made in the last name")
Пример #11
0
def convert_phone_number(num: str):
    if len(num) == 11:
        return f"+7({num[1:4]}){num[4:7]}-{num[7:9]}-{num[9:11]}"
    else:
        ERR_LOG.error(f"Ошибка в 'номере телефона': '{num}'")
        raise ValueError("Invalid phone number")