Skip to content

Instantly share code, notes, and snippets.

Last active February 2, 2024 07:57
Show Gist options
  • Save willwade/f5d9a2c30906e33fb404437b870ef89a to your computer and use it in GitHub Desktop.
Save willwade/f5d9a2c30906e33fb404437b870ef89a to your computer and use it in GitHub Desktop.
AutoCorrect using OpenAI
from pynput import keyboard, mouse
from pynput.keyboard import Key, Controller as KeyboardController
import requests
import clipman
keyboard_controller = KeyboardController()
text_buffer = []
def correct_text(text):
api_url = ""
api_key = "sk-keyhere" # Replace with your actual API key
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
data = {
"model": "gpt-3.5-turbo",
"messages": [
"role": "system",
"content": "Autocorrect sentence that may have typos in it and capitalization errors as well as bad spacing between words. You will not be verbose. Just return the corrected text if it can be"
"role": "user",
"content": text
response =, json=data, headers=headers)
if response.status_code == 200:
assistant_response = response.json()['choices'][0]['message']['content'].strip()
clipman.set(assistant_response) # Copy corrected text to clipboard
print(f"Failed to correct text. HTTP Status Code: {response.status_code}")
def replace_text(length_of_text):
# Simulate Shift + Left Arrow to select the text
with keyboard_controller.pressed(Key.shift):
for _ in range(length_of_text):
# Simulate Ctrl+V to paste the corrected text
def on_press(key):
# Attempt to capture printable characters
if hasattr(key, 'char') and key.char is not None:
elif key ==
# Process text upon pressing space, for simplicity
sentence = ''.join(text_buffer)
if sentence.endswith('.'):
text_buffer.clear() # Clear the buffer after processing
except Exception as e:
print(f"Error processing key press: {e}")
with keyboard.Listener(on_press=on_press) as listener:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment