tx3bas commited on
Commit
4465a0f
·
verified ·
1 Parent(s): 67b354c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -70
app.py CHANGED
@@ -1,47 +1,28 @@
1
  import streamlit as st
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
  lang_list = list(lang_dict.keys())
 
44
 
 
45
  def split_text(text, limit=4000):
46
  sentences = re.split(r'([;.])', text)
47
  chunks = []
@@ -56,50 +37,73 @@ def split_text(text, limit=4000):
56
  chunks.append(chunk)
57
  return chunks
58
 
59
- def translate_text(lang, text):
60
- # Obtener el código del idioma
61
- lang_code = lang_dict[lang]
62
-
63
- # Dividir el texto en fragmentos que no superen el límite de 4000 caracteres
64
- chunks = split_text(text)
65
-
66
- translated_chunks = [translate(chunk, lang_code) for chunk in chunks]
67
- translated_text = ''.join(translated_chunks)
68
-
69
- return translated_text
 
 
 
 
 
 
 
 
70
 
71
  def main():
72
- st.title("Traducción sin límites")
73
-
74
- text = st.text_area("Texto a traducir", height=200)
75
- lang = st.selectbox("Idioma", lang_list)
76
-
77
- if st.button("Traducir"):
78
- # Realizar la traducción
79
- translated_text = translate_text(lang, text)
80
-
81
- # Mostrar el resultado con el botón de copia
82
- st.session_state.translated_text = translated_text
83
- st.write("Texto traducido:")
84
- st.write(translated_text)
85
-
86
- # Mostrar el botón de copiar
87
- copy_button = f"""
88
- <button onclick="copyToClipboard()">Copiar</button>
89
- <script>
90
- function copyToClipboard() {{
91
- var text = `{html.escape(translated_text)}`;
92
- navigator.clipboard.writeText(text).then(function() {{
93
- alert('Texto copiado al portapapeles');
94
- }}, function(err) {{
95
- console.error('No se pudo copiar el texto: ', err);
96
- }});
97
- }}
98
- </script>
99
- """
100
- st.markdown(copy_button, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  if "translated_text" not in st.session_state:
103
  st.session_state.translated_text = ""
104
 
105
- main()
 
 
1
  import streamlit as st
2
  from mtranslate import translate
3
+ from bs4 import BeautifulSoup, NavigableString
4
  import re
5
+ import time
6
  import html
7
 
8
  # Diccionario de idiomas y sus códigos
9
  lang_dict = {
10
+ 'Auto': 'auto',
11
  'Español': 'es',
12
  'English': 'en',
 
 
 
 
 
 
 
 
 
 
 
13
  'Francés': 'fr',
14
+ 'Alemán': 'de',
 
15
  'Italiano': 'it',
16
+ 'Portugués': 'pt',
17
+ 'Chino': 'zh',
18
+ 'Japonés': 'ja',
19
+ 'Ruso': 'ru',
 
 
 
 
 
 
 
 
 
 
 
 
20
  }
21
 
22
  lang_list = list(lang_dict.keys())
23
+ source_lang_list = ['Auto'] + lang_list
24
 
25
+ # --- FUNCIONES ---
26
  def split_text(text, limit=4000):
27
  sentences = re.split(r'([;.])', text)
28
  chunks = []
 
37
  chunks.append(chunk)
38
  return chunks
39
 
40
+ def translate_html_content(text, source_lang, target_lang):
41
+ soup = BeautifulSoup(text, 'html.parser')
42
+
43
+ for node in soup.find_all(text=True):
44
+ if isinstance(node, NavigableString) and node.strip():
45
+ original_text = node.strip()
46
+ chunks = split_text(original_text)
47
+ translated_chunks = [translate(chunk, target_lang, source_lang) for chunk in chunks]
48
+ translated_text = ''.join(translated_chunks)
49
+
50
+ # Asegurar espacios alrededor del texto
51
+ if node.previous_sibling and not node.previous_sibling.endswith(' '):
52
+ translated_text = ' ' + translated_text
53
+ if node.next_sibling and not node.next_sibling.startswith(' '):
54
+ translated_text += ' '
55
+
56
+ node.replace_with(translated_text)
57
+
58
+ return str(soup)
59
 
60
  def main():
61
+ st.title("🌍 Traductor HTML Inteligente")
62
+
63
+ with st.expander("ℹ️ Instrucciones"):
64
+ st.write(
65
+ "- Introduce tu texto o HTML en la caja de texto.\n"
66
+ "- Selecciona el idioma de origen y el idioma de destino.\n"
67
+ "- Haz clic en 'Traducir' para obtener el texto traducido."
68
+ )
69
+
70
+ text = st.text_area("✍️ Introduce el texto o HTML aquí:", height=200)
71
+ col1, col2 = st.columns(2)
72
+ with col1:
73
+ source_lang = st.selectbox("🌐 Idioma de origen:", source_lang_list)
74
+ with col2:
75
+ target_lang = st.selectbox("🎯 Idioma de destino:", lang_list, index=1)
76
+
77
+ if st.button("🚀 Traducir"):
78
+ if text.strip():
79
+ with st.spinner("⏳ Traduciendo..."):
80
+ translated_text = translate_html_content(text, lang_dict[source_lang], lang_dict[target_lang])
81
+ st.session_state.translated_text = translated_text
82
+ time.sleep(2) # Simulación de carga
83
+
84
+ st.subheader("📝 Resultado de la traducción:")
85
+ st.write(translated_text)
86
+
87
+ # Botón de copiar
88
+ copy_button = f"""
89
+ <button onclick="copyToClipboard()">📋 Copiar</button>
90
+ <script>
91
+ function copyToClipboard() {{
92
+ var text = `{html.escape(translated_text)}`;
93
+ navigator.clipboard.writeText(text).then(function() {{
94
+ alert('Texto copiado al portapapeles');
95
+ }}, function(err) {{
96
+ console.error('No se pudo copiar el texto: ', err);
97
+ }});
98
+ }}
99
+ </script>
100
+ """
101
+ st.markdown(copy_button, unsafe_allow_html=True)
102
+ else:
103
+ st.warning("⚠️ Por favor, introduce un texto antes de traducir.")
104
 
105
  if "translated_text" not in st.session_state:
106
  st.session_state.translated_text = ""
107
 
108
+ # Ejecutar la app
109
+ main()