Created
November 6, 2025 15:05
-
-
Save alekrutkowski/6415f502e19869d46ac2f9d75f47922b to your computer and use it in GitHub Desktop.
R/Shiny app similar to Google Translate whole page translation (when you paste a URL)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #### Prerequisites -- in Linux terminal: | |
| # Once: | |
| # pipx install libretranslate | |
| # Run in the background: | |
| # libretranslate | |
| #### Test: | |
| # Open the following page in a web browser | |
| # (but first modify your.shiny-server.domain and your_translate_app_name): | |
| # https://your.shiny-server.domain/your_translate_app_name/?url=https://example.com/&from=en&to=fr | |
| # equivalent of: | |
| # https://translate.google.com/?sl=en&tl=fr&text=https%3A%2F%2Fexample.com&op=translate | |
| # which provides the link: | |
| # https://example-com.translate.goog/?_x_tr_sl=en&_x_tr_tl=fr | |
| library(shiny) | |
| library(curl) | |
| library(jsonlite) | |
| library(magrittr) | |
| INTERNAL_URL <- "http://localhost:5000/translate" | |
| fetch_and_transform <- function(URL,from,to) { | |
| con <- | |
| url(URL, "rb") | |
| on.exit(close(con), add = TRUE) | |
| json_data <- | |
| readLines(con, warn=FALSE, encoding="UTF-8") %>% | |
| paste(collapse="") %>% | |
| list(q=., | |
| source=from, | |
| target=to, | |
| format="html") %>% | |
| toJSON(auto_unbox = TRUE) | |
| h <- | |
| new_handle() | |
| handle_setheaders(h, "Content-Type"="application/json") | |
| handle_setopt(h, postfields=json_data) | |
| curl_fetch_memory(INTERNAL_URL, handle=h) %>% | |
| .$content %>% | |
| rawToChar %>% | |
| fromJSON %>% | |
| .$translatedText %>% | |
| substr(5,nchar(.)) # remove string "html" from the beginning | |
| } | |
| ui <- function(request) { | |
| query <- | |
| parseQueryString(request$QUERY_STRING) | |
| URL <- | |
| URLdecode(query$url) | |
| from <- | |
| tolower(query$from) %>% | |
| `if`(length(.)==0,'en',.) | |
| to <- | |
| tolower(query$to) %>% | |
| `if`(length(.)==0,'pl',.) | |
| content <- | |
| tryCatch(fetch_and_transform(URL,from,to), | |
| error = function(e) e) | |
| if (inherits(content, "error")) | |
| httpResponse( | |
| status = 502, | |
| content_type = "text/plain; charset=UTF-8", | |
| content = paste0("Upstream fetch failed: ", conditionMessage(content)) | |
| ) else | |
| httpResponse( | |
| status = 200, | |
| content_type = "text/html; charset=UTF-8", | |
| content = content | |
| ) | |
| } | |
| server <- function(input, output, session) {} | |
| shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment