0

Runnning Ventura 13.4 on Intel.

I wrote a Python script that replaces text by the translated version. It looks like this:

    import openai
import sys

# Read the API key
openai.api_key = 'Here-is-my-API-Key'

# Get the selected text
selected_text = sys.stdin.read()

# Call the OpenAI API to translate the text
model = "gpt-3.5-turbo"
language = "German"
response = openai.ChatCompletion.create(
    model=model,
    messages=[
        {
            "role": "user",
            "content": f"Translate the following text to {language} without changing the formatting: {selected_text}",
        }
    ]
)

# Grabs the response from the API and strips it of leading/trailing newlines
translated_text = response["choices"][0]["message"]["content"].strip()

# Replace the selected text with the translated text
sys.stdout.write(translated_text)

It works perfectly in Automator, if I test it. It runs as expected, if I run it via service when I am writing a text in Apple Mail. It also works inside Terminal. But I can not get it to work in any other program (e.g. TextEdit or Word.) outside these two. I tried giving Full disk access to Automator. I also tried this setting my Path in .zshenv:

Automator run shell script does not know my PATH?

Nevertheless, If I try to run it in TextEdit I always get something like this:

The action “Run Shell Script” encountered an error: “Traceback (most
recent call last): File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connection.py",
line 200, in _new_conn sock = connection.create_connection(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/util/connection.py",
line 85, in create_connection raise err File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/util/connection.py",
line 73, in create_connection sock.connect(sa) OSError: [Errno 9] Bad
file descriptor

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py",
line 790, in urlopen response = self._make_request(
^^^^^^^^^^^^^^^^^^^ File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py",
line 491, in _make_request raise new_e File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py",
line 467, in _make_request self._validate_conn(conn) File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py",
line 1092, in _validate_conn conn.connect() File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connection.py",
line 604, in connect self.sock = sock = self._new_conn()
^^^^^^^^^^^^^^^^ File
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connection.py",
line 215, in _new_conn raise NewConnectionError(
urllib3.exceptions.NewConnectionError:
<urllib3.connection.HTTPSConnection object at 0x109d99090>: Failed to
establish a new connection: [Errno 9] Bad file descriptor

Also If I am trying to run another script using zsh only the situation is similar with this error:

The action “Run Shell Script” encountered an error: “gawk: /dev/fd/63:4045: fatal: cannot open two way pipe `/inet/tcp/0/translate.googleapis.com/80' for input/output: Bad file descriptor”

Also tried running it via Apple script. No success. Any advice, what else I could try?

5
  • You probably want to send keystrokes to those apps vs just writing to stdout. An example can be found here. Commented Jul 10, 2023 at 15:41
  • Thanks. I am selecting the text and then using the right click menu though, not a shortcut.
    – phillip
    Commented Jul 10, 2023 at 15:49
  • The link I gave you is an eample of sending keystrokes. Commented Jul 10, 2023 at 20:17
  • I see. Sorry, i think I missed the point in the first place, but I believe I understand vaguely what you are pointing at. I will dig into it. Thanks!
    – phillip
    Commented Jul 10, 2023 at 20:30
  • Thanks Marc, with your hint I could resolve the problem. I will post the answer here.
    – phillip
    Commented Jul 23, 2023 at 16:07

1 Answer 1

1

This is how I got it to work as intended:

  1. Install Fastscripts
  2. Set up an Applescript, which looks like this (replace the paths!):
on run
    -- Copy the currently selected text to the clipboard
    tell application "System Events"
        keystroke "c" using {command down}
        delay 0.5 -- Wait for the data to be available
    end tell

    -- Get the selected text from the clipboard
    set selectedText to (the clipboard as text)

    -- Call the Python script and pass the selected text
    set translatedText to do shell script "echo " & quoted form of   > selectedText & " |
        /PATH/TO/YOUR/python3
        /PATH/TO/MY/SCRIPT/DK_openAi.py"

    -- Put the translated text back into the clipboard
    set the clipboard to translatedText

    -- Paste the translated text
    tell application "System Events"
        keystroke "v" using {command down}
    end tell
end run
  1. Set up DK_openAi.py that looks like this:
import openai
import sys
    
# Read the API key
openai.api_key = 'YOUR-API-KEY'
    
# Get the selected text
selected_text = sys.stdin.read().strip()
    
# Call the OpenAI API to translate the text
model = "gpt-3.5-turbo"
language = "Danish"
response = openai.ChatCompletion.create(
    model=model,
    messages=[
        {
            "role": "user",
            "content": f"Translate the following text to {language} without changing the formatting: {selected_text}",
        }
    ]
)

# Grabs the response from the API and strips it of leading/trailing newlines
translated_text = response["choices"][0]["message"]["content"].strip()
    
# Replace the selected text with the translated text
print(translated_text, end="")
  1. Set-up shortcuts to run the apple scripts via Fastscripts

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .