tx3bas commited on
Commit
2dac9bd
·
verified ·
1 Parent(s): f14054c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -16
app.py CHANGED
@@ -1,9 +1,10 @@
1
  import gradio as gr
2
  from mtranslate import translate
3
  from bs4 import BeautifulSoup
 
4
  import json
5
 
6
- # Diccionario de idiomas
7
  lang_dict = {
8
  'Auto': 'auto',
9
  'Español': 'es',
@@ -14,39 +15,58 @@ lang_dict = {
14
  lang_list = [k for k in lang_dict.keys() if k != 'Auto']
15
  source_lang_list = ['Auto'] + lang_list
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def translate_html_content(text, source_lang, target_lang):
18
  """
19
- Traduce el contenido de texto dentro de un HTML, preservando las etiquetas.
20
  """
21
- # Parsear el HTML con BeautifulSoup
22
  soup = BeautifulSoup(text, 'html.parser')
23
 
24
- # Recorrer todos los nodos de texto
25
  for node in soup.find_all(text=True):
26
  text_to_translate = node.strip()
27
  if text_to_translate:
28
- # Traducir el texto si no está vacío
29
- translated_text = translate(text_to_translate, target_lang, source_lang)
30
- # Reemplazar el nodo original con el texto traducido
 
 
 
 
 
 
 
 
 
31
  node.replace_with(translated_text)
32
 
33
- # Devolver el HTML como string
34
  return str(soup)
35
 
36
  def main(Texto, source_lang, target_lang):
37
- """
38
- Función principal que procesa la entrada y genera la salida con un botón de copiar.
39
- """
40
  source_code = lang_dict[source_lang]
41
  target_code = lang_dict[target_lang]
42
 
43
- # Traducir el contenido HTML
44
  translated_text = translate_html_content(Texto, source_code, target_code)
45
-
46
- # Escapar el texto solo para el botón de copiar
47
  escaped_text = json.dumps(translated_text)[1:-1]
48
 
49
- # Generar la salida HTML con el botón de copiar
50
  html_output = f"""
51
  <div style="position: relative; min-height: 100px;">
52
  <div id="translated-content">{translated_text}</div>
@@ -58,7 +78,7 @@ def main(Texto, source_lang, target_lang):
58
  """
59
  return html_output
60
 
61
- # Configuración de la interfaz de Gradio
62
  iface = gr.Interface(
63
  fn=main,
64
  inputs=[
 
1
  import gradio as gr
2
  from mtranslate import translate
3
  from bs4 import BeautifulSoup
4
+ import re
5
  import json
6
 
7
+ # Diccionario de idiomas (sin cambios)
8
  lang_dict = {
9
  'Auto': 'auto',
10
  'Español': 'es',
 
15
  lang_list = [k for k in lang_dict.keys() if k != 'Auto']
16
  source_lang_list = ['Auto'] + lang_list
17
 
18
+ def split_text(text, limit=4000):
19
+ """
20
+ Divide el texto en fragmentos de hasta 'limit' caracteres usando el punto (.) como delimitador.
21
+ """
22
+ sentences = re.split(r'(\.)', text) # Separa conservando el punto
23
+ chunks = []
24
+ chunk = ''
25
+ for i in range(0, len(sentences), 2):
26
+ sentence = sentences[i] + (sentences[i+1] if i+1 < len(sentences) else '')
27
+ if len(chunk) + len(sentence) > limit:
28
+ if chunk:
29
+ chunks.append(chunk)
30
+ chunk = sentence
31
+ else:
32
+ chunk += sentence
33
+ if chunk:
34
+ chunks.append(chunk)
35
+ return chunks
36
+
37
  def translate_html_content(text, source_lang, target_lang):
38
  """
39
+ Traduce el texto dentro de un HTML, preservando las etiquetas y dividiendo en fragmentos de máximo 4000 caracteres.
40
  """
 
41
  soup = BeautifulSoup(text, 'html.parser')
42
 
 
43
  for node in soup.find_all(text=True):
44
  text_to_translate = node.strip()
45
  if text_to_translate:
46
+ # Divide el texto en fragmentos usando el punto como delimitador
47
+ chunks = split_text(text_to_translate)
48
+ translated_chunks = []
49
+ for chunk in chunks:
50
+ # Traduce cada fragmento
51
+ translated_chunk = translate(chunk, target_lang, source_lang)
52
+ # Limpia caracteres escapados no deseados
53
+ translated_chunk = translated_chunk.replace('\\"', '"').replace('\\n', '\n').replace('\\\\', '\\')
54
+ translated_chunks.append(translated_chunk)
55
+ # Une los fragmentos traducidos
56
+ translated_text = ''.join(translated_chunks)
57
+ # Reemplaza el texto original por el traducido
58
  node.replace_with(translated_text)
59
 
 
60
  return str(soup)
61
 
62
  def main(Texto, source_lang, target_lang):
 
 
 
63
  source_code = lang_dict[source_lang]
64
  target_code = lang_dict[target_lang]
65
 
 
66
  translated_text = translate_html_content(Texto, source_code, target_code)
 
 
67
  escaped_text = json.dumps(translated_text)[1:-1]
68
 
69
+ # Genera el HTML con el texto traducido y un botón para copiar
70
  html_output = f"""
71
  <div style="position: relative; min-height: 100px;">
72
  <div id="translated-content">{translated_text}</div>
 
78
  """
79
  return html_output
80
 
81
+ # Configuración de la interfaz
82
  iface = gr.Interface(
83
  fn=main,
84
  inputs=[