tx3bas commited on
Commit
9bd8424
·
verified ·
1 Parent(s): ecd101a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -77
app.py CHANGED
@@ -1,54 +1,52 @@
1
  import gradio as gr
2
  from mtranslate import translate
3
  import re
 
4
 
5
  # Diccionario de idiomas y sus códigos
6
  lang_dict = {
7
- 'Automático': 'auto',
8
- 'Español': 'es',
9
- 'English': 'en',
10
- 'Mandarín': 'zh',
11
- 'Hindi': 'hi',
12
- 'Árabe': 'ar',
13
- 'Portugués': 'pt',
14
- 'Bengalí': 'bn',
15
- 'Ruso': 'ru',
16
- 'Japonés': 'ja',
17
- 'Panyabí': 'pa',
18
- 'Alemán': 'de',
19
- 'Javanés': 'jw',
20
- 'Coreano': 'ko',
21
- 'Francés': 'fr',
22
- 'Vietnamita': 'vi',
23
- 'Turco': 'tr',
24
- 'Italiano': 'it',
25
- 'Ucraniano': 'uk',
26
- 'Tailandés': 'th',
27
- 'Guyaratí': 'gu',
28
- 'Polaco': 'pl',
29
- 'Griego': 'el',
30
- 'Neerlandés': 'nl',
31
- 'Sueco': 'sv',
32
- 'Rumano': 'ro',
33
- 'Checo': 'cs',
34
- 'Húngaro': 'hu',
35
- 'Hebreo': 'he',
36
- 'Indonesio': 'id',
37
- 'Nepalí': 'ne',
38
- 'Gallego': 'gl',
39
- 'Catalán': 'ca',
40
  'Vasco': 'eu'
41
  }
42
 
43
- lang_list = list(lang_dict.keys())
 
 
44
 
45
- # Función para separar texto y etiquetas HTML
46
- def split_html_text(text):
47
- pattern = r'(<[^>]+>)'
48
- parts = re.split(pattern, text)
49
- return [part for part in parts if part] # Eliminar partes vacías
50
 
51
- # Función para dividir texto en fragmentos
52
  def split_text(text, limit=4000):
53
  sentences = re.split(r'([;.])', text)
54
  chunks = []
@@ -63,56 +61,106 @@ def split_text(text, limit=4000):
63
  chunks.append(chunk)
64
  return chunks
65
 
66
- # Función de traducción mejorada
67
- def translate_text(from_lang, to_lang, text):
68
- from_code = lang_dict[from_lang]
69
- to_code = lang_dict[to_lang]
70
 
71
- # Separar texto y etiquetas HTML
72
- parts = split_html_text(text)
73
- translated_parts = []
74
 
75
- for part in parts:
76
- if re.match(r'<[^>]+>', part):
77
- # Es una etiqueta HTML, se mantiene intacta
78
- translated_parts.append(part)
79
- else:
80
- # Es texto, se divide en fragmentos si es necesario y se traduce
81
- chunks = split_text(part)
82
- translated_chunks = []
83
- for chunk in chunks:
84
- if from_code == 'auto':
85
- translated_chunk = translate(chunk, to_code)
86
- else:
87
- translated_chunk = translate(chunk, to_code, from_code)
88
- translated_chunks.append(translated_chunk)
89
- translated_parts.append(''.join(translated_chunks))
90
 
91
- translated_text = ''.join(translated_parts)
92
- return translated_text
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Función principal
95
- def main(Texto, from_lang, to_lang):
96
- translated_text = translate_text(from_lang, to_lang, Texto)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  html_output = f"""
98
- <div>
99
- {translated_text}
 
 
 
 
 
100
  </div>
101
  """
 
102
  return html_output
103
 
