Repository: yihong0618/bilingual_book_maker
File: book_maker/translator/chatgptapi_translator.py (Python)

Code before:
        while len(result_list) != plist_len and retry_count < 3:
            print(
                f"bug: {plist_len} -> {len(result_list)} : Number of paragraphs before and after translation"
            )
            sleep_dur = 6
            print(f"sleep for {sleep_dur}s and retry {retry_count+1} ...")
            time.sleep(sleep_dur)
            result_list = self.translate_and_split_lines(new_str)
            retry_count += 1

        state = "success"
        if len(result_list) != plist_len:
            state = "fail"

        if retry_count > 0:
            print(f"retry {state}")
            with open("buglog.txt", "a") as f:
                print(
                    f"retry {state}, count = {retry_count}",
                    file=f,
                )

        if len(result_list) != plist_len:
            newlist = new_str.split(sep)
            with open("buglog.txt", "a") as f:
                for i in range(0, len(newlist)):
                    print(newlist[i], file=f)
                    print(file=f)
                    if i < len(result_list):
                        print(result_list[i], file=f)
                        print(file=f)
                    print("=============================", file=f)
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

            print(
                f"bug: {plist_len} paragraphs of text translated into {len(result_list)} paragraphs"
            )
            print("continue")

        return result_list


Review comment (suggestion):
```suggestion
                for i in range(len(newlist)):
```

Code after:
        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:
            print(re.sub("\n{3,}", "\n\n", t_text))

        elapsed_time = time.time() - start_time
        # print(f"translation time: {elapsed_time:.1f}s")

        return t_text

    def translate_and_split_lines(self, text):
        result_str = self.translate(text, False)
        lines = result_str.split("\n")
        lines = [line.strip() for line in lines if line.strip() != ""]
        return lines

    def get_best_result_list(
        self, plist_len, new_str, sleep_dur, result_list, max_retries=15
    ):
        if len(result_list) == plist_len:
            return result_list, 0

        best_result_list = result_list
        retry_count = 0

        while retry_count < max_retries and len(result_list) != plist_len:
            print(
                f"bug: {plist_len} -> {len(result_list)} : Number of paragraphs before and after translation"
            )
            print(f"sleep for {sleep_dur}s and retry {retry_count+1} ...")
            time.sleep(sleep_dur)
            retry_count += 1