Skip to content

Instantly share code, notes, and snippets.

@tos-kamiya
Last active September 4, 2024 04:21
Show Gist options
  • Save tos-kamiya/613fe2577796f0457d4d4ac59702a9a2 to your computer and use it in GitHub Desktop.
Save tos-kamiya/613fe2577796f0457d4d4ac59702a9a2 to your computer and use it in GitHub Desktop.
A simple text translator script
#!/bin/bash
# Function to display help message
function show_help() {
echo "Usage: $0 <language_code> [-p] <text_file_or_text>"
echo
echo "Arguments:"
echo " <language_code> The target language code (e.g., 'en' for English, 'ja' for Japanese)."
echo " <text_file_or_text> The path to the text file to be translated, or the text itself if -p is used. Use '-' to read from stdin."
echo
echo "Options:"
echo " -p Treat the remaining arguments as text to be translated."
echo " -h, --help Show this help message and exit."
exit 0
}
# Initialize variables
LANGUAGE_CODE=""
TEXT=""
IS_P_OPTION=false
# Check if help is requested
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
show_help
fi
# Parse the arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-p)
IS_P_OPTION=true
shift
;;
-h|--help)
show_help
;;
*)
if [ -z "$LANGUAGE_CODE" ]; then
LANGUAGE_CODE="$1"
else
if [ "$IS_P_OPTION" = true ]; then
TEXT="$TEXT $1"
else
TEXT_FILE="$1"
fi
fi
shift
;;
esac
done
# Trim leading and trailing whitespace from TEXT
TEXT=$(echo "$TEXT" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
# Validate the input
if [ -z "$LANGUAGE_CODE" ]; then
echo "Error: Missing language code."
echo "Try '$0 --help' for more information."
exit 1
fi
if [ "$IS_P_OPTION" = false ] && [ -z "$TEXT_FILE" ]; then
echo "Error: Missing text file or text."
echo "Try '$0 --help' for more information."
exit 1
fi
# Read the text content if -p is not used
if [ "$IS_P_OPTION" = false ]; then
if [ "$TEXT_FILE" = "-" ]; then
# Read from stdin
TEXT=$(cat)
else
# Read from the specified file
if [ ! -f "$TEXT_FILE" ]; then
echo "Error: File '$TEXT_FILE' not found."
exit 1
fi
TEXT=$(cat "$TEXT_FILE")
fi
fi
# Construct the prompt for ollama
PROMPT="Please translate the following text to \`$LANGUAGE_CODE\` and provide only the translated text without any additional explanation.\n---\n$TEXT"
# Run the ollama command and output the result
ollama run qwen2 "$PROMPT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment