Skip to content

Commit

Permalink
improve exception
Browse files Browse the repository at this point in the history
  • Loading branch information
hleft committed Mar 15, 2023
1 parent c859c69 commit 780147b
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions book_maker/translator/chatgptapi_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ def get_translation(self, text):
try:
completion = self.create_chat_completion(text)
except Exception:
if len(completion["choices"]) == 0:
raise
if completion["choices"][0]["finish_reason"] != "length":
raise

Expand Down Expand Up @@ -108,18 +110,26 @@ def translate(self, text, needprint=True):
if needprint:
print(re.sub("\n{3,}", "\n\n", text))

try:
t_text = self.get_translation(text)
except Exception as e:
# todo: better sleep time? why sleep alawys about key_len
# 1. openai server error or own network interruption, sleep for a fixed time
# 2. an apikey has no money or reach limit, don’t sleep, just replace it with another apikey
# 3. all apikey reach limit, then use current sleep
sleep_time = int(60 / self.key_len)
print(e, f"will sleep {sleep_time} seconds")
time.sleep(sleep_time)

t_text = self.get_translation(text)
attempt_count = 0
max_attempts = 3
t_text = ""

while attempt_count < max_attempts:
try:
t_text = self.get_translation(text)
break
except Exception as e:
# todo: better sleep time? why sleep alawys about key_len
# 1. openai server error or own network interruption, sleep for a fixed time
# 2. an apikey has no money or reach limit, don’t sleep, just replace it with another apikey
# 3. all apikey reach limit, then use current sleep
sleep_time = int(60 / self.key_len)
print(e, f"will sleep {sleep_time} seconds")
time.sleep(sleep_time)
attempt_count += 1
if attempt_count == max_attempts:
print(f"Get {attempt_count} consecutive exceptions")
raise

# todo: Determine whether to print according to the cli option
if needprint:
Expand Down

0 comments on commit 780147b

Please sign in to comment.