|
import gradio as gr |
|
from mtranslate import translate |
|
import re |
|
import json |
|
import uuid |
|
|
|
|
|
lang_dict = { |
|
'Auto': 'auto', |
|
'Español': 'es', |
|
'English': 'en', |
|
|
|
} |
|
|
|
lang_list = [k for k in lang_dict.keys() if k != 'Auto'] |
|
source_lang_list = ['Auto'] + lang_list |
|
|
|
def split_text(text, limit=4000): |
|
sentences = re.split(r'([;.])', text) |
|
chunks = [] |
|
chunk = '' |
|
for i in range(0, len(sentences), 2): |
|
sentence = sentences[i] + (sentences[i+1] if i+1 < len(sentences) else '') |
|
if len(chunk) + len(sentence) > limit: |
|
chunks.append(chunk) |
|
chunk = '' |
|
chunk += sentence |
|
if chunk: |
|
chunks.append(chunk) |
|
return chunks |
|
|
|
def translate_html_content(text, source_lang, target_lang): |
|
|
|
html_tag_pattern = re.compile(r'<[^>]+>') |
|
|
|
|
|
tags = html_tag_pattern.findall(text) |
|
|
|
|
|
markers = {f"{{{uuid.uuid4()}}}": tag for tag in tags} |
|
for marker, tag in markers.items(): |
|
text = text.replace(tag, marker) |
|
|
|
|
|
chunks = split_text(text) |
|
|
|
|
|
translated_chunks = [] |
|
for chunk in chunks: |
|
|
|
translated_chunk = translate(chunk, target_lang, source_lang) |
|
|
|
translated_chunk = translated_chunk.replace('\\"', '"').replace('\\n', '\n').replace('\\\\', '\\') |
|
translated_chunks.append(translated_chunk) |
|
|
|
|
|
translated_text = ''.join(translated_chunks) |
|
|
|
|
|
for marker, tag in markers.items(): |
|
translated_text = translated_text.replace(marker, tag) |
|
|
|
return translated_text |
|
|
|
def main(Texto, source_lang, target_lang): |
|
source_code = lang_dict[source_lang] |
|
target_code = lang_dict[target_lang] |
|
|
|
translated_text = translate_html_content(Texto, source_code, target_code) |
|
|
|
escaped_text = json.dumps(translated_text)[1:-1] |
|
|
|
html_output = f""" |
|
<div style="position: relative; min-height: 100px;"> |
|
<div id="translated-content">{translated_text}</div> |
|
<button onclick="navigator.clipboard.writeText('{escaped_text}').then(() => alert('Texto copiado'))" |
|
style="position: absolute; top: 0; right: 0; padding: 5px; background: #ffffff; border: 1px solid #e0e0e0; border-radius: 4px; cursor: pointer;"> |
|
📋 Copiar |
|
</button> |
|
</div> |
|
""" |
|
return html_output |
|
|
|
|
|
iface = gr.Interface( |
|
fn=main, |
|
inputs=[ |
|
"text", |
|
gr.Dropdown(source_lang_list, value="Auto", label="Idioma origen"), |
|
gr.Dropdown(lang_list, value="Español", label="Idioma destino") |
|
], |
|
outputs="text", |
|
title="Traducción sin límites", |
|
description="Ingresa el texto que deseas traducir y selecciona los idiomas. ¡No hay límites!", |
|
article="Desarrollada por © Artxe Web" |
|
) |
|
|
|
iface.launch() |