/
bioxakep
/
VoiceTrans
Обзор
Документация
Войти
/
bioxakep
/
VoiceTrans
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
utils_common.py
184 строки
7 KB
bioxakep
remove unused things
13 авг 2025, 23:33
13 авг 2025, 23:33
62ae8c4
Код
Авторство
О чём код?
import os import re from collections import Counter, defaultdict from dataclasses import dataclass from datetime import datetime from math import ceil from string import punctuation NO_PHONE_ABONENT = "NO_PHONE" @dataclass class SoundData: dt: datetime abonent: str contact: str duration: int def get_phones(file_name: str): phone_pattern = re.compile(r"\d{10,14}") phones = phone_pattern.findall(file_name) if len(phones) < 2: return None, None return phones[:2] def rename_sounds(billing_file_path: str, sounds_dir: str): if not os.path.exists(billing_file_path): raise FileExistsError("Файл с соединениями не найден.") if not os.path.exists(sounds_dir): raise FileExistsError("Директория со звуком не найдена.") billing_data = defaultdict(SoundData) with open(billing_file_path, "r") as billing_file: header = list( map(lambda x: x.strip('"'), billing_file.readline().strip("\n").split(";")) ) for line in billing_file: line_data = dict( zip( header, list(map(lambda x: x.strip('"'), line.strip("\n").split(";"))), ) ) bil_sound_id = line_data["Ид.записи"].lower() dt = datetime.strptime( line_data["Время начала соединения"], "%d.%m.%Y %H:%M:%S" ) abonent = line_data["Номер абонента"] or NO_PHONE_ABONENT contact = line_data["Номер контакта"] or NO_PHONE_ABONENT duration = line_data["Длительность, сек"] if bil_sound_id in billing_data.keys(): sound_data = billing_data.get(bil_sound_id) updated_data = False if ( sound_data.abonent == NO_PHONE_ABONENT and abonent != NO_PHONE_ABONENT ): sound_data.abonent = abonent updated_data = True if ( sound_data.contact == NO_PHONE_ABONENT and contact != NO_PHONE_ABONENT ): sound_data.contact = contact updated_data = True print(f"Exists rec {bil_sound_id}, updated: {updated_data}") continue print(f"New rec {bil_sound_id} = {dt}") billing_data[bil_sound_id] = SoundData( dt=dt, abonent=abonent, contact=contact, duration=duration ) for f in os.listdir(sounds_dir): wav_sound_id = f.split(".")[0].lower() sound_ext = f.split(".")[-1] sound_path: str = os.path.join(sounds_dir, f) if wav_sound_id not in billing_data.keys(): print(f"Файл со звуком {wav_sound_id} в билинге не найден.") continue rec_data = billing_data.get(wav_sound_id) dt_str = rec_data.dt.strftime("%Y_%m_%d_%H_%M_%S") new_file_name: str = ( f"{dt_str}_{rec_data.abonent}_{rec_data.contact}_{rec_data.duration}.{sound_ext}" ) new_sound_path: str = os.path.join(sounds_dir, new_file_name) if os.path.exists(new_sound_path): os.remove(new_sound_path) os.rename(sound_path, new_sound_path) print(f"Файл {f} переименован в {new_file_name}") yield new_sound_path, rec_data.abonent, rec_data.contact def humanize_time(time_seconds: int | float, clocks=True) -> str: time_seconds = ceil(time_seconds) if time_seconds == 0: return "0 секунд" if not clocks else "00:00:00" human_time = "" human_time_clocks = "" # Дни days = time_seconds // 86400 if days > 0: human_time = str(days) if days % 10 == 1 and days not in range(11, 20): human_time += " день, " elif days % 10 in [2, 3, 4]: human_time += f" дня, " else: human_time += f" дней, " if clocks: human_time_clocks = f"{days}d " # Часы hours = (time_seconds - days * 86400) // 3600 if hours > 0: human_time += str(hours) if hours % 10 == 1 and hours not in range(11, 20): human_time += " час, " elif hours % 10 in [2, 3, 4] and hours not in range(11, 20): human_time += f" часа, " else: human_time += f" часов, " human_time_clocks += ("0" if hours < 10 else f"") + str(hours) + ":" else: human_time_clocks += "00:" # Минуты minutes = (time_seconds - days * 86400 - hours * 3600) // 60 if minutes > 0: human_time += str(minutes) if minutes % 10 == 1 and minutes not in range(11, 20): human_time += " минута, " elif minutes % 10 in [2, 3, 4] and minutes not in range(11, 20): human_time += f" минуты, " else: human_time += f" минут, " human_time_clocks += ("0" if minutes < 10 else f"") + str(minutes) + ":" else: human_time_clocks += "00:" # Секунды seconds = time_seconds - days * 86400 - hours * 3600 - minutes * 60 if seconds > 0: human_time += str(seconds) if seconds % 10 == 1 and seconds not in range(11, 20): human_time += " секунда" elif seconds % 10 in [2, 3, 4] and seconds not in range(11, 20): human_time += f" секунды" else: human_time += f" секунд" human_time_clocks += ("0" if seconds < 10 else f"") + str(seconds) else: human_time_clocks += "00" return human_time_clocks if clocks else human_time def compare_texts(base_text, new_text): base_text = base_text.lower() new_text = new_text.lower() for p in punctuation: base_text = base_text.replace(p, "") new_text = new_text.replace(p, "") base_text_counter = Counter(base_text.split()) new_text_counter = Counter(new_text.split()) both_keys = list(set(base_text_counter.keys()) & set(new_text_counter.keys())) keys_argument = len(both_keys) / len( base_text_counter.keys() | new_text_counter.keys() ) words_argument = len(both_keys) for key in both_keys: if new_text_counter[key] != base_text_counter[key]: words_argument -= 1 if len(both_keys) > 0: words_argument = words_argument / len(both_keys) else: words_argument = 0 print( f"Сравнение: слова: {keys_argument * 100: 0.2f}", f"частота: {words_argument * 100: 0.2f}", f"общее: {keys_argument * words_argument * 100: 0.2f}", ) return keys_argument * 100 if __name__ == "__main__": print(humanize_time(13123123)) print(humanize_time(13123123, clocks=False))