Translate a Kirby website with ChatGPT

Hey everyone!

I started a little experiment that I wanted to share with you here. I asked ChatGPT to write me a script that will copy (on my Mac, it uses pbcopy and pbpaste commands to access the clipboard) the contents of each .en.txt file in a Kirby folder into the clipboard, along with a prompt to ask ChatGPT to translate it into a lanuage of my choice (say “fr”), and then wait for me to do it, copy the resulting translation into the clipboard, and then write the clipboard’s content into the .fr.txt file. It’s not perfect, but it works nicely for small files! :slight_smile: Feel free to experiment further with it!

#!/bin/zsh

# Ask for the language code
echo "Enter the language code (e.g., es for Spanish, fr for French): "
read lang_code

# Check if the language code is empty
if [[ -z "$lang_code" ]]; then
    echo "Language code cannot be empty."
    exit 1
fi

# Store all the .en.txt files in an array
files=($(find . -name '*.en.txt'))
total_files=${#files[@]}

# Initialize a counter for the current file's position
counter=1

# Process each file from the array
for file in "${files[@]}"; do
    # Check if the file contains keys without non-empty values
    if ! awk -F':' 'NF>1 && $2 !~ /^ *$/ { hasValue=1; exit } END { exit !hasValue }' "$file"; then
        echo "Skipping file $counter out of $total_files: $file (No non-empty values found)"
        counter=$((counter + 1))
        continue
    fi

    echo "Processing file $counter out of $total_files: $file..."

    # Fetch the content of the file into a variable
    content=$(cat "$file")

    # Create the instruction with the file content and copy to clipboard
    clipboard_content="Translate only the values (right side of the colon) in the provided content to $lang_code. Keep the keys (left side of the colon) untouched and retain the original structure. Specifically, do NOT translate values for the key 'Template'. Output the translated content as code:
\```
$content
\```
"
    echo "$clipboard_content" | pbcopy
    
    # Provide a prompt to the user
    echo "-------------------------------------"
    echo "The content of the file $file along with the instruction has been copied to the clipboard. Please paste it directly into ChatGPT."
    echo "-------------------------------------"

    echo "After translating, copy the results back to the clipboard, excluding the instruction. Press any key when ready..."
    read -k1 -s  # Wait for a single key press

    # Paste the translated content to the appropriate file
    pbpaste > "${file/.en.txt/.$lang_code.txt}"

    echo "Saved translated content to ${file/.en.txt/.$lang_code.txt}"
    
    # Increment the counter
    counter=$((counter + 1))
done

echo "Finished processing all files."

Of course, this could also work with ChatGPT CLI or so, but I wanted to start here. :slight_smile: