-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.py
134 lines (101 loc) · 4.77 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import os
import sys
import json
import requests
import re
from num2words import num2words
def clamp(value, min_value, max_value):
return max(min_value, min(value, max_value))
def load_text_from_file(filename):
"""
Загружает текст из файла, расположенного в папке 'Crazy'.
:param filename: Имя файла или относительный путь к файлу.
:return: Содержимое файла в виде строки. Если файл не найден, возвращает пустую строку.
"""
print(f"Загружаю {filename}")
try:
# Получаем полный путь к файлу
filepath = get_resource_path(filename)
# Если путь не найден, возвращаем пустую строку
if filepath is None:
return ""
# Убедимся, что путь в правильном формате
filepath = os.path.normpath(filepath)
# Проверяем, существует ли файл
if not os.path.exists(filepath):
print(f"Файл не найден: {filepath}")
return ""
# Читаем файл
with open(filepath, 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
print(f"Ошибка при чтении файла {filename}: {e}")
return ""
def get_resource_path(filename):
"""
Возвращает полный путь к файлу в папке 'Crazy'.
:param filename: Имя файла или относительный путь к файлу.
:return: Полный путь к файлу или None, если папка 'Crazy' не найдена.
"""
# Определяем базовый путь
if getattr(sys, 'frozen', False):
# Если программа "заморожена" (например, с помощью PyInstaller)
base_path = os.path.dirname(sys.executable)
else:
# Если программа запущена как скрипт
base_path = os.path.dirname(__file__)
# Формируем путь к папке
promts_path = os.path.join(base_path)
# Проверяем, существует ли папка 'Crazy'
if not os.path.isdir(promts_path):
print(f"Ошибка: Папка не найдена по пути: {promts_path}")
return None
# Возвращаем полный путь к файлу
return os.path.join(promts_path, filename)
def load_json_file(filepath):
try:
with open(filepath, "r", encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
print(f"Файл {filepath} не найден.")
return {}
def save_combined_messages(combined_messages, output_folder="SavedMessages"):
os.makedirs(output_folder, exist_ok=True)
file_name = f"combined_messages.json"
file_path = os.path.join(output_folder, file_name)
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(combined_messages, file, ensure_ascii=False, indent=4)
print(f"Сообщения сохранены в файл: {file_path}")
def calculate_cost_for_combined_messages(self, combined_messages, cost_input_per_1000):
token_count = self.count_tokens(combined_messages)
cost = (token_count / 1000) * cost_input_per_1000
return f"Токенов {token_count} Цена {cost}"
def count_tokens(self, messages):
return sum(
len(self.tokenizer.encode(msg["content"])) for msg in messages if isinstance(msg, dict) and "content" in msg)
def SH(s, placeholder="***", percent=0.20):
"""
Сокращает строку, оставляя % символов в начале и % в конце.
Средняя часть заменяется на placeholder.
:param percent:
:param s: Исходная строка.
:param placeholder: Заполнитель для скрытой части строки (по умолчанию "***").
:return: Сокращенная строка.
"""
if not s:
return s
length = len(s)
# Вычисляем 20% от длины строки
visible_length = max(1, int(length * percent)) # Минимум 1 символ
# Берем начало и конец строки
start = s[:visible_length]
end = s[-visible_length:]
# Собираем результат
return f"{start}{placeholder}{end}"
#Замена чисел на слова в русском тексте
def replace_numbers_with_words(text):
numbers = re.findall(r'\d+', text)
for number in numbers:
word = num2words(int(number), lang='ru')
text = text.replace(number, word)
return text