trans (6896B)
1 #!/bin/sh 2 3 # ─── Configuração ───────────────────────────────────────────────────────────── 4 API_URL="https://translate.disroot.org" 5 API_KEY="" 6 DEFAULT_SOURCE="auto" 7 DEFAULT_TARGET="pt" 8 CONFIG_FILE="$HOME/.config/translate/config" 9 mkdir -p "$(dirname "$CONFIG_FILE")" 10 # ────────────────────────────────────────────────────────────────────────────── 11 12 usage() { 13 cat <<EOF 14 USO: 15 translate [opções] "texto" ["texto2" ...] 16 translate [opções] -f arquivo.txt 17 echo "texto" | translate [opções] 18 19 OPÇÕES: 20 -s LANG Idioma de origem (padrão: auto) 21 -t LANG Idioma de destino (padrão: $DEFAULT_TARGET) 22 -f ARQUIVO Traduz o conteúdo de um arquivo 23 -o ARQUIVO Salva resultado neste arquivo (só com -f por padrão é automático) 24 -l Lista os idiomas disponíveis 25 -k KEY API key para esta execução 26 -v Verbose: mostra idioma detectado 27 -h Esta ajuda 28 29 ARQUIVO: 30 Com -f, o resultado é salvo automaticamente como: 31 arquivo.LANG.txt (ex: doc.txt → doc.pt.txt) 32 Use -o para escolher outro nome de saída. 33 34 EXEMPLOS: 35 translate "Hello world" 36 translate "Good morning" "See you later" 37 translate -t en "Olá mundo" 38 translate -f relatorio.txt # salva relatorio.pt.txt 39 translate -f doc.txt -t en # salva doc.en.txt 40 translate -f doc.txt -o saida.txt # salva no nome escolhido 41 translate -v "Hello" # mostra idioma detectado 42 translate -l # lista idiomas 43 44 CONFIGURAÇÃO (~/.config/translate/config): 45 API_KEY=sua_chave 46 DEFAULT_TARGET=en 47 EOF 48 } 49 50 # ─── Carrega config ─────────────────────────────────────────────────────────── 51 [ -f "$CONFIG_FILE" ] && . "$CONFIG_FILE" 52 53 # ─── Parse de argumentos ────────────────────────────────────────────────────── 54 SOURCE="$DEFAULT_SOURCE" 55 TARGET="$DEFAULT_TARGET" 56 INPUT_FILE="" 57 OUTPUT_FILE="" 58 LIST_LANGS=0 59 VERBOSE=0 60 61 while getopts "s:t:f:o:k:lvh" opt; do 62 case "$opt" in 63 s) SOURCE="$OPTARG" ;; 64 t) TARGET="$OPTARG" ;; 65 f) INPUT_FILE="$OPTARG" ;; 66 o) OUTPUT_FILE="$OPTARG" ;; 67 k) API_KEY="$OPTARG" ;; 68 l) LIST_LANGS=1 ;; 69 v) VERBOSE=1 ;; 70 h) usage; exit 0 ;; 71 *) usage; exit 1 ;; 72 esac 73 done 74 shift $((OPTIND - 1)) 75 76 # ─── Verifica dependências ──────────────────────────────────────────────────── 77 for cmd in curl jq; do 78 command -v "$cmd" > /dev/null 2>&1 || { 79 printf 'Erro: "%s" não encontrado. Instale com: apk add %s\n' "$cmd" "$cmd" >&2 80 exit 1 81 } 82 done 83 84 # ─── Lista idiomas ──────────────────────────────────────────────────────────── 85 if [ "$LIST_LANGS" -eq 1 ]; then 86 printf 'Buscando idiomas em %s...\n' "$API_URL" >&2 87 response=$(curl -sf "$API_URL/languages") 88 [ $? -ne 0 ] || [ -z "$response" ] && { echo "Erro: não foi possível contatar $API_URL" >&2; exit 1; } 89 printf '\nCódigo Idioma\n────── ──────────────────────\n' 90 echo "$response" | jq -r '.[] | "\(.code)\t\(.name)"' | sort | \ 91 awk -F'\t' '{printf " %-6s %s\n", $1, $2}' 92 exit 0 93 fi 94 95 # ─── Função: traduz um bloco de texto, imprime resultado ───────────────────── 96 translate_text() { 97 _text="$1" 98 _payload=$(jq -n \ 99 --arg q "$_text" \ 100 --arg source "$SOURCE" \ 101 --arg target "$TARGET" \ 102 --arg key "$API_KEY" \ 103 '{q: $q, source: $source, target: $target, format: "html", api_key: $key}') 104 105 _response=$(curl -sf \ 106 -X POST "$API_URL/translate" \ 107 -H "Content-Type: application/json" \ 108 -d "$_payload") 109 110 [ $? -ne 0 ] || [ -z "$_response" ] && { echo "Erro: falha na conexão com $API_URL" >&2; return 1; } 111 112 if echo "$_response" | jq -e '.error' > /dev/null 2>&1; then 113 printf 'Erro da API: %s\n' "$(echo "$_response" | jq -r '.error')" >&2 114 return 1 115 fi 116 117 _translated=$(echo "$_response" | jq -r '.translatedText') 118 119 if [ "$VERBOSE" -eq 1 ]; then 120 _detected=$(echo "$_response" | jq -r '.detectedLanguage.language // empty') 121 _conf=$(echo "$_response" | jq -r '.detectedLanguage.confidence // empty') 122 if [ -n "$_detected" ]; then 123 _pct=$(awk "BEGIN{printf \"%.0f\", $_conf * 100}" 2>/dev/null || echo "?") 124 printf '[detectado: %s ~%s%%] ' "$_detected" "$_pct" >&2 125 fi 126 fi 127 128 printf '%s\n' "$_translated" 129 } 130 131 # ─── Função: deriva nome do arquivo de saída ────────────────────────────────── 132 derive_output() { 133 _in="$1" 134 _base="${_in%.*}" 135 _ext="${_in##*.}" 136 137 if [ "$_base" = "$_in" ]; then 138 printf '%s.%s' "$_in" "$TARGET" 139 else 140 printf '%s.%s.%s' "$_base" "$TARGET" "$_ext" 141 fi 142 } 143 144 # ─── Modo arquivo ───────────────────────────────────────────────────────────── 145 if [ -n "$INPUT_FILE" ]; then 146 [ -f "$INPUT_FILE" ] || { echo "Erro: arquivo '$INPUT_FILE' não encontrado." >&2; exit 1; } 147 148 if [ -z "$OUTPUT_FILE" ]; then 149 OUTPUT_FILE=$(derive_output "$INPUT_FILE") 150 fi 151 152 if [ -f "$OUTPUT_FILE" ]; then 153 printf 'Aviso: "%s" já existe e será sobrescrito.\n' "$OUTPUT_FILE" >&2 154 fi 155 156 printf 'Traduzindo "%s" (%s → %s)...\n' "$INPUT_FILE" "$SOURCE" "$TARGET" >&2 157 158 result=$(translate_text "$(cat "$INPUT_FILE")") || exit 1 159 printf '%s\n' "$result" > "$OUTPUT_FILE" 160 printf 'Salvo em: %s\n' "$OUTPUT_FILE" >&2 161 exit 0 162 fi 163 164 # ─── Modo texto / stdin ─────────────────────────────────────────────────────── 165 if [ $# -gt 0 ]; then 166 i=1 167 for arg in "$@"; do 168 [ $# -gt 1 ] && printf '[%d] ' "$i" >&2 169 translate_text "$arg" || exit 1 170 i=$((i + 1)) 171 done 172 elif [ ! -t 0 ]; then 173 translate_text "$(cat)" 174 else 175 echo "Erro: nenhum texto fornecido. Use -h para ajuda." >&2 176 exit 1 177 fi