From a2b54bc1dae8a61d42f6eee9e4577e12034ee6b1 Mon Sep 17 00:00:00 2001 From: Tomer Date: Sun, 28 Jul 2024 12:55:44 +0200 Subject: [PATCH] fix: vectorization --- CRAN-SUBMISSION | 6 ++--- R/google_translate_long_text.R | 41 ++++++++++++++++++++++++---------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/CRAN-SUBMISSION b/CRAN-SUBMISSION index 869b2b2..0b643ca 100644 --- a/CRAN-SUBMISSION +++ b/CRAN-SUBMISSION @@ -1,3 +1,3 @@ -Version: 1.0.0 -Date: 2022-09-15 19:19:22 UTC -SHA: b2b2e963c5b0f0eefc8d83c9d1841805e7e30ef7 +Version: 1.5.1 +Date: 2024-07-27 10:43:08 UTC +SHA: 6f3f984a3df4162ff45262d4eb0cc5b2a5a51bd7 diff --git a/R/google_translate_long_text.R b/R/google_translate_long_text.R index 87496f4..691d760 100644 --- a/R/google_translate_long_text.R +++ b/R/google_translate_long_text.R @@ -33,15 +33,8 @@ google_translate_long_text <- function(text, target_language = "en", source_lang sapply(split_indices, function(i) substr(text, i, i + chunk_size - 1)) } - # Split text into chunks if it's too long - if (nchar(text) > chunk_size) { - text_chunks <- split_text(text, chunk_size) - } else { - text_chunks <- list(text) - } - - # Translate each chunk - translations <- sapply(text_chunks, function(chunk) { + # Function to translate a single chunk of text + translate_chunk <- function(chunk) { formatted_text <- urltools::url_encode(chunk) formatted_link <- paste0( "https://translate.google.com/m?tl=", @@ -56,8 +49,32 @@ google_translate_long_text <- function(text, target_language = "en", source_lang translation <- urltools::url_decode(translation) gsub("\n", "", translation) - }) + } + + # Check if the input is a vector + is_vector <- is.vector(text) && length(text) > 1 + + if (is_vector) { + # Process each element in the vector + translations <- sapply(text, function(single_text) { + if (nchar(single_text) > chunk_size) { + text_chunks <- split_text(single_text, chunk_size) + } else { + text_chunks <- list(single_text) + } + translated_chunks <- sapply(text_chunks, translate_chunk) + paste(translated_chunks, collapse = " ") + }) + } else { + # Process a single string + if (nchar(text) > chunk_size) { + text_chunks <- split_text(text, chunk_size) + } else { + text_chunks <- list(text) + } + translations <- sapply(text_chunks, translate_chunk) + translations <- paste(translations, collapse = " ") + } - # Combine translated chunks - paste(translations, collapse = " ") + return(translations) }