Skip to content

Instantly share code, notes, and snippets.

@newmen
Created May 13, 2025 08:36
Show Gist options
  • Save newmen/eb91e7f0864057d45355f5b5014662b3 to your computer and use it in GitHub Desktop.
Save newmen/eb91e7f0864057d45355f5b5014662b3 to your computer and use it in GitHub Desktop.
Считает количество токенов в переданном файле
import tiktoken
import sys
import os
def count_tokens(file_path):
try:
# Проверяем, существует ли файл
if not os.path.exists(file_path):
print(f"Ошибка: Файл '{file_path}' не найден.")
return
# Читаем содержимое файла
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Инициализируем токенизатор (cl100k_base используется в большинстве современных моделей)
encoding = tiktoken.get_encoding("cl100k_base")
# Подсчитываем токены
tokens = encoding.encode(content)
token_count = len(tokens)
print(f"Количество токенов в файле '{file_path}': {token_count}")
except UnicodeDecodeError:
print("Ошибка: Не удалось декодировать файл. Убедитесь, что файл в формате UTF-8.")
except Exception as e:
print(f"Произошла ошибка: {str(e)}")
def main():
# Проверяем, передан ли аргумент
if len(sys.argv) != 2:
print("Использование: python count_tokens.py <путь_к_файлу>")
sys.exit(1)
file_path = sys.argv[1]
count_tokens(file_path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment