Created
June 13, 2017 10:24
-
-
Save stephlocke/441ea493be926b76bac59452a3f57281 to your computer and use it in GitHub Desktop.
Call Microsoft Cognitive Services APIs in R
This file contains 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
library(httr) | |
library(jsonlite) | |
library(dplyr) | |
library(purrr) | |
cogapikey<-"XXX" | |
text=c("is this english?" | |
,"tak er der mere kage" | |
,"merci beaucoup" | |
,"guten morgen" | |
,"bonjour" | |
,"merde" | |
,"That's terrible" | |
,"R is awesome") | |
# Put data in an object that converts to the expected schema for the API | |
data_frame(text) %>% | |
mutate(id=row_number()) -> | |
textdf | |
textdf %>% | |
list(documents=.) -> | |
mydata | |
cogapi<-"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?numberOfLanguagesToDetect=1" | |
cogapi %>% | |
POST(add_headers(`Ocp-Apim-Subscription-Key`=cogapikey), | |
body=toJSON(mydata)) -> | |
response | |
# Process response | |
response %>% | |
content() %>% | |
flatten_df() %>% | |
select(detectedLanguages) %>% | |
flatten_df()-> | |
respframe | |
textdf %>% | |
mutate(language= respframe$iso6391Name) -> | |
textdf | |
# New info | |
mydata<-list(documents = textdf) | |
# New endpoint | |
cogapi<-"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment" | |
# Construct a request | |
cogapi %>% | |
POST(add_headers(`Ocp-Apim-Subscription-Key`=cogapikey), | |
body=toJSON(mydata)) -> | |
response | |
# Process response | |
response %>% | |
content() %>% | |
flatten_df() %>% | |
mutate(id=as.numeric(id))-> | |
respframe | |
# Combine | |
textdf %>% | |
left_join(respframe) -> | |
textdf | |
knitr::kable(textdf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Process response
response %>%
Error in overscope_eval_next(overscope, expr) :
object 'detectedLanguages' not found
Error in mutate_impl(.data, dots) :
Evaluation error: object 'respframe' not found.
Sorry, your code not run at this point