-
Notifications
You must be signed in to change notification settings - Fork 3
/
count_tokens.py
55 lines (45 loc) · 1.73 KB
/
count_tokens.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
"""
python count_tokens.py
Recursively scan a directory and count the tokens in each file
"""
# ******************************************************************************************************************120
# standard imports
import os
# 3rd party imports
import click
import tiktoken
# custom imports
@click.command()
@click.option('-d', '--directory', type=str, required=True, help='Directory')
@click.option('-r', '--reverse', type=bool, required=False, default=False,
help='String sort ascheding or descending')
def main(directory: str,
reverse: bool) -> None: # pylint: disable=unused-argument
"""Main Function"""
embeddings = tiktoken.encoding_for_model("gpt-4o")
process_dir(directory,reverse,embeddings)
def process_dir(directory:str, reverse: bool, embeddings):
"""Process Directory"""
dir_count = 0
dir_tokens = 0
assert os.path.isdir(directory)
list_files = os.listdir(directory)
list_files.sort(reverse=reverse)
for fn in list_files:
fqp = os.path.join(directory,fn)
if os.path.isfile(fqp):
with open(fqp,mode='r',encoding='utf8') as file_in:
tokens = len(embeddings.encode(file_in.read()))
dir_tokens = dir_tokens + tokens
dir_count = dir_count + 1
elif os.path.isdir(fqp):
sub_tokens,sub_count = process_dir(fqp,reverse,embeddings)
dir_tokens=dir_tokens+sub_tokens
dir_count=dir_count + sub_count
else:
print(fqp)
raise RuntimeError("WTF?")
print(f'tokens: {dir_tokens:>20} count: {dir_count:>10} {directory}')
return dir_tokens,dir_count
if __name__ == '__main__':
main() # pylint: disable=no-value-for-parameter