104
- # Interfaz de Gradio
105
  iface = gr.Interface(
106
  fn=main,
107
  inputs=[
108
- gr.Textbox(label="Texto a traducir"),
109
- gr.Dropdown(lang_list, label="Idioma de origen", value="Automático"),
110
- gr.Dropdown(lang_list, label="Idioma de destino")
111
  ],
112
- outputs="text",
113
- title="<div style='margin:0 auto;text-align:center'><div style='margin:0 auto;text-align:center'><img style='width:100px;display: inline-table;margin-bottom:-10px' src='https://artxeweb.com/media/files/idioma.jpg'><p>Traducción sin límites</p></div>",
114
- description="<p style='margin-bottom:10px;text-align:center;background: #ffffff; padding: 8px; border-radius: 8px; border-width: 1px; border: solid 1px #e5e7eb;'>Ingresa el texto que deseas traducir, selecciona el idioma de origen (o deja 'Automático') y el idioma de destino. ¡No hay límites!</p>",
115
- article="<div style='margin-top:10px'><p style='text-align: center !important; background: #ffffff; padding: 5px 30px; border-radius: 8px; border-width: 1px; border: solid 1px #e5e7eb; width: fit-content; margin: auto;'>Desarrollada por <a style='text-decoration: none !important; color: #e12a31 !important;' title='Artxe Web' href='https://artxeweb.com'>© Artxe Web</a></p></div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  )
117
 
118
  iface.launch()
 
1
  import gradio as gr
2
  from mtranslate import translate
3
  import re
4
+ import html
5
 
6
  # Diccionario de idiomas y sus códigos
7
  lang_dict = {
8
+ 'Español': 'es',
9
+ 'English': 'en',
10
+ 'Mandarín': 'zh',
11
+ 'Hindi': 'hi',
12
+ 'Árabe': 'ar',
13
+ 'Portugués': 'pt',
14
+ 'Bengalí': 'bn',
15
+ 'Ruso': 'ru',
16
+ 'Japonés': 'ja',
17
+ 'Panyabí': 'pa',
18
+ 'Alemán': 'de',
19
+ 'Javanés': 'jw',
20
+ 'Coreano': 'ko',
21
+ 'Francés': 'fr',
22
+ 'Vietnamita': 'vi',
23
+ 'Turco': 'tr',
24
+ 'Italiano': 'it',
25
+ 'Ucraniano': 'uk',
26
+ 'Tailandés': 'th',
27
+ 'Guyaratí': 'gu',
28
+ 'Polaco': 'pl',
29
+ 'Griego': 'el',
30
+ 'Neerlandés': 'nl',
31
+ 'Sueco': 'sv',
32
+ 'Rumano': 'ro',
33
+ 'Checo': 'cs',
34
+ 'Húngaro': 'hu',
35
+ 'Hebreo': 'he',
36
+ 'Indonesio': 'id',
37
+ 'Nepalí': 'ne',
38
+ 'Gallego': 'gl',
39
+ 'Catalán': 'ca',
 
40
  'Vasco': 'eu'
41
  }
42
 
43
+ # Añadir el idioma base para seleccionar el origen
44
+ source_lang_dict = {'Detectar automáticamente': 'auto'}
45
+ source_lang_dict.update(lang_dict)
46
 
47
+ lang_list = list(lang_dict.keys())
48
+ source_lang_list = list(source_lang_dict.keys())
 
 
 
49
 
 
50
  def split_text(text, limit=4000):
51
  sentences = re.split(r'([;.])', text)
52
  chunks = []
 
61
  chunks.append(chunk)
62
  return chunks
63
 
64
+ def protect_html_tags(text):
65
+ # Identificar y extraer etiquetas HTML
66
+ html_pattern = re.compile(r'<([^>]+)>')
67
+ html_matches = html_pattern.finditer(text)
68
 
69
+ # Crear un diccionario de reemplazo
70
+ replacements = {}
 
71
 
72
+ # Crear una versión del texto con marcadores únicos en lugar de las etiquetas HTML
73
+ protected_text = text
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ for i, match in enumerate(html_matches):
76
+ placeholder = f"__HTML_TAG_{i}__"
77
+ replacements[placeholder] = match.group(0)
78
+ protected_text = protected_text.replace(match.group(0), placeholder, 1)
79
+
80
+ return protected_text, replacements
81
+
82
+ def restore_html_tags(text, replacements):
83
+ # Restaurar las etiquetas HTML originales
84
+ restored_text = text
85
+ for placeholder, original in replacements.items():
86
+ restored_text = restored_text.replace(placeholder, original)
87
+ return restored_text
88
 
89
+ def translate_text(source_lang, target_lang, text):
90
+ # Proteger etiquetas HTML
91
+ protected_text, replacements = protect_html_tags(text)
92
+
93
+ # Obtener código del idioma de destino
94
+ target_code = lang_dict[target_lang]
95
+
96
+ # Dividir el texto en fragmentos para no superar el límite
97
+ chunks = split_text(protected_text)
98
+
99
+ # Traducir cada fragmento
100
+ translated_chunks = []
101
+ for chunk in chunks:
102
+ # mtranslate no acepta el parámetro 'source', solo podemos especificar el destino
103
+ # La API de Google detecta automáticamente el idioma de origen
104
+ translated_chunk = translate(chunk, target_code)
105
+ translated_chunks.append(translated_chunk)
106
+
107
+ translated_text = ''.join(translated_chunks)
108
+
109
+ # Restaurar etiquetas HTML
110
+ final_text = restore_html_tags(translated_text, replacements)
111
+
112
+ return final_text
113
+
114
+ def main(texto, target_lang):
115
+ # Verificar si hay texto para traducir
116
+ if not texto.strip():
117
+ return "<div>Por favor, ingresa un texto para traducir.</div>"
118
+
119
+ # Realizar la traducción
120
+ translated_text = translate_text('Detectar automáticamente', target_lang, texto)
121
+
122
+ # Escapar el texto traducido para JavaScript (para el botón de copia)
123
+ escaped_text = html.escape(translated_text).replace("'", "\\'").replace('"', '\\"')
124
+
125
+ # Generar HTML con botón de copia
126
  html_output = f"""
127
+ <div style="position: relative;">
128
+ <div>{translated_text}</div>
129
+ <button
130
+ style="position: absolute; top: 0; right: 0; font-size: small; padding: 5px; background-color: #f0f0f0; color: #333; border: 1px solid #ccc; border-radius: 4px; cursor: pointer;"
131
+ onclick='navigator.clipboard.writeText("{escaped_text}").then(() => alert("Texto copiado al portapapeles"))'>
132
+ Copiar
133
+ </button>
134
  </div>
135
  """
136
+
137
  return html_output
138
 
 
139
  iface = gr.Interface(
140
  fn=main,
141
  inputs=[
142
+ "text",
143
+ gr.Dropdown(lang_list, label="Idioma de Destino")
 
144
  ],
145
+ outputs="html",
146
+ title="""<div style='margin:0 auto;text-align:center'>
147
+ <div style='margin:0 auto;text-align:center'>
148
+ <img style='width:100px;display: inline-table;margin-bottom:-10px' src='https://artxeweb.com/media/files/idioma.jpg'>
149
+ <p>Traducción sin límites</p>
150
+ </div>
151
+ </div>""",
152
+ description="""<p style='margin-bottom:10px;text-align:center;background: #ffffff; padding: 8px; border-radius: 8px;
153
+ border-width: 1px; border: solid 1px #e5e7eb;'>
154
+ Ingresa el texto que deseas traducir y selecciona el idioma de destino. Las etiquetas HTML serán preservadas.
155
+ El idioma de origen se detecta automáticamente. ¡No hay límites!
156
+ </p>""",
157
+ article="""<div style='margin-top:10px'>
158
+ <p style='text-align: center !important; background: #ffffff; padding: 5px 30px;
159
+ border-radius: 8px; border-width: 1px; border: solid 1px #e5e7eb; width: fit-content; margin: auto;'>
160
+ Desarrollada por <a style='text-decoration: none !important; color: #e12a31 !important;'
161
+ title='Artxe Web' href='https://artxeweb.com'>© Artxe Web</a>
162
+ </p>
163
+ </div>"""
164
  )
165
 
166
  iface.launch()