Skip to content

Commit

Permalink
fix: vectorization
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomeriko96 committed Jul 28, 2024
1 parent 6f3f984 commit a2b54bc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
6 changes: 3 additions & 3 deletions CRAN-SUBMISSION
Original file line number Diff line number Diff line change
@@ -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
41 changes: 29 additions & 12 deletions R/google_translate_long_text.R
Original file line number Diff line number Diff line change
Expand Up @@ -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=",
Expand All @@ -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)
}

0 comments on commit a2b54bc

Please sign in to comment.