Skip to content

Commit

Permalink
feat: detect language
Browse files Browse the repository at this point in the history
  • Loading branch information
tin900 committed Jun 16, 2023
1 parent fe5b3f4 commit 81eb41a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

export("%>%")
export(google_translate)
export(language_detect)
export(mymemory_translate)
export(translate_file)
importFrom(magrittr,"%>%")
27 changes: 27 additions & 0 deletions R/language_detect.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#' Detect Language using Google Translate API
#'
#' This function detects the language of a given text using the Google Translate API.
#'
#' @param text The text for which the language needs to be detected.
#' @return A character string representing the detected language.
#' @export
language_detect <- function(text) {
url <- "https://translate.googleapis.com/translate_a/single"
params <- list(
client = "gtx",
sl = "auto",
tl = "en",
dt = "t",
q = text
)

response <- httr::GET(url, query = params)

if (httr::status_code(response) == 200) {
result <- httr::content(response, "parsed")
language <- purrr::keep(result, is.character) %>% as.character()
return(language)
} else {
stop("Language detection failed. Please check your connection and try again.")
}
}
17 changes: 17 additions & 0 deletions man/language_detect.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions vignettes/Movie_Reviews.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ Now, let's translate the review column to French using the `polyglotr` package:
```{r translated}
# Translate the review column to French
translated_reviews <- df %>%
dplyr::mutate(french_review = purrr::map(review, ~ google_translate(.x, target_language = "fr", source_language = "en")))
dplyr::mutate(french_review = purrr::map_chr(review, ~ google_translate(.x, target_language = "fr", source_language = "en")))
```


In the code snippet above, we utilize the `mutate` function from `dplyr` in conjunction with `purrr::map` to apply the google_translate function from the package to each element in the review column. The translated reviews are stored in a new column named "french_review".
In the code snippet above, we utilize the `mutate` function from `dplyr` in conjunction with `purrr::map_chr` to apply the google_translate function from the package to each element in the review column. The translated reviews are stored in a new column named "french_review".

# Results

Expand Down

0 comments on commit 81eb41a

Please sign in to comment.