Compare commits

..

1 Commits

Author SHA1 Message Date
rafa 4475ebb04b Dar contexto al traducir títulos
Co-authored-by: rafa <rcalvotorrejon@gmail.com>
Signed-off-by: rafa <rcalvotorrejon@gmail.com>
2026-08-11 21:57:37 -04:00
2 changed files with 17 additions and 54 deletions
-52
View File
@@ -924,58 +924,6 @@ function fea_is_front_page(): bool {
return $id && in_array($id, fea_front_page_ids(), true); return $id && in_array($id, fea_front_page_ids(), true);
} }
/** URL de la búsqueda avanzada en el idioma actual, con fallback al español. */
function fea_home_advanced_search_url(): string {
$url = home_url('/buscar/');
if (!function_exists('pll_current_language') || !function_exists('pll_get_post')) return $url;
$lang = pll_current_language();
$default = function_exists('pll_default_language') ? pll_default_language() : 'es';
if (!$lang || $lang === $default) return $url;
$page = get_page_by_path('buscar');
if (!$page) return $url;
$translated_id = pll_get_post($page->ID, $lang);
return $translated_id ? get_permalink($translated_id) : $url;
}
// En desktop, una lupa sin texto abre la búsqueda avanzada en vez de activar la
// validación nativa del campo requerido del bloque Search de WordPress.
add_action('wp_footer', function() {
if (!fea_is_front_page()) return;
$advanced_url = wp_json_encode(fea_home_advanced_search_url());
?>
<script>
(function() {
function configureDesktopSearch() {
if (!window.matchMedia('(min-width: 601px)').matches) return;
document.querySelectorAll('form.wp-block-search, .wp-block-search form').forEach(function(form) {
var input = form.querySelector('input[type="search"], input[name="s"]');
if (!input || form.dataset.feaEmptySearchReady) return;
form.dataset.feaEmptySearchReady = 'true';
form.noValidate = true;
input.removeAttribute('required');
form.addEventListener('submit', function(event) {
if (input.value.trim() !== '') return;
event.preventDefault();
window.location.assign(<?php echo $advanced_url; ?>);
});
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', configureDesktopSearch);
} else {
configureDesktopSearch();
}
})();
</script>
<?php
});
/** True para la landing de Escuela, que no muestra título visible. */ /** True para la landing de Escuela, que no muestra título visible. */
function fea_is_escuela_page(): bool { function fea_is_escuela_page(): bool {
if (!is_page()) return false; if (!is_page()) return false;
+17 -2
View File
@@ -176,7 +176,7 @@ def _system_prompt(lang: str) -> str:
) )
def translate_text(text: str, lang: str, *, is_title: bool = False) -> str: def translate_text(text: str, lang: str, *, is_title: bool = False, context: str = "") -> str:
text = text.strip() text = text.strip()
if not text: if not text:
return "" return ""
@@ -185,6 +185,13 @@ def translate_text(text: str, lang: str, *, is_title: bool = False) -> str:
return out return out
user = f"<<<INI>>>{text}<<<FIN>>>" user = f"<<<INI>>>{text}<<<FIN>>>"
if is_title: if is_title:
context_block = ""
if context:
context_block = (
"\nBODY CONTEXT (for meaning only; do not translate or include it):\n"
f"<<<CONTEXT>>>{context}<<<ENDCONTEXT>>>\n"
)
user = context_block + user
kind = "el TÍTULO" kind = "el TÍTULO"
task = ( task = (
f"Traduce {kind} que va entre las marcas.\n" f"Traduce {kind} que va entre las marcas.\n"
@@ -192,6 +199,7 @@ def translate_text(text: str, lang: str, *, is_title: bool = False) -> str:
f"No lo dejes en inglés salvo que el original ya sea un nombre propio o una marca.\n" f"No lo dejes en inglés salvo que el original ya sea un nombre propio o una marca.\n"
f"Responde solo con el título traducido entre las marcas:\n{user}" f"Responde solo con el título traducido entre las marcas:\n{user}"
) )
task += "\nSi es un modismo, interpreta su sentido segun el contexto, no lo calques."
else: else:
kind = "el texto" kind = "el texto"
task = f"Traduce {kind} que va entre las marcas:\n{user}" task = f"Traduce {kind} que va entre las marcas:\n{user}"
@@ -226,6 +234,13 @@ def translate_html(html: str, lang: str) -> str:
# ── Datos / estado ─────────────────────────────────────────────────────────── # ── Datos / estado ───────────────────────────────────────────────────────────
def title_context(html: str) -> str:
"""First paragraph gives title idioms enough meaning without bloating the prompt."""
first = re.search(r"<p\b[^>]*>.*?</p>", html, flags=re.IGNORECASE | re.DOTALL)
context = first.group(0) if first else html
return re.sub(r"\s+", " ", context).strip()[:2000]
def read_post(post_id: int) -> dict: def read_post(post_id: int) -> dict:
return json.loads(php_helper("read", str(post_id))) return json.loads(php_helper("read", str(post_id)))
@@ -290,8 +305,8 @@ def process_post(post_id: int, langs: list[str], status: str, force: bool, state
log(f" {lang}: --force, eliminada traducción previa #{existing}") log(f" {lang}: --force, eliminada traducción previa #{existing}")
try: try:
t0 = time.time() t0 = time.time()
title = translate_text(src["title"], lang, is_title=True)
content = translate_html(src["content"], lang) content = translate_html(src["content"], lang)
title = translate_text(src["title"], lang, is_title=True, context=title_context(src["content"]))
new_id = create_translation(post_id, lang, title, content, status) new_id = create_translation(post_id, lang, title, content, status)
dt = time.time() - t0 dt = time.time() - t0
log(f" {lang}: creado #{new_id} ({dt:.0f}s) → «{title[:50]}»") log(f" {lang}: creado #{new_id} ({dt:.0f}s) → «{title[:50]}»")