in this script, we monitor the clipboard and if there's a new text copied in it, the…
- User
in this script, we monitor the clipboard and if there's a new text copied in it, the script will automatically translate it using gpt. the translated text will either be shown on the shell, copied to clipboard, or keep it in a logs depending on the user's settings, the script also create a window and showed only the translated text in there. i want you make the window to also show the untranslated texts (raw from clipboard), separate the untranslated text’s textbox and the translated text’s textbox. make a button that makes the script to retranslate the text in the untranslated textbox if the text in there was edited. do not remove clipboard monitor. here’s the full script:
import time import pyperclip import openai import sys import keyboard import json import tkinter as tk import threading from tkinter import font, Menu
Set your OpenAI API key and base
openai.api_base = “” openai.api_key = “”
Toggleable features
PRINT_TRANSLATION = False COPY_TO_CLIPBOARD = False KEEP_LOGS = True
Initialize dictionary to store translated texts
translated_dict = {}
Define JSON file to store translations
jsonfile = “translations.json”
Load existing translations from JSON file
try: with open(jsonfile, “r”, encoding=“utf-8”) as f: translated_dict = json.load(f) except FileNotFoundError: pass
def translate_text(text_to_translate):
Sends the input text to GPT-3 with a simple translation prompt
prompt = f"Translate the following text:{text_to_translate}“
try: completion = openai.ChatCompletion.create( model=“gpt-3.5”, messages=[ { “role”: “user”, “content”: f”{prompt}“, } ], ) translated_text = ( completion[“choices”][0] .get(“message”) .get(“content”) .encode(“utf8”) .decode() )
except Exception as e: print(e, f"No credits found in key. Exiting…”) sys.exit()
return translated_text
def update_display(text): display.delete(1.0, tk.END) display.insert(tk.END, text)
def clipboard_monitor(): old_clipboard = “” exit_flag = False
while not exit_flag: new_clipboard = pyperclip.paste()
Compare new_clipboard with old_clipboard to detect changes
if new_clipboard != old_clipboard:
Update the old_clipboard variable
old_clipboard = new_clipboard
Check if the copied text has already been translated
if new_clipboard in translated_dict: translated_text = translated_dict[new_clipboard] else: translated_text = translate_text(new_clipboard)
Store the translation in the dictionary and the JSON file
translated_dict[new_clipboard] = translated_text with open(jsonfile, “w”, encoding=“utf-8”) as f: json.dump(translated_dict, f, ensure_ascii=False, indent=4)
if PRINT_TRANSLATION: print(f"\nTranslation:\n{translated_text}“)
- Assistant
- User
put the “Manual Retranslate” button inside the untranslated textbox in the lower left corner
- Assistant