| 1 |
.onLoad <- function(lib, pkg) {
|
|
| 2 | ! |
if (Sys.getenv("RECEPTIVITI_URL") == "") Sys.setenv(RECEPTIVITI_URL = "https://api.receptiviti.com/")
|
| 3 |
} |
|
| 4 | ||
| 5 |
#' Receptiviti API |
|
| 6 |
#' |
|
| 7 |
#' The main function to access the \href{https://www.receptiviti.com}{Receptiviti} API.
|
|
| 8 |
#' |
|
| 9 |
#' @param text A character vector with text to be processed, path to a directory containing files, or a vector of file paths. |
|
| 10 |
#' If a single path to a directory, each file is collapsed to a single text. If a path to a file or files, |
|
| 11 |
#' each line or row is treated as a separate text, unless \code{collapse_lines} is \code{TRUE}.
|
|
| 12 |
#' @param output Path to a \code{.csv} file to write results to. If this already exists, set \code{overwrite} to \code{TRUE}
|
|
| 13 |
#' to overwrite it. |
|
| 14 |
#' @param id Vector of unique IDs the same length as \code{text}, to be included in the results.
|
|
| 15 |
#' @param text_column,id_column Column name of text/id, if \code{text} is a matrix-like object, or a path to a csv file.
|
|
| 16 |
#' @param file_type File extension to search for, if \code{text} is the path to a directory containing files to be read in.
|
|
| 17 |
#' @param return_text Logical; if \code{TRUE}, \code{text} is included as the first column of the result.
|
|
| 18 |
#' @param frameworks A vector of frameworks to include results from. Texts are always scored with all available framework -- |
|
| 19 |
#' this just specifies what to return. Defaults to \code{all}, to return all scored frameworks. Can be set by the
|
|
| 20 |
#' \code{receptiviti_frameworks} option (e.g., \code{options(receptiviti_frameworks = c("liwc", "sallee"))}).
|
|
| 21 |
#' @param framework_prefix Logical; if \code{FALSE}, will remove the framework prefix from column names, which may result in duplicates.
|
|
| 22 |
#' If this is not specified, and 1 framework is selected, or \code{as_list} is \code{TRUE}, will default to remove prefixes.
|
|
| 23 |
#' @param as_list Logical; if \code{TRUE}, returns a list with frameworks in separate entries.
|
|
| 24 |
#' @param bundle_size Number of texts to include in each request; between 1 and 1,000. |
|
| 25 |
#' @param collapse_lines Logical; if \code{TRUE}, and \code{text} contains paths to files, each file is treated as a single text.
|
|
| 26 |
#' @param retry_limit Maximum number of times each request can be retried after hitting a rate limit. |
|
| 27 |
#' @param overwrite Logical; if \code{TRUE}, will overwrite an existing \code{output} file.
|
|
| 28 |
#' @param compress Logical; if \code{TRUE}, will save as an \code{xz}-compressed file.
|
|
| 29 |
#' @param make_request Logical; if \code{FALSE}, a request is not made. This could be useful if you want to be sure and
|
|
| 30 |
#' load from one of the caches, but aren't sure that all results exist there; it will error out if it encounters |
|
| 31 |
#' texts it has no other source for. |
|
| 32 |
#' @param text_as_paths Logical; if \code{TRUE}, ensures \code{text} is treated as a vector of file paths. Otherwise, this will be
|
|
| 33 |
#' determined if there are no \code{NA}s in \code{text} and every entry is under 500 characters long.
|
|
| 34 |
#' @param cache Path to a directory in which to save unique results for reuse; defaults to \code{Sys.getenv("RECEPTIVITI_CACHE")}.
|
|
| 35 |
#' See the Cache section for details. |
|
| 36 |
#' @param cache_overwrite Logical; if \code{TRUE}, will write results to the cache without reading from it. This could be used
|
|
| 37 |
#' if you want fresh results to be cached without clearing the cache. |
|
| 38 |
#' @param cache_format Format of the cache database; see \code{\link[arrow]{FileFormat}}.
|
|
| 39 |
#' Defaults to \code{Sys.getenv("RECEPTIVITI_CACHE_FORMAT")}.
|
|
| 40 |
#' @param clear_cache Logical; if \code{TRUE}, will clear any existing files in the cache. Use \code{cache_overwrite} if
|
|
| 41 |
#' you want fresh results without clearing or disabling the cache. Use \code{cache = FALSE} to disable the cache.
|
|
| 42 |
#' @param request_cache Logical; if \code{FALSE}, will always make a fresh request, rather than using the response
|
|
| 43 |
#' from a previous identical request. |
|
| 44 |
#' @param cores Number of CPU cores to split bundles across, if there are multiple bundles. See the Parallelization section. |
|
| 45 |
#' @param use_future Logical; if \code{TRUE}, uses a \code{future} back-end to process bundles, in which case,
|
|
| 46 |
#' parallelization can be controlled with the \code{\link[future]{plan}} function (e.g., \code{plan("multisession")}
|
|
| 47 |
#' to use multiple cores); this is required to see progress bars when using multiple cores. See the Parallelization section. |
|
| 48 |
#' @param in_memory Logical; if \code{FALSE}, will write bundles to temporary files, and only load them as they are being requested.
|
|
| 49 |
#' @param clear_scratch_cache Logical; if \code{FALSE}, will preserve the bundles written when \code{in_memory} is \code{TRUE}, after
|
|
| 50 |
#' the request has been made. |
|
| 51 |
#' @param verbose Logical; if \code{TRUE}, will show status messages.
|
|
| 52 |
#' @param key API Key; defaults to \code{Sys.getenv("RECEPTIVITI_KEY")}.
|
|
| 53 |
#' @param secret API Secret; defaults to \code{Sys.getenv("RECEPTIVITI_SECRET")}.
|
|
| 54 |
#' @param url API endpoint; defaults to \code{Sys.getenv("RECEPTIVITI_URL")}, which defaults to
|
|
| 55 |
#' \code{"https://api.receptiviti.com/"}.
|
|
| 56 |
#' @param include_headers Logical; if \code{TRUE}, \code{receptiviti_status}'s verbose message will include
|
|
| 57 |
#' the HTTP headers. |
|
| 58 |
#' |
|
| 59 |
#' @returns A \code{data.frame} with columns for \code{text} (if \code{return_text} is \code{TRUE}; the originally entered text),
|
|
| 60 |
#' \code{id} (if one was provided), \code{text_hash} (the MD5 hash of the text), and scores from each included framework
|
|
| 61 |
#' (e.g., \code{summary.word_count} and \code{liwc.i}). If \code{as_list} is \code{TRUE}, returns a list
|
|
| 62 |
#' with a named entry containing such a \code{data.frame} for each framework.
|
|
| 63 |
#' |
|
| 64 |
#' @section Cache: |
|
| 65 |
#' By default, results for unique texts are saved in an \href{https://arrow.apache.org}{Arrow} database in the
|
|
| 66 |
#' cache location (\code{Sys.getenv("RECEPTIVITI_CACHE")}), and are retrieved with subsequent requests.
|
|
| 67 |
#' This ensures that the exact same texts are not re-sent to the API. |
|
| 68 |
#' This does, however, add some processing time and disc space usage. |
|
| 69 |
#' |
|
| 70 |
#' If a cache location is not specified, a default directory (\code{receptiviti_cache}) will be looked for
|
|
| 71 |
#' in the system's temporary directory (which is usually the parent of \code{tempdir()}).
|
|
| 72 |
#' If this does not exist, you will be asked if it should be created. You can disable this prompt with the |
|
| 73 |
#' \code{receptiviti.cache_prompt} option (\code{options(receptiviti.cache_prompt = FALSE)}).
|
|
| 74 |
#' |
|
| 75 |
#' The \code{cache_format} arguments (or the \code{RECEPTIVITI_CACHE_FORMAT} environment variable) can be used to adjust the format of the cache.
|
|
| 76 |
#' |
|
| 77 |
#' You can use the cache independently with \code{open_database(Sys.getenv("RECEPTIVITI_CACHE"))}.
|
|
| 78 |
#' |
|
| 79 |
#' You can set the \code{cache} argument to \code{FALSE} to prevent the cache from being used, which might make sense if
|
|
| 80 |
#' you don't expect to need to reprocess it. |
|
| 81 |
#' |
|
| 82 |
#' You can also set the \code{clear_cache} argument to \code{TRUE} to clear the cache before it is used again, which may be useful
|
|
| 83 |
#' if the cache has gotten big, or you know new results will be returned. Even if a cached result exists, it will be |
|
| 84 |
#' reprocessed if it does not have all of the variables of new results, but this depends on there being at least 1 uncached |
|
| 85 |
#' result. If, for instance, you add a framework to your account and want to reprocess a previously processed set of texts, |
|
| 86 |
#' you would need to first clear the cache. |
|
| 87 |
#' |
|
| 88 |
#' Either way, duplicated texts within the same call will only be sent once. |
|
| 89 |
#' |
|
| 90 |
#' The \code{request_cache} argument controls a more temporary cache of each bundle request. This is cleared when the
|
|
| 91 |
#' R session ends. You might want to set this to \code{FALSE} if a new framework becomes available on your account
|
|
| 92 |
#' and you want to process a set of text you already processed in the current R session without restarting. |
|
| 93 |
#' |
|
| 94 |
#' Another temporary cache is made when \code{in_memory} is \code{FALSE}, which is the default when processing
|
|
| 95 |
#' in parallel (when \code{cores} is over \code{1} or \code{use_future} is \code{TRUE}). This contains
|
|
| 96 |
#' a file for each unique bundle, which is read by as needed by the parallel workers. |
|
| 97 |
#' |
|
| 98 |
#' @section Parallelization: |
|
| 99 |
#' \code{text}s are split into bundles based on the \code{bundle_size} argument. Each bundle represents
|
|
| 100 |
#' a single request to the API, which is why they are limited to 1000 texts and a total size of 10 MB. |
|
| 101 |
#' When there is more than one bundle and either \code{cores} is greater than 1 or \code{use_future} is \code{TRUE} (and you've
|
|
| 102 |
#' externally specified a \code{\link[future]{plan}}), bundles are processed by multiple cores.
|
|
| 103 |
#' |
|
| 104 |
#' Using \code{future} also allows for progress bars to be specified externally with \code{\link[progressr]{handlers}}; see examples.
|
|
| 105 |
#' @examples |
|
| 106 |
#' \dontrun{
|
|
| 107 |
#' |
|
| 108 |
#' # check that the API is available, and your credentials work |
|
| 109 |
#' receptiviti_status() |
|
| 110 |
#' |
|
| 111 |
#' # score a single text |
|
| 112 |
#' single <- receptiviti("a text to score")
|
|
| 113 |
#' |
|
| 114 |
#' # score multiple texts, and write results to a file |
|
| 115 |
#' multi <- receptiviti(c("first text to score", "second text"), "filename.csv")
|
|
| 116 |
#' |
|
| 117 |
#' # score many texts in separate files |
|
| 118 |
#' ## defaults to look for .txt files |
|
| 119 |
#' file_results <- receptiviti("./path/to/txt_folder")
|
|
| 120 |
#' |
|
| 121 |
#' ## could be .csv |
|
| 122 |
#' file_results <- receptiviti( |
|
| 123 |
#' "./path/to/csv_folder", |
|
| 124 |
#' text_column = "text", file_type = "csv" |
|
| 125 |
#' ) |
|
| 126 |
#' |
|
| 127 |
#' # score many texts from a file, with a progress bar |
|
| 128 |
#' ## set up cores and progress bar (only necessary if you want the progress bar) |
|
| 129 |
#' future::plan("multisession")
|
|
| 130 |
#' progressr::handlers(global = TRUE) |
|
| 131 |
#' progressr::handlers("progress")
|
|
| 132 |
#' |
|
| 133 |
#' ## make request |
|
| 134 |
#' results <- receptiviti( |
|
| 135 |
#' "./path/to/largefile.csv", |
|
| 136 |
#' text_column = "text", use_future = TRUE |
|
| 137 |
#' ) |
|
| 138 |
#' } |
|
| 139 |
#' @importFrom curl new_handle curl_fetch_memory curl_fetch_disk |
|
| 140 |
#' @importFrom jsonlite toJSON fromJSON read_json |
|
| 141 |
#' @importFrom utils object.size |
|
| 142 |
#' @importFrom digest digest |
|
| 143 |
#' @importFrom parallel detectCores makeCluster clusterExport parLapplyLB parLapply stopCluster |
|
| 144 |
#' @importFrom future.apply future_lapply |
|
| 145 |
#' @importFrom progressr progressor |
|
| 146 |
#' @importFrom arrow read_csv_arrow write_csv_arrow schema string write_dataset open_dataset |
|
| 147 |
#' @importFrom dplyr filter compute collect select |
|
| 148 |
#' @export |
|
| 149 | ||
| 150 |
receptiviti <- function(text, output = NULL, id = NULL, text_column = NULL, id_column = NULL, file_type = "txt", return_text = FALSE, |
|
| 151 |
frameworks = getOption("receptiviti_frameworks", "all"), framework_prefix = TRUE, as_list = FALSE,
|
|
| 152 |
bundle_size = 1000, collapse_lines = FALSE, retry_limit = 10, clear_cache = FALSE, clear_scratch_cache = TRUE, |
|
| 153 |
request_cache = TRUE, cores = detectCores() - 1, use_future = FALSE, in_memory = TRUE, verbose = FALSE, |
|
| 154 |
overwrite = FALSE, compress = FALSE, make_request = TRUE, text_as_paths = FALSE, cache = Sys.getenv("RECEPTIVITI_CACHE"),
|
|
| 155 |
cache_overwrite = FALSE, cache_format = Sys.getenv("RECEPTIVITI_CACHE_FORMAT", "parquet"),
|
|
| 156 |
key = Sys.getenv("RECEPTIVITI_KEY"), secret = Sys.getenv("RECEPTIVITI_SECRET"), url = Sys.getenv("RECEPTIVITI_URL")) {
|
|
| 157 |
# check input |
|
| 158 | 52x |
final_res <- text_hash <- bin <- NULL |
| 159 | 52x |
if (!is.null(output)) {
|
| 160 | ! |
if (!file.exists(output) && file.exists(paste0(output, ".xz"))) output <- paste0(output, ".xz") |
| 161 | 1x |
if (!overwrite && file.exists(output)) stop("output file already exists; use overwrite = TRUE to overwrite it", call. = FALSE)
|
| 162 |
} |
|
| 163 | 51x |
if (cache == "") {
|
| 164 | 16x |
temp <- dirname(tempdir()) |
| 165 | ! |
if (basename(temp) == "working_dir") temp <- dirname(dirname(temp)) |
| 166 | 16x |
cache <- paste0(temp, "/receptiviti_cache") |
| 167 | 16x |
if (!dir.exists(cache)) {
|
| 168 | ! |
if (interactive() && !isFALSE(getOption("receptiviti.cache_prompt")) &&
|
| 169 | ! |
grepl("^(?:[Yy1]|$)", readline("Do you want to establish a default cache? [Y/n] "))) {
|
| 170 | ! |
dir.create(cache, FALSE) |
| 171 |
} else {
|
|
| 172 | ! |
options(receptiviti.cache_prompt = FALSE) |
| 173 | ! |
cache <- "" |
| 174 |
} |
|
| 175 |
} |
|
| 176 |
} |
|
| 177 | 51x |
st <- proc.time()[[3]] |
| 178 | 51x |
if (is.null(final_res)) {
|
| 179 | 1x |
if (missing(text)) stop("enter text as the first argument", call. = FALSE)
|
| 180 | 50x |
if (text_as_paths) {
|
| 181 | 1x |
if (anyNA(text)) stop("NAs are not allowed in text when being treated as file paths", call. = FALSE)
|
| 182 | 1x |
if (!all(file.exists(text))) stop("not all of the files in text exist", call. = FALSE)
|
| 183 |
} |
|
| 184 | 48x |
read_in <- FALSE |
| 185 | 48x |
if (text_as_paths || (is.character(text) && !anyNA(text) && all(nchar(text) < 500))) {
|
| 186 | 31x |
if (length(text) == 1 && dir.exists(text)) {
|
| 187 | ! |
if (verbose) message("reading in texts from directory: ", text, " (", round(proc.time()[[3]] - st, 4), ")")
|
| 188 | 4x |
text_as_paths <- TRUE |
| 189 | 4x |
text <- list.files(text, file_type, full.names = TRUE) |
| 190 | 27x |
} else if (text_as_paths || all(file.exists(text))) {
|
| 191 | 5x |
text_as_paths <- FALSE |
| 192 | ! |
if (verbose) message("reading in texts from file list (", round(proc.time()[[3]] - st, 4), ")")
|
| 193 | 4x |
if (missing(id_column)) names(text) <- if (length(id) != length(text)) text else id |
| 194 | 5x |
if (all(grepl(".csv", text, fixed = TRUE))) {
|
| 195 | 1x |
if (is.null(text_column)) stop("text appears to point to csv files, but text_column was not specified", call. = FALSE)
|
| 196 | 2x |
read_in <- TRUE |
| 197 | 2x |
text <- unlist(lapply(text, function(f) {
|
| 198 | 2x |
if (file.exists(f)) {
|
| 199 | 2x |
d <- read_csv_arrow(f) |
| 200 | 2x |
d <- if (!is.null(id_column) && id_column %in% colnames(d)) {
|
| 201 | 1x |
structure(d[, text_column, drop = TRUE], names = d[, id_column, drop = TRUE]) |
| 202 |
} else {
|
|
| 203 | 1x |
d[, text_column, drop = TRUE] |
| 204 |
} |
|
| 205 | ! |
if (collapse_lines) d <- paste(d, collapse = " ") |
| 206 | 2x |
d |
| 207 |
} else {
|
|
| 208 | ! |
f |
| 209 |
} |
|
| 210 |
})) |
|
| 211 |
} else {
|
|
| 212 | 2x |
text <- unlist(lapply(text, function(f) {
|
| 213 | 2x |
if (file.exists(f)) {
|
| 214 | 2x |
d <- readLines(f, warn = FALSE, skipNul = TRUE) |
| 215 | 1x |
if (collapse_lines) d <- paste(d, collapse = " ") |
| 216 | 2x |
d |
| 217 |
} else {
|
|
| 218 | ! |
f |
| 219 |
} |
|
| 220 |
})) |
|
| 221 |
} |
|
| 222 | 3x |
if (!collapse_lines) id <- names(text) |
| 223 |
} |
|
| 224 |
} |
|
| 225 | 47x |
if (is.null(dim(text))) {
|
| 226 | 41x |
if (!read_in) {
|
| 227 | 1x |
if (!text_as_paths && !is.null(text_column)) stop("text_column is specified, but text has no columns", call. = FALSE)
|
| 228 | 1x |
if (!is.null(id_column)) stop("id_column is specified, but text has no columns", call. = FALSE)
|
| 229 |
} |
|
| 230 |
} else {
|
|
| 231 | 1x |
if (length(id) == 1 && id %in% colnames(text)) id_column <- id |
| 232 | 6x |
if (!is.null(id_column)) {
|
| 233 | 2x |
if (id_column %in% colnames(text)) {
|
| 234 | 1x |
id <- text[, id_column, drop = TRUE] |
| 235 |
} else {
|
|
| 236 | 1x |
stop("id_column not found in text", call. = FALSE)
|
| 237 |
} |
|
| 238 |
} |
|
| 239 | 5x |
if (!is.null(text_column)) {
|
| 240 | 3x |
if (text_column %in% colnames(text)) {
|
| 241 | 2x |
text <- text[, text_column, drop = TRUE] |
| 242 |
} else {
|
|
| 243 | 1x |
if (!text_as_paths) stop("text_column not found in text", call. = FALSE)
|
| 244 |
} |
|
| 245 |
} |
|
| 246 | 4x |
if (!is.null(dim(text))) {
|
| 247 | 2x |
if (ncol(text) == 1) {
|
| 248 | 1x |
text <- text[, 1, drop = TRUE] |
| 249 |
} else {
|
|
| 250 | 1x |
stop("text has dimensions, but no text_column column", call. = FALSE)
|
| 251 |
} |
|
| 252 |
} |
|
| 253 |
} |
|
| 254 | 2x |
if (!is.character(text)) text <- as.character(text) |
| 255 | 4x |
if (length(id) && !is.character(id)) id <- as.character(id) |
| 256 | 42x |
provided_id <- FALSE |
| 257 | 42x |
if (length(id)) {
|
| 258 | 1x |
if (length(id) != length(text)) stop("id is not the same length as text", call. = FALSE)
|
| 259 | 1x |
if (anyDuplicated(id)) stop("id contains duplicate values", call. = FALSE)
|
| 260 | 6x |
provided_id <- TRUE |
| 261 |
} else {
|
|
| 262 | 34x |
id <- paste0("t", seq_along(text))
|
| 263 |
} |
|
| 264 | 1x |
if (!is.numeric(retry_limit)) retry_limit <- 0 |
| 265 | 40x |
url <- paste0(sub("(?:/v\\d+)?/+$", "", url), "/v1/")
|
| 266 | ||
| 267 |
# ping API |
|
| 268 | 40x |
if (make_request) {
|
| 269 | 2x |
if (verbose) message("pinging API (", round(proc.time()[[3]] - st, 4), ")")
|
| 270 | 38x |
ping <- receptiviti_status(url, key, secret, verbose = FALSE) |
| 271 | 1x |
if (ping$status_code != 200) stop(ping$status_message, call. = FALSE) |
| 272 |
} |
|
| 273 | ||
| 274 |
# prepare text |
|
| 275 | 2x |
if (verbose) message("preparing text (", round(proc.time()[[3]] - st, 4), ")")
|
| 276 | 37x |
data <- data.frame(text = text, id = id, stringsAsFactors = FALSE) |
| 277 | 37x |
text <- data[!is.na(data$text) & data$text != "" & !duplicated(data$text), ] |
| 278 | 1x |
if (!nrow(text)) stop("no valid texts to process", call. = FALSE)
|
| 279 | 1x |
if (!is.numeric(bundle_size)) bundle_size <- 1000 |
| 280 | 36x |
n <- ceiling(nrow(text) / min(1000, max(1, bundle_size))) |
| 281 | 36x |
bundles <- split(text, sort(rep_len(seq_len(n), nrow(text)))) |
| 282 | 36x |
size_fun <- if (text_as_paths) function(b) sum(file.size(b$text)) else object.size |
| 283 | 36x |
for (i in seq_along(bundles)) {
|
| 284 | 146x |
size <- size_fun(bundles[[i]]) |
| 285 | 146x |
if (size > 1e7) {
|
| 286 | 2x |
sizes <- vapply(seq_len(nrow(bundles[[i]])), function(r) as.numeric(size_fun(bundles[[i]][r, ])), 0) |
| 287 | 1x |
if (any(sizes > 1e7)) stop("one of your texts is over the individual size limit (10 MB)", call. = FALSE)
|
| 288 | 1x |
bins <- rep(1, length(sizes)) |
| 289 | 1x |
bin_size <- 0 |
| 290 | 1x |
bi <- 1 |
| 291 | 1x |
for (ti in seq_along(bins)) {
|
| 292 | 51x |
bin_size <- bin_size + sizes[ti] |
| 293 | 51x |
if (bin_size > 1e7) {
|
| 294 | 1x |
bin_size <- sizes[ti] |
| 295 | 1x |
bi <- bi + 1 |
| 296 |
} |
|
| 297 | 51x |
bins[ti] <- bi |
| 298 |
} |
|
| 299 | 1x |
bundles <- c(bundles[-i], unname(split(bundles[[i]], paste0(i, ".", bins)))) |
| 300 |
} |
|
| 301 |
} |
|
| 302 | 35x |
n <- length(bundles) |
| 303 | 35x |
bundle_ref <- if (n == 1) "bundle" else "bundles" |
| 304 | 2x |
if (verbose) message("prepared text in ", n, " ", bundle_ref, " (", round(proc.time()[[3]] - st, 4), ")")
|
| 305 | ||
| 306 |
# prepare cache |
|
| 307 | 35x |
if (is.character(cache)) {
|
| 308 | 27x |
temp <- paste0(normalizePath(cache, "/", FALSE), "/") |
| 309 | 27x |
cache <- TRUE |
| 310 | 2x |
if (clear_cache) unlink(temp, recursive = TRUE) |
| 311 | 27x |
dir.create(temp, FALSE) |
| 312 |
} else {
|
|
| 313 | 8x |
temp <- NULL |
| 314 | 8x |
cache <- FALSE |
| 315 |
} |
|
| 316 | ||
| 317 | 35x |
check_cache <- cache && !cache_overwrite |
| 318 | 35x |
endpoint <- paste0(url, "framework/bulk") |
| 319 | 35x |
auth <- paste0(key, ":", secret) |
| 320 | ! |
if (missing(in_memory) && (use_future || cores > 1) && n > cores) in_memory <- FALSE |
| 321 | 35x |
request_scratch <- NULL |
| 322 | 35x |
if (!in_memory) {
|
| 323 | ! |
if (verbose) message("writing ", bundle_ref, " to disc (", round(proc.time()[[3]] - st, 4), ")")
|
| 324 | 2x |
request_scratch <- paste0(tempdir(), "/receptiviti_request_scratch/") |
| 325 | 2x |
dir.create(request_scratch, FALSE) |
| 326 | 2x |
if (clear_scratch_cache) on.exit(unlink(request_scratch, recursive = TRUE)) |
| 327 | 2x |
bundles <- vapply(bundles, function(b) {
|
| 328 | 6x |
scratch_bundle <- paste0(request_scratch, digest(b), ".rds") |
| 329 | 6x |
if (!file.exists(scratch_bundle)) saveRDS(b, scratch_bundle, compress = FALSE) |
| 330 | 6x |
scratch_bundle |
| 331 | 2x |
}, "", USE.NAMES = FALSE) |
| 332 |
} |
|
| 333 | ||
| 334 | 35x |
doprocess <- function(bundles, cores, future) {
|
| 335 | 5x |
env <- parent.frame() |
| 336 | 5x |
if (future) {
|
| 337 | 1x |
eval(expression(future.apply::future_lapply(bundles, process)), envir = env) |
| 338 |
} else {
|
|
| 339 | 4x |
cl <- parallel::makeCluster(cores) |
| 340 | 4x |
parallel::clusterExport(cl, ls(envir = env), env) |
| 341 | 4x |
on.exit(parallel::stopCluster(cl)) |
| 342 | 4x |
(if (length(bundles) > cores * 2) parallel::parLapplyLB else parallel::parLapply)(cl, bundles, process) |
| 343 |
} |
|
| 344 |
} |
|
| 345 | ||
| 346 | 35x |
request <- function(body, bin, ids, attempt = retry_limit) {
|
| 347 | 128x |
unpack <- function(d) {
|
| 348 | 15721x |
if (is.list(d)) as.data.frame(lapply(d, unpack), optional = TRUE) else d |
| 349 |
} |
|
| 350 | 128x |
json <- jsonlite::toJSON(body, auto_unbox = TRUE) |
| 351 | 128x |
temp_file <- paste0(tempdir(), "/", digest::digest(json, serialize = FALSE), ".json") |
| 352 | 119x |
if (!request_cache) unlink(temp_file) |
| 353 | 128x |
res <- NULL |
| 354 | 128x |
if (!file.exists(temp_file)) {
|
| 355 | 124x |
if (make_request) {
|
| 356 | 123x |
handler <- curl::new_handle( |
| 357 | 123x |
httpauth = 1, userpwd = auth, |
| 358 | 123x |
copypostfields = jsonlite::toJSON(unname(body), auto_unbox = TRUE) |
| 359 |
) |
|
| 360 | 123x |
res <- curl::curl_fetch_disk(endpoint, temp_file, handler) |
| 361 |
} else {
|
|
| 362 | 1x |
stop("make_request is FALSE, but there are texts with no cached results", call. = FALSE)
|
| 363 |
} |
|
| 364 |
} |
|
| 365 | 127x |
result <- if (file.exists(temp_file)) {
|
| 366 | 127x |
jsonlite::read_json(temp_file, simplifyVector = TRUE) |
| 367 |
} else {
|
|
| 368 | ! |
list(message = rawToChar(res$content)) |
| 369 |
} |
|
| 370 | 127x |
if (!is.null(result$results)) {
|
| 371 | 79x |
result <- result$results |
| 372 | 79x |
if ("error" %in% names(result)) {
|
| 373 | ! |
su <- !is.na(result$error$code) |
| 374 | ! |
errors <- result[su & !duplicated(result$error$code), "error"] |
| 375 | ! |
warning( |
| 376 | ! |
if (sum(su) > 1) "some texts were invalid: " else "a text was invalid: ", |
| 377 | ! |
paste( |
| 378 | ! |
do.call(paste0, data.frame("(", errors$code, ") ", errors$message, stringsAsFactors = FALSE)),
|
| 379 | ! |
collapse = "; " |
| 380 |
), |
|
| 381 | ! |
call. = FALSE |
| 382 |
) |
|
| 383 |
} |
|
| 384 | 79x |
result <- unpack(result[!names(result) %in% c("response_id", "language", "version", "error")])
|
| 385 | 79x |
if (!is.null(result) && nrow(result)) {
|
| 386 | 79x |
colnames(result)[1] <- "text_hash" |
| 387 | 79x |
cbind(id = ids, bin = bin, result) |
| 388 |
} |
|
| 389 |
} else {
|
|
| 390 | ! |
if (substr(result$message, 1, 1) == "{") result <- jsonlite::fromJSON(result$message)
|
| 391 | 48x |
if (!is.null(result$code) && result$code == 1420 && attempt > 0) {
|
| 392 | 47x |
unlink(temp_file) |
| 393 | 47x |
wait_time <- as.numeric(regmatches(result$message, regexec("[0-9]+(?:\\.[0-9]+)?", result$message)))
|
| 394 | 47x |
Sys.sleep(if (is.na(wait_time)) 1 else wait_time / 1e3) |
| 395 | 47x |
request(body, bin, ids, attempt - 1) |
| 396 |
} else {
|
|
| 397 | 1x |
stop(paste0(if (length(result$code)) {
|
| 398 | 1x |
paste0( |
| 399 | 1x |
if (is.null(res$status_code)) 200 else res$status_code, " (", result$code, "): "
|
| 400 |
) |
|
| 401 | 1x |
}, result$message), call. = FALSE) |
| 402 |
} |
|
| 403 |
} |
|
| 404 |
} |
|
| 405 | ||
| 406 | 35x |
process <- function(bundle) {
|
| 407 | 101x |
opts <- getOption("stringsAsFactors")
|
| 408 | 101x |
options("stringsAsFactors" = FALSE)
|
| 409 | 101x |
on.exit(options("stringsAsFactors" = opts))
|
| 410 | 1x |
if (is.character(bundle)) bundle <- readRDS(bundle) |
| 411 | 101x |
text <- bundle$text |
| 412 | 101x |
bin <- NULL |
| 413 | 101x |
if (text_as_paths) {
|
| 414 | 2x |
if (all(grepl("\\.csv", text))) {
|
| 415 | 1x |
if (is.null(text_column)) stop("files appear to be csv, but no text_column was specified", call. = FALSE)
|
| 416 | 1x |
text <- vapply(text, function(f) paste(arrow::read_csv_arrow(f)[, text_column], collapse = " "), "") |
| 417 |
} else {
|
|
| 418 | ! |
text <- vapply(text, function(f) paste(readLines(f, warn = FALSE, skipNul = TRUE), collapse = " "), "") |
| 419 |
} |
|
| 420 |
} |
|
| 421 | 100x |
bundle$hashes <- vapply(text, digest::digest, "", serialize = FALSE) |
| 422 | 100x |
initial <- paste0("h", substr(bundle$hashes, 1, 1))
|
| 423 | 100x |
set <- !is.na(text) & text != "" & text != "logical(0)" & !duplicated(bundle$hashes) |
| 424 | 100x |
res_cached <- res_fresh <- NULL |
| 425 | 100x |
if (check_cache && dir.exists(paste0(temp, "bin=h"))) {
|
| 426 | 23x |
db <- arrow::open_dataset(temp, partitioning = arrow::schema(bin = arrow::string()), format = cache_format) |
| 427 | 23x |
cached <- if (!is.null(db$schema$GetFieldByName("text_hash"))) {
|
| 428 | 23x |
tryCatch( |
| 429 | 23x |
dplyr::compute(dplyr::filter(db, bin %in% unique(initial), text_hash %in% bundle$hashes)), |
| 430 | 23x |
error = function(e) matrix(integer(), 0) |
| 431 |
) |
|
| 432 |
} else {
|
|
| 433 | ! |
matrix(integer(), 0) |
| 434 |
} |
|
| 435 | 23x |
if (nrow(cached)) {
|
| 436 | 21x |
cached <- as.data.frame(cached$to_data_frame()) |
| 437 | ! |
if (anyDuplicated(cached$text_hash)) cached <- cached[!duplicated(cached$text_hash), ] |
| 438 | 21x |
rownames(cached) <- cached$text_hash |
| 439 | 21x |
cached_set <- bundle$hashes %in% cached$text_hash |
| 440 | 21x |
set[cached_set] <- FALSE |
| 441 | 21x |
res_cached <- cbind(id = bundle[cached_set, "id"], cached[bundle[cached_set, "hashes"], ]) |
| 442 |
} |
|
| 443 |
} |
|
| 444 | 100x |
if (any(set)) {
|
| 445 | 81x |
set <- which(set) |
| 446 | 81x |
res_fresh <- request(lapply( |
| 447 | 81x |
set, function(i) list(content = text[[i]], request_id = bundle[i, "hashes"]) |
| 448 | 81x |
), initial[set], bundle[set, "id"]) |
| 449 | 79x |
if (check_cache && !is.null(res_cached) && !all(colnames(res_cached) %in% colnames(res_fresh))) {
|
| 450 | ! |
res_cached <- NULL |
| 451 | ! |
res_fresh <- rbind( |
| 452 | ! |
res_fresh, |
| 453 | ! |
request(lapply( |
| 454 | ! |
cached_set, function(i) list(content = text[[i]], request_id = bundle[i, "hashes"]) |
| 455 | ! |
), initial[cached_set], bundle[cached_set, "ids"]) |
| 456 |
) |
|
| 457 |
} |
|
| 458 |
} |
|
| 459 | 98x |
res <- rbind(res_cached, res_fresh) |
| 460 | 98x |
missing_ids <- !bundle$id %in% res$id |
| 461 | 98x |
if (any(missing_ids)) {
|
| 462 | 1x |
varnames <- colnames(res)[colnames(res) != "id"] |
| 463 | 1x |
res <- rbind(res, cbind( |
| 464 | 1x |
id = bundle[missing_ids, "id"], |
| 465 | 1x |
as.data.frame(matrix(NA, sum(missing_ids), length(varnames), dimnames = list(NULL, varnames))) |
| 466 |
)) |
|
| 467 |
} |
|
| 468 | 98x |
prog() |
| 469 | 98x |
res |
| 470 |
} |
|
| 471 | ||
| 472 |
# make request(s) |
|
| 473 | 35x |
cores <- if (is.numeric(cores)) max(1, min(length(bundles), cores)) else 1 |
| 474 | 35x |
call_env <- new.env(parent = globalenv()) |
| 475 | 35x |
prog <- progressor(along = bundles) |
| 476 | 35x |
environment(doprocess) <- call_env |
| 477 | 35x |
environment(request) <- call_env |
| 478 | 35x |
environment(process) <- call_env |
| 479 | 35x |
for (name in c( |
| 480 | 35x |
"doprocess", "request", "process", "text_column", "prog", "make_request", "check_cache", "endpoint", |
| 481 | 35x |
"temp", "use_future", "cores", "bundles", "cache_format", "request_cache", "auth", |
| 482 | 35x |
"text_as_paths", "retry_limit" |
| 483 |
)) {
|
|
| 484 | 595x |
call_env[[name]] <- get(name) |
| 485 |
} |
|
| 486 | 35x |
results <- if (use_future || cores > 1) {
|
| 487 | 5x |
if (verbose) {
|
| 488 | ! |
message( |
| 489 | ! |
"processing ", bundle_ref, " using ", if (use_future) "future backend" else paste(cores, "cores"), |
| 490 | ! |
" (", round(proc.time()[[3]] - st, 4), ")"
|
| 491 |
) |
|
| 492 |
} |
|
| 493 | 5x |
eval(expression(doprocess(bundles, cores, use_future)), envir = call_env) |
| 494 |
} else {
|
|
| 495 | 2x |
if (verbose) message("processing ", bundle_ref, " sequentially (", round(proc.time()[[3]] - st, 4), ")")
|
| 496 | 30x |
lapply(bundles, process) |
| 497 |
} |
|
| 498 | 2x |
if (verbose) message("done retrieving; preparing final results (", round(proc.time()[[3]] - st, 4), ")")
|
| 499 | 32x |
final_res <- do.call(rbind, results) |
| 500 | ||
| 501 |
# update cache |
|
| 502 | 32x |
if (!is.null(temp)) {
|
| 503 | 2x |
if (verbose) message("checking cache (", round(proc.time()[[3]] - st, 4), ")")
|
| 504 | 26x |
initialized <- dir.exists(paste0(temp, "bin=h")) |
| 505 | 26x |
if (initialized) {
|
| 506 | 24x |
db <- arrow::open_dataset(temp, partitioning = arrow::schema(bin = arrow::string()), format = cache_format) |
| 507 | 24x |
if (db$num_cols != (ncol(final_res) - 1)) {
|
| 508 | ! |
if (verbose) message("clearing existing cache since columns did not align (", round(proc.time()[[3]] - st, 4), ")")
|
| 509 | ! |
if (clear_cache) unlink(temp, recursive = TRUE) |
| 510 | ! |
dir.create(temp, FALSE) |
| 511 | ! |
initialized <- FALSE |
| 512 |
} |
|
| 513 |
} |
|
| 514 | 26x |
if (!initialized) {
|
| 515 | 2x |
initial <- final_res[1, -1] |
| 516 | 2x |
initial$text_hash <- "" |
| 517 | 2x |
initial$bin <- "h" |
| 518 | 2x |
initial[, !colnames(initial) %in% c( |
| 519 | 2x |
"bin", "text_hash", "summary.word_count", "summary.sentence_count" |
| 520 | 2x |
)] <- .1 |
| 521 | 2x |
initial <- rbind(initial, final_res[, -1]) |
| 522 | 2x |
if (verbose) {
|
| 523 | 1x |
message( |
| 524 | 1x |
"initializing cache with ", nrow(final_res), " result", |
| 525 | 1x |
if (nrow(final_res) > 1) "s", " (", round(proc.time()[[3]] - st, 4), ")"
|
| 526 |
) |
|
| 527 |
} |
|
| 528 | 2x |
arrow::write_dataset(initial, temp, partitioning = "bin", format = cache_format) |
| 529 |
} else {
|
|
| 530 | 24x |
fresh <- final_res[!duplicated(final_res$text_hash), -1] |
| 531 | 24x |
cached <- dplyr::filter(db, bin %in% unique(fresh$bin), text_hash %in% fresh$text_hash) |
| 532 | 24x |
if (!nrow(cached) || nrow(cached) != nrow(fresh)) {
|
| 533 | 5x |
uncached_hashes <- if (nrow(cached)) {
|
| 534 | 3x |
!fresh$text_hash %in% dplyr::collect(dplyr::select(cached, text_hash))[, 1] |
| 535 |
} else {
|
|
| 536 | 2x |
rep(TRUE, nrow(fresh)) |
| 537 |
} |
|
| 538 | 5x |
if (any(uncached_hashes)) {
|
| 539 | 5x |
if (verbose) {
|
| 540 | 1x |
message( |
| 541 | 1x |
"updating cache with ", sum(uncached_hashes), " result", |
| 542 | 1x |
if (sum(uncached_hashes) > 1) "s", " (", round(proc.time()[[3]] - st, 4), ")"
|
| 543 |
) |
|
| 544 |
} |
|
| 545 | 5x |
arrow::write_dataset(fresh[uncached_hashes, ], temp, partitioning = "bin", format = cache_format) |
| 546 |
} |
|
| 547 |
} |
|
| 548 |
} |
|
| 549 |
} |
|
| 550 | ||
| 551 |
# prepare final results |
|
| 552 | 2x |
if (verbose) message("preparing output (", round(proc.time()[[3]] - st, 4), ")")
|
| 553 | 32x |
rownames(final_res) <- final_res$id |
| 554 | 32x |
rownames(data) <- data$id |
| 555 | 32x |
data$text_hash <- structure(final_res$text_hash, names = data[final_res$id, "text"])[data$text] |
| 556 | 32x |
final_res <- cbind( |
| 557 | 32x |
data[, c(if (return_text) "text", if (provided_id) "id", "text_hash"), drop = FALSE], |
| 558 | 32x |
final_res[ |
| 559 | 32x |
structure(final_res$id, names = final_res$text_hash)[data$text_hash], |
| 560 | 32x |
!colnames(final_res) %in% c("id", "bin", "text_hash", "custom")
|
| 561 |
] |
|
| 562 |
) |
|
| 563 | 32x |
row.names(final_res) <- NULL |
| 564 | 32x |
if (!is.null(output)) {
|
| 565 | ! |
if (!grepl(".csv", output, fixed = TRUE)) output <- paste0(output, ".csv")
|
| 566 | 1x |
if (compress && !grepl(".xz", output, fixed = TRUE)) output <- paste0(output, ".xz")
|
| 567 | 1x |
if (grepl(".xz", output, fixed = TRUE)) compress <- TRUE
|
| 568 | 1x |
if (verbose) message("writing results to file: ", output, " (", round(proc.time()[[3]] - st, 4), ")")
|
| 569 | 3x |
dir.create(dirname(output), FALSE, TRUE) |
| 570 | 2x |
if (overwrite) unlink(output) |
| 571 | 1x |
if (compress) output <- xzfile(output) |
| 572 | 3x |
write_csv_arrow(final_res, file = output) |
| 573 |
} |
|
| 574 |
} |
|
| 575 | 32x |
if (is.character(frameworks) && frameworks[1] != "all") {
|
| 576 | ! |
if (verbose) message("selecting frameworks (", round(proc.time()[[3]] - st, 4), ")")
|
| 577 | 4x |
vars <- colnames(final_res) |
| 578 | 4x |
sel <- grepl(paste0("^(?:", paste(tolower(frameworks), collapse = "|"), ")"), vars)
|
| 579 | 4x |
if (any(sel)) {
|
| 580 | 1x |
if (missing(framework_prefix) && (length(frameworks) == 1 && frameworks != "all")) framework_prefix <- FALSE |
| 581 | 3x |
sel <- unique(c("text", "id", "text_hash", vars[sel]))
|
| 582 | 3x |
sel <- sel[sel %in% vars] |
| 583 | 3x |
final_res <- final_res[, sel] |
| 584 |
} else {
|
|
| 585 | 1x |
warning("frameworks did not match any columns -- returning all", call. = FALSE)
|
| 586 |
} |
|
| 587 |
} |
|
| 588 | 32x |
if (as_list) {
|
| 589 | 1x |
if (missing(framework_prefix)) framework_prefix <- FALSE |
| 590 | 1x |
inall <- c("text", "id", "text_hash")
|
| 591 | 1x |
cols <- colnames(final_res) |
| 592 | 1x |
inall <- inall[inall %in% cols] |
| 593 | 1x |
pre <- sub("\\..*$", "", cols)
|
| 594 | 1x |
pre <- unique(pre[!pre %in% inall]) |
| 595 | 1x |
final_res <- lapply(structure(pre, names = pre), function(f) {
|
| 596 | 9x |
res <- final_res[, c(inall, grep(paste0("^", f), cols, value = TRUE))]
|
| 597 | 9x |
if (!framework_prefix) colnames(res) <- sub("^.+\\.", "", colnames(res))
|
| 598 | 9x |
res |
| 599 |
}) |
|
| 600 | 2x |
} else if (!framework_prefix) colnames(final_res) <- sub("^.+\\.", "", colnames(final_res))
|
| 601 | 2x |
if (verbose) message("done (", round(proc.time()[[3]] - st, 4), ")")
|
| 602 | 32x |
invisible(final_res) |
| 603 |
} |
| 1 |
#' @rdname receptiviti |
|
| 2 |
#' @export |
|
| 3 | ||
| 4 |
receptiviti_status <- function(url = Sys.getenv("RECEPTIVITI_URL"), key = Sys.getenv("RECEPTIVITI_KEY"),
|
|
| 5 |
secret = Sys.getenv("RECEPTIVITI_SECRET"), verbose = TRUE, include_headers = FALSE) {
|
|
| 6 | 2x |
if (key == "") stop("specify your key, or set it to the RECEPTIVITI_KEY environment variable", call. = FALSE)
|
| 7 | 2x |
if (secret == "") stop("specify your secret, or set it to the RECEPTIVITI_SECRET environment variable", call. = FALSE)
|
| 8 | 39x |
handler <- new_handle(httpauth = 1, userpwd = paste0(key, ":", secret)) |
| 9 | 39x |
url <- paste0(sub("(?:/v\\d+)?/+$", "", url), "/v1/ping")
|
| 10 | 39x |
ping <- curl_fetch_memory(url, handler) |
| 11 | 39x |
ping$content <- list(message = rawToChar(ping$content)) |
| 12 | 38x |
if (substr(ping$content, 1, 1) == "{") ping$content <- fromJSON(ping$content$message)
|
| 13 | 39x |
ok <- ping$status_code == 200 && !length(ping$content$code) |
| 14 | 39x |
ping$status_message <- if (ok) {
|
| 15 | 36x |
ping$content$pong |
| 16 |
} else {
|
|
| 17 | 3x |
paste0( |
| 18 | 3x |
if (length(ping$content$code)) paste0(ping$status_code, " (", ping$content$code, "): "),
|
| 19 | 3x |
if (nchar(ping$content$message) > 500 || grepl("<", ping$content$message, fixed = TRUE)) {
|
| 20 | 1x |
ping$status_code |
| 21 |
} else {
|
|
| 22 | 2x |
ping$content$message |
| 23 |
} |
|
| 24 |
) |
|
| 25 |
} |
|
| 26 | 39x |
if (verbose) {
|
| 27 | 3x |
message("Status: ", if (ok) "OK" else "ERROR", "\nMessage: ", ping$status_message)
|
| 28 | 3x |
if (include_headers) {
|
| 29 | 1x |
ping$headers <- strsplit(rawToChar(ping$headers), "[\r\n]+", perl = TRUE)[[1]] |
| 30 | 1x |
json <- regexec("\\{.+\\}", ping$headers)
|
| 31 | 1x |
for (i in seq_along(json)) {
|
| 32 | 10x |
if (json[[i]] != -1) {
|
| 33 | 2x |
regmatches(ping$headers[[i]], json[[i]]) <- paste(" ", strsplit(toJSON(
|
| 34 | 2x |
fromJSON(regmatches(ping$headers[[i]], json[[i]])), |
| 35 | 2x |
auto_unbox = TRUE, pretty = TRUE |
| 36 | 2x |
), "\n")[[1]], collapse = "\n") |
| 37 |
} |
|
| 38 |
} |
|
| 39 | 1x |
message(paste0("\n", paste(" ", ping$headers, collapse = "\n")))
|
| 40 |
} |
|
| 41 |
} |
|
| 42 | 39x |
invisible(ping) |
| 43 |
} |