Advertisement
dergachoff

GPT Corrector as macOS Automator Service v0.2

Mar 18th, 2023
441
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
AppleScript 1.64 KB | Source Code | 1 0
  1. on run {input, parameters}
  2.     set originalText to input as string
  3.     set apiKey to "YOURGPTAPIKEY" -- Replace with your GPT-3.5 Turbo API key
  4.    
  5.     set pythonScript to "import json, sys, urllib.request
  6.  
  7. original_text = sys.argv[1]
  8. api_key = sys.argv[2]
  9.  
  10. prompt_template = 'Please rewrite the following text as English native, don’t put the answer in quotes, don’t return errors, just correct text: '
  11. prompt_text = prompt_template + original_text
  12.  
  13. api_endpoint = 'https://api.openai.com/v1/chat/completions'
  14.  
  15. request_headers = {
  16.    'Content-Type': 'application/json',
  17.    'Authorization': f'Bearer {api_key}'
  18. }
  19.  
  20. request_body = {
  21.    'model': 'gpt-3.5-turbo',
  22.    'messages': [{'role': 'user', 'content': prompt_text}],
  23.    'temperature': 0.7
  24. }
  25.  
  26. request_data = json.dumps(request_body).encode('utf-8')
  27.  
  28. req = urllib.request.Request(api_endpoint, data=request_data, headers=request_headers)
  29. try:
  30.    with urllib.request.urlopen(req) as response:
  31.        response_json = json.loads(response.read())
  32.        content = response_json['choices'][0]['message']['content'].strip()
  33.        print(content)
  34. except urllib.error.HTTPError as e:
  35.    error_message = e.read().decode('utf-8')
  36.    print('Error:', error_message, file=sys.stderr)
  37.    sys.exit(1)
  38. "
  39.    
  40.     set theResponse to ""
  41.    
  42.     try
  43.         set theResponse to (do shell script "/usr/bin/python3 -c " & (quoted form of pythonScript) & " " & (quoted form of originalText) & " " & apiKey)
  44.     on error errMsg
  45.         display dialog "Error processing JSON response: " & errMsg buttons {"OK"} default button 1
  46.         return
  47.     end try
  48.    
  49.     return theResponse
  50. end run
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement