-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_reduction.py
More file actions
38 lines (32 loc) · 1.32 KB
/
Copy pathcontext_reduction.py
File metadata and controls
38 lines (32 loc) · 1.32 KB
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
from transformers import OpenAIGPTTokenizer
# Initialize the (static) tokenizer
tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
def get_token_count(text: str) -> int:
"""
Get the length of a text in (GPT) tokens
:param text: The text to count the tokens
:return: The number of tokens
"""
token_count = len(tokenizer.tokenize(text))
return token_count
def approximate_truncate_to_token_count(text: str, token_count: int) -> str:
"""
Get text approximately in the token count length
:param token_count: Length of text in tokens. The returned text will have this size +- 10%
:param text: The text to count the tokens
:return: The number of tokens
"""
# First approximation
token_count = int(token_count * 0.95)
char_length = int(token_count * 10)
# maximum iterations to 10 to avoid endless loop
for i in range(0, 10):
truncated_text = text[:char_length]
current_token_count = get_token_count(truncated_text)
# Break if variance < 5%
if token_count * 1.05 > current_token_count > token_count * 0.95:
break
# Calculate correction factor; avoid division by zero
correction_factor = token_count / max(current_token_count, 1)
char_length = int(char_length * correction_factor)
return truncated_text