Código de Python - Traductor de texto.

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Traductor de texto.gráfica de visualizaciones


Python

Actualizado el 11 de Noviembre del 2020 por Antonio (75 códigos) (Publicado el 24 de Junio del 2020)
12.750 visualizaciones desde el 24 de Junio del 2020
Aplicación para traducir un texto a otro idioma (seleccionado por el usuario) de un listado de idiomas disponibles, pudiendo oír dicha traducción. También ofrece la posibilidad de copiar texto desde otro documento.

trad

Requerimientos

Lenguaje: Python
Librerías: tkinter, time, pyperclip,threading,playsound,gtts,os,googletrans.

1.2
estrellaestrellaestrellaestrellaestrella(3)

Actualizado el 12 de Noviembre del 2020 (Publicado el 24 de Junio del 2020)gráfica de visualizaciones de la versión: 1.2
12.751 visualizaciones desde el 24 de Junio del 2020
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.scrolledtext as scrolledtext
from tkinter import messagebox
from tkinter import ttk, filedialog
import pyperclip
import time
import threading
from playsound import playsound
import gtts
import os
from googletrans import Translator
 
langs ={'af': 'Afrikaans', 'sq': 'Albanian', 'ar': 'Arabic', 'hy': 'Armenian', 'bn': 'Bengali', 'bs': 'Bosnian', 'ca': 'Catalan', 'hr': 'Croatian',
        'cs': 'Czech', 'da': 'Danish', 'nl': 'Dutch', 'en': 'English', 'eo': 'Esperanto', 'et': 'Estonian', 'tl': 'Filipino','fi': 'Finnish','fr': 'French',
        'de': 'German', 'el': 'Greek', 'gu': 'Gujarati', 'hi': 'Hindi', 'hu': 'Hungarian', 'is': 'Icelandic', 'id': 'Indonesian', 'it': 'Italian',
        'ja': 'Japanese', 'jw': 'Javanese', 'kn': 'Kannada', 'km': 'Khmer', 'ko': 'Korean', 'la': 'Latin', 'lv': 'Latvian', 'mk': 'Macedonian',
        'ml': 'Malayalam', 'mr': 'Marathi', 'my': 'Myanmar (Burmese)', 'ne': 'Nepali', 'no': 'Norwegian', 'pl': 'Polish',
        'pt': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian', 'sr': 'Serbian', 'si': 'Sinhala', 'sk': 'Slovak', 'es': 'Spanish', 'su': 'Sundanese',
        'sw': 'Swahili', 'sv': 'Swedish', 'ta': 'Tamil', 'te': 'Telugu', 'th': 'Thai', 'tr': 'Turkish', 'uk': 'Ukrainian', 'ur': 'Urdu',
        'vi': 'Vietnamese', 'cy': 'Welsh', 'zh-cn': 'Chinese (Mandarin/China)', 'zh-tw': 'Chinese (Mandarin/Taiwan)'}
 
 
class traductor():
    def __init__(self):
        self.ventana = Tk()
        self.ventana.title("Traductor")
        self.ventana['bg'] = 'light blue'
        self.ventana.geometry('1101x490')
        self.translator = Translator()
        self.texto = ""
        self.traduc = ""
        self.finished = True
        self.copia = ""
 
        self.display1 = scrolledtext.ScrolledText(self.ventana,width=55,height=18)
        self.display1.place(x=30,y=77)
        self.display2 = scrolledtext.ScrolledText(self.ventana,width=55,height=18)
        self.display2.place(x=610,y=77)
        self.btnListen1 = Button(self.ventana,text='ESCUCHAR',bg='green',fg='white',width=64,command=self.inicia_detect)
        self.btnListen1.place(x=30,y=373)
        self.btnListen2 = Button(self.ventana,text='ESCUCHAR',bg='green',fg='white',width=64,command=self.inicia)
        self.btnListen2.place(x=610,y=373)
        self.label1 = Label(self.ventana,text="TEXTO A TRADUCIR",bg="light blue",width=64)
        self.label1.place(x=30,y=53)
        self.label2 = Label(self.ventana,text="TRADUCCIÓN",bg="light blue",width=64)
        self.label2.place(x=610,y=53)
        self.btnTans = Button(self.ventana,text='TRADUCIR',command=self.inicia_traduc)
        self.btnTans.place(x=516,y=225)
        self.label3 = Label(self.ventana,text='TRADUCIR A:',bg="light blue")
        self.label3.place(x=511,y=1)
        self.entryLang = ttk.Combobox(self.ventana,width=24,state='readonly')
        self.entryLang.place(x=467,y=1)#y=170)
        self.valores = list(langs.values())
        self.claves = list(langs.keys())
        self.entryLang["values"]=self.valores
        self.entryLang.set("Selecciona Idioma")
        self.btnCopy = Button(self.ventana,text="PEGAR UN TEXTO",command=self.inicia_copia)
        self.btnCopy.place(x=30,y=420)
        self.textLabel = Label(self.ventana, width=156, bg="light blue")
        self.textLabel.place(x=1,y=25)
        self.btnReset = Button(self.ventana, text="RECUPERAR TEXTO",command=self.recover_text)
        self.btnReset.place(x=30,y=450)
        self.btnSave = Button(self.ventana,text="GUARDAR TRADUCCIÓN",command=self.guardar)
        self.btnSave.place(x=929,y=450)
 
 
        self.ventana.mainloop()
 
    def guardar(self):
        if len(self.display2.get('1.0',END))>1:
            documento = filedialog.asksaveasfilename(initialdir="/",
                        title="Guardar en",defaultextension='.txt')
            if documento != "":
                archivo_guardar = open(documento,"w",encoding="utf-8")
                linea=""
                for c in str(self.display2.get('1.0',END)):
                    linea=linea+c
                    if len(linea) == 160:
                        archivo_guardar.write(linea+"\n")
                        linea=""
                archivo_guardar.write(linea)
                archivo_guardar.close()
                messagebox.showinfo("GUARDADO","TRADUCCIÓN GUARDADA EN \'{}\'".format(documento))
 
    def detect(self):
        if "speaking1.mp3" in os.listdir():
            os.remove("speaking1.mp3")
        if len(self.display1.get('1.0',END)) > 1:
            try:
                self.lang = (self.translator.translate(self.display1.get('1.0',END)).src)
                print(self.lang)
                self.tts = gtts.gTTS(self.display1.get('1.0',END),lang=self.lang)
                self.tts.save("speaking1.mp3")
                self.textLabel.configure(text="")
                playsound("speaking1.mp3")
            except Exception as e:
                messagebox.showwarning("ERROR","Se produjo un error inesperado.")
                self.textLabel.configure(text="")
 
    def copy_text(self):
        self.display1.delete('1.0',END)
        self.ultima_copia = pyperclip.paste().strip()
        while True:
            time.sleep(0.1)
            self.copia = pyperclip.paste().strip()
            if self.copia != self.ultima_copia:
                self.display1.insert(END,self.copia)
                self.ultima_copia = self.copia
                print("Done!")
                break
 
    def recover_text(self):
        self.display1.insert(END,self.copia)
 
 
    def traduce(self):
        try:
            if "speaking.mp3" in os.listdir():
                os.remove("speaking.mp3")
            self.display2.delete('1.0',END)
            if len(self.display1.get('1.0',END)) > 1 and self.entryLang.get() != "":
                self.texto = self.display1.get('1.0',END)
                self.lang = self.claves[(self.valores).index(self.entryLang.get())]
                self.traduc = (self.translator.translate(self.texto.lower(),dest=self.lang).text)
                self.display2.insert(END,self.traduc)
                self.textLabel.configure(text="")
                self.tts = gtts.gTTS(self.traduc,lang=self.lang)
                self.tts.save("speaking.mp3")
                self.texto = ""
                self.finished = True
        except:
            self.textLabel.configure(text="SE PRODUJO UN ERROR")
        self.textLabel.configure(text="")
 
 
    def inicia_traduc(self):
        self.finished = False
        self.textLabel.configure(text="TRADUCIENDO...")
        t1 = threading.Thread(target=self.traduce)
        t1.start()
 
    def inicia(self):
        t = threading.Thread(target=self.listen)
        t.start()
 
    def inicia_detect(self):
        if len(self.display1.get('1.0',END)) > 1:
            self.textLabel.configure(text="GENERANDO AUDIO...")
            t2 = threading.Thread(target=self.detect)
            t2.start()
 
    def listen(self):
        if "speaking.mp3" in os.listdir() and self.finished == True:
            playsound("speaking.mp3")
 
    def inicia_copia(self):
        messagebox.showinfo("COPIAR TEXTO","Seleccione el texto a pegar y escoje la opción \'Copiar\'")
        t3 = threading.Thread(target=self.copy_text)
        t3.start()
 
    def __del__(self):
        if "speaking1.mp3" in os.listdir():
            os.remove("speaking1.mp3")
        if "speaking.mp3" in os.listdir():
            os.remove("speaking.mp3")
 
if __name__=="__main__":
    traductor()



Comentarios sobre la versión: 1.2 (3)

Imágen de perfil
24 de Junio del 2020
estrellaestrellaestrellaestrellaestrella
Que grande Antonio, no sabia que existiera una librería con el Translator de Google!!!
Responder
Imágen de perfil
24 de Junio del 2020
estrellaestrellaestrellaestrellaestrella
Yo tampoco hasta hace unas pocas semanas, cuando la descubrí por pura casualidad, mirando por ahí y por allá :)
Responder
alam
30 de Octubre del 2021
estrellaestrellaestrellaestrellaestrella
Yo lo copie y pegue e instale todas las librerias pero cuando quiero traducir no hace nada
queria saber porque no funciona, se queda que solo dice "traduciendo y no hace mas nada"
Responder

Comentar la versión: 1.2

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s6318