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 (!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 | 6x |
if (!is.null(id_column)) { |
232 | 2x |
if (id_column %in% colnames(text)) { |
233 | 1x |
id <- text[, id_column, drop = TRUE] |
234 |
} else { |
|
235 | 1x |
stop("id_column not found in text", call. = FALSE) |
236 |
} |
|
237 |
} |
|
238 | 5x |
if (!is.null(text_column)) { |
239 | 3x |
if (text_column %in% colnames(text)) { |
240 | 2x |
text <- text[, text_column, drop = TRUE] |
241 |
} else { |
|
242 | 1x |
if (!text_as_paths) stop("text_column not found in text", call. = FALSE) |
243 |
} |
|
244 |
} |
|
245 | 4x |
if (!is.null(dim(text))) { |
246 | 2x |
if (ncol(text) == 1) { |
247 | 1x |
text <- text[, 1, drop = TRUE] |
248 |
} else { |
|
249 | 1x |
stop("text has dimensions, but no text_column column", call. = FALSE) |
250 |
} |
|
251 |
} |
|
252 |
} |
|
253 | 2x |
if (!is.character(text)) text <- as.character(text) |
254 | 4x |
if (length(id) && !is.character(id)) id <- as.character(id) |
255 | 42x |
provided_id <- FALSE |
256 | 42x |
if (length(id)) { |
257 | 1x |
if (length(id) != length(text)) stop("id is not the same length as text", call. = FALSE) |
258 | 1x |
if (anyDuplicated(id)) stop("id contains duplicate values", call. = FALSE) |
259 | 6x |
provided_id <- TRUE |
260 |
} else { |
|
261 | 34x |
id <- paste0("t", seq_along(text)) |
262 |
} |
|
263 | 1x |
if (!is.numeric(retry_limit)) retry_limit <- 0 |
264 | 40x |
url <- paste0(sub("(?:/v\\d+)?/+$", "", url), "/v1/") |
265 | ||
266 |
# ping API |
|
267 | 40x |
if (make_request) { |
268 | 2x |
if (verbose) message("pinging API (", round(proc.time()[[3]] - st, 4), ")") |
269 | 38x |
ping <- receptiviti_status(url, key, secret, verbose = FALSE) |
270 | 1x |
if (ping$status_code != 200) stop(ping$status_message, call. = FALSE) |
271 |
} |
|
272 | ||
273 |
# prepare text |
|
274 | 2x |
if (verbose) message("preparing text (", round(proc.time()[[3]] - st, 4), ")") |
275 | 37x |
data <- data.frame(text = text, id = id, stringsAsFactors = FALSE) |
276 | 37x |
text <- data[!is.na(data$text) & data$text != "" & !duplicated(data$text), ] |
277 | 1x |
if (!nrow(text)) stop("no valid texts to process", call. = FALSE) |
278 | 1x |
if (!is.numeric(bundle_size)) bundle_size <- 1000 |
279 | 36x |
n <- ceiling(nrow(text) / min(1000, max(1, bundle_size))) |
280 | 36x |
bundles <- split(text, sort(rep_len(seq_len(n), nrow(text)))) |
281 | 36x |
size_fun <- if (text_as_paths) function(b) sum(file.size(b$text)) else object.size |
282 | 36x |
for (i in seq_along(bundles)) { |
283 | 146x |
size <- size_fun(bundles[[i]]) |
284 | 146x |
if (size > 1e7) { |
285 | 2x |
sizes <- vapply(seq_len(nrow(bundles[[i]])), function(r) as.numeric(size_fun(bundles[[i]][r, ])), 0) |
286 | 1x |
if (any(sizes > 1e7)) stop("one of your texts is over the individual size limit (10 MB)", call. = FALSE) |
287 | 1x |
bins <- rep(1, length(sizes)) |
288 | 1x |
bin_size <- 0 |
289 | 1x |
bi <- 1 |
290 | 1x |
for (ti in seq_along(bins)) { |
291 | 51x |
bin_size <- bin_size + sizes[ti] |
292 | 51x |
if (bin_size > 1e7) { |
293 | 1x |
bin_size <- sizes[ti] |
294 | 1x |
bi <- bi + 1 |
295 |
} |
|
296 | 51x |
bins[ti] <- bi |
297 |
} |
|
298 | 1x |
bundles <- c(bundles[-i], unname(split(bundles[[i]], paste0(i, ".", bins)))) |
299 |
} |
|
300 |
} |
|
301 | 35x |
n <- length(bundles) |
302 | 35x |
bundle_ref <- if (n == 1) "bundle" else "bundles" |
303 | 2x |
if (verbose) message("prepared text in ", n, " ", bundle_ref, " (", round(proc.time()[[3]] - st, 4), ")") |
304 | ||
305 |
# prepare cache |
|
306 | 35x |
if (is.character(cache)) { |
307 | 27x |
temp <- paste0(normalizePath(cache, "/", FALSE), "/") |
308 | 27x |
cache <- TRUE |
309 | 2x |
if (clear_cache) unlink(temp, recursive = TRUE) |
310 | 27x |
dir.create(temp, FALSE) |
311 |
} else { |
|
312 | 8x |
temp <- NULL |
313 | 8x |
cache <- FALSE |
314 |
} |
|
315 | ||
316 | 35x |
check_cache <- cache && !cache_overwrite |
317 | 35x |
endpoint <- paste0(url, "framework/bulk") |
318 | 35x |
auth <- paste0(key, ":", secret) |
319 | ! |
if (missing(in_memory) && (use_future || cores > 1) && n > cores) in_memory <- FALSE |
320 | 35x |
request_scratch <- NULL |
321 | 35x |
if (!in_memory) { |
322 | ! |
if (verbose) message("writing ", bundle_ref, " to disc (", round(proc.time()[[3]] - st, 4), ")") |
323 | 2x |
request_scratch <- paste0(tempdir(), "/receptiviti_request_scratch/") |
324 | 2x |
dir.create(request_scratch, FALSE) |
325 | 2x |
if (clear_scratch_cache) on.exit(unlink(request_scratch, recursive = TRUE)) |
326 | 2x |
bundles <- vapply(bundles, function(b) { |
327 | 6x |
scratch_bundle <- paste0(request_scratch, digest(b), ".rds") |
328 | 6x |
if (!file.exists(scratch_bundle)) saveRDS(b, scratch_bundle, compress = FALSE) |
329 | 6x |
scratch_bundle |
330 | 2x |
}, "", USE.NAMES = FALSE) |
331 |
} |
|
332 | ||
333 | 35x |
doprocess <- function(bundles, cores, future) { |
334 | 5x |
env <- parent.frame() |
335 | 5x |
if (future) { |
336 | 1x |
eval(expression(future.apply::future_lapply(bundles, process)), envir = env) |
337 |
} else { |
|
338 | 4x |
cl <- parallel::makeCluster(cores) |
339 | 4x |
parallel::clusterExport(cl, ls(envir = env), env) |
340 | 4x |
on.exit(parallel::stopCluster(cl)) |
341 | 4x |
(if (length(bundles) > cores * 2) parallel::parLapplyLB else parallel::parLapply)(cl, bundles, process) |
342 |
} |
|
343 |
} |
|
344 | ||
345 | 35x |
request <- function(body, bin, ids, attempt = retry_limit) { |
346 | 127x |
unpack <- function(d) { |
347 | 16119x |
if (is.list(d)) as.data.frame(lapply(d, unpack), optional = TRUE) else d |
348 |
} |
|
349 | 127x |
json <- jsonlite::toJSON(body, auto_unbox = TRUE) |
350 | 127x |
temp_file <- paste0(tempdir(), "/", digest::digest(json, serialize = FALSE), ".json") |
351 | 118x |
if (!request_cache) unlink(temp_file) |
352 | 127x |
res <- NULL |
353 | 127x |
if (!file.exists(temp_file)) { |
354 | 123x |
if (make_request) { |
355 | 122x |
handler <- curl::new_handle( |
356 | 122x |
httpauth = 1, userpwd = auth, |
357 | 122x |
copypostfields = jsonlite::toJSON(unname(body), auto_unbox = TRUE) |
358 |
) |
|
359 | 122x |
res <- curl::curl_fetch_disk(endpoint, temp_file, handler) |
360 |
} else { |
|
361 | 1x |
stop("make_request is FALSE, but there are texts with no cached results", call. = FALSE) |
362 |
} |
|
363 |
} |
|
364 | 126x |
result <- if (file.exists(temp_file)) { |
365 | 126x |
jsonlite::read_json(temp_file, simplifyVector = TRUE) |
366 |
} else { |
|
367 | ! |
list(message = rawToChar(res$content)) |
368 |
} |
|
369 | 126x |
if (!is.null(result$results)) { |
370 | 81x |
result <- result$results |
371 | 81x |
if ("error" %in% names(result)) { |
372 | ! |
su <- !is.na(result$error$code) |
373 | ! |
errors <- result[su & !duplicated(result$error$code), "error"] |
374 | ! |
warning( |
375 | ! |
if (sum(su) > 1) "some texts were invalid: " else "a text was invalid: ", |
376 | ! |
paste( |
377 | ! |
do.call(paste0, data.frame("(", errors$code, ") ", errors$message, stringsAsFactors = FALSE)), |
378 | ! |
collapse = "; " |
379 |
), |
|
380 | ! |
call. = FALSE |
381 |
) |
|
382 |
} |
|
383 | 81x |
result <- unpack(result[!names(result) %in% c("response_id", "language", "version", "error")]) |
384 | 81x |
if (!is.null(result) && nrow(result)) { |
385 | 81x |
colnames(result)[1] <- "text_hash" |
386 | 81x |
cbind(id = ids, bin = bin, result) |
387 |
} |
|
388 |
} else { |
|
389 | ! |
if (substr(result$message, 1, 1) == "{") result <- jsonlite::fromJSON(result$message) |
390 | 45x |
if (!is.null(result$code) && result$code == 1420 && attempt > 0) { |
391 | 44x |
unlink(temp_file) |
392 | 44x |
wait_time <- as.numeric(regmatches(result$message, regexec("[0-9]+(?:\\.[0-9]+)?", result$message))) |
393 | 44x |
Sys.sleep(if (is.na(wait_time)) 1 else wait_time / 1e3) |
394 | 44x |
request(body, bin, ids, attempt - 1) |
395 |
} else { |
|
396 | 1x |
stop(paste0(if (length(result$code)) { |
397 | 1x |
paste0( |
398 | 1x |
if (is.null(res$status_code)) 200 else res$status_code, " (", result$code, "): " |
399 |
) |
|
400 | 1x |
}, result$message), call. = FALSE) |
401 |
} |
|
402 |
} |
|
403 |
} |
|
404 | ||
405 | 35x |
process <- function(bundle) { |
406 | 103x |
opts <- getOption("stringsAsFactors") |
407 | 103x |
options("stringsAsFactors" = FALSE) |
408 | 103x |
on.exit(options("stringsAsFactors" = opts)) |
409 | 1x |
if (is.character(bundle)) bundle <- readRDS(bundle) |
410 | 103x |
text <- bundle$text |
411 | 103x |
bin <- NULL |
412 | 103x |
if (text_as_paths) { |
413 | 2x |
if (all(grepl("\\.csv", text))) { |
414 | 1x |
if (is.null(text_column)) stop("files appear to be csv, but no text_column was specified", call. = FALSE) |
415 | 1x |
text <- vapply(text, function(f) paste(arrow::read_csv_arrow(f)[, text_column], collapse = " "), "") |
416 |
} else { |
|
417 | ! |
text <- vapply(text, function(f) paste(readLines(f, warn = FALSE, skipNul = TRUE), collapse = " "), "") |
418 |
} |
|
419 |
} |
|
420 | 102x |
bundle$hashes <- vapply(text, digest::digest, "", serialize = FALSE) |
421 | 102x |
initial <- paste0("h", substr(bundle$hashes, 1, 1)) |
422 | 102x |
set <- !is.na(text) & text != "" & text != "logical(0)" & !duplicated(bundle$hashes) |
423 | 102x |
res_cached <- res_fresh <- NULL |
424 | 102x |
if (check_cache && dir.exists(paste0(temp, "bin=h"))) { |
425 | 23x |
db <- arrow::open_dataset(temp, partitioning = arrow::schema(bin = arrow::string()), format = cache_format) |
426 | 23x |
cached <- if (!is.null(db$schema$GetFieldByName("text_hash"))) { |
427 | 23x |
tryCatch( |
428 | 23x |
dplyr::compute(dplyr::filter(db, bin %in% unique(initial), text_hash %in% bundle$hashes)), |
429 | 23x |
error = function(e) matrix(integer(), 0) |
430 |
) |
|
431 |
} else { |
|
432 | ! |
matrix(integer(), 0) |
433 |
} |
|
434 | 23x |
if (nrow(cached)) { |
435 | 21x |
cached <- as.data.frame(cached$to_data_frame()) |
436 | ! |
if (anyDuplicated(cached$text_hash)) cached <- cached[!duplicated(cached$text_hash), ] |
437 | 21x |
rownames(cached) <- cached$text_hash |
438 | 21x |
cached_set <- bundle$hashes %in% cached$text_hash |
439 | 21x |
set[cached_set] <- FALSE |
440 | 21x |
res_cached <- cbind(id = bundle[cached_set, "id"], cached[bundle[cached_set, "hashes"], ]) |
441 |
} |
|
442 |
} |
|
443 | 102x |
if (any(set)) { |
444 | 83x |
set <- which(set) |
445 | 83x |
res_fresh <- request(lapply( |
446 | 83x |
set, function(i) list(content = text[[i]], request_id = bundle[i, "hashes"]) |
447 | 83x |
), initial[set], bundle[set, "id"]) |
448 | 81x |
if (check_cache && !is.null(res_cached) && !all(colnames(res_cached) %in% colnames(res_fresh))) { |
449 | ! |
res_cached <- NULL |
450 | ! |
res_fresh <- rbind( |
451 | ! |
res_fresh, |
452 | ! |
request(lapply( |
453 | ! |
cached_set, function(i) list(content = text[[i]], request_id = bundle[i, "hashes"]) |
454 | ! |
), initial[cached_set], bundle[cached_set, "ids"]) |
455 |
) |
|
456 |
} |
|
457 |
} |
|
458 | 100x |
res <- rbind(res_cached, res_fresh) |
459 | 100x |
missing_ids <- !bundle$id %in% res$id |
460 | 100x |
if (any(missing_ids)) { |
461 | 1x |
varnames <- colnames(res)[colnames(res) != "id"] |
462 | 1x |
res <- rbind(res, cbind( |
463 | 1x |
id = bundle[missing_ids, "id"], |
464 | 1x |
as.data.frame(matrix(NA, sum(missing_ids), length(varnames), dimnames = list(NULL, varnames))) |
465 |
)) |
|
466 |
} |
|
467 | 100x |
prog() |
468 | 100x |
res |
469 |
} |
|
470 | ||
471 |
# make request(s) |
|
472 | 35x |
cores <- if (is.numeric(cores)) max(1, min(length(bundles), cores)) else 1 |
473 | 35x |
call_env <- new.env(parent = globalenv()) |
474 | 35x |
prog <- progressor(along = bundles) |
475 | 35x |
environment(doprocess) <- call_env |
476 | 35x |
environment(request) <- call_env |
477 | 35x |
environment(process) <- call_env |
478 | 35x |
for (name in c( |
479 | 35x |
"doprocess", "request", "process", "text_column", "prog", "make_request", "check_cache", "endpoint", |
480 | 35x |
"temp", "use_future", "cores", "bundles", "cache_format", "request_cache", "auth", |
481 | 35x |
"text_as_paths", "retry_limit" |
482 |
)) { |
|
483 | 595x |
call_env[[name]] <- get(name) |
484 |
} |
|
485 | 35x |
results <- if (use_future || cores > 1) { |
486 | 5x |
if (verbose) { |
487 | ! |
message( |
488 | ! |
"processing ", bundle_ref, " using ", if (use_future) "future backend" else paste(cores, "cores"), |
489 | ! |
" (", round(proc.time()[[3]] - st, 4), ")" |
490 |
) |
|
491 |
} |
|
492 | 5x |
eval(expression(doprocess(bundles, cores, use_future)), envir = call_env) |
493 |
} else { |
|
494 | 2x |
if (verbose) message("processing ", bundle_ref, " sequentially (", round(proc.time()[[3]] - st, 4), ")") |
495 | 30x |
lapply(bundles, process) |
496 |
} |
|
497 | 2x |
if (verbose) message("done retrieving; preparing final results (", round(proc.time()[[3]] - st, 4), ")") |
498 | 32x |
final_res <- do.call(rbind, results) |
499 | ||
500 |
# update cache |
|
501 | 32x |
if (!is.null(temp)) { |
502 | 2x |
if (verbose) message("checking cache (", round(proc.time()[[3]] - st, 4), ")") |
503 | 26x |
initialized <- dir.exists(paste0(temp, "bin=h")) |
504 | 26x |
if (initialized) { |
505 | 24x |
db <- arrow::open_dataset(temp, partitioning = arrow::schema(bin = arrow::string()), format = cache_format) |
506 | 24x |
if (db$num_cols != (ncol(final_res) - 1)) { |
507 | ! |
if (verbose) message("clearing existing cache since columns did not align (", round(proc.time()[[3]] - st, 4), ")") |
508 | ! |
if (clear_cache) unlink(temp, recursive = TRUE) |
509 | ! |
dir.create(temp, FALSE) |
510 | ! |
initialized <- FALSE |
511 |
} |
|
512 |
} |
|
513 | 26x |
if (!initialized) { |
514 | 2x |
initial <- final_res[1, -1] |
515 | 2x |
initial$text_hash <- "" |
516 | 2x |
initial$bin <- "h" |
517 | 2x |
initial[, !colnames(initial) %in% c( |
518 | 2x |
"bin", "text_hash", "summary.word_count", "summary.sentence_count" |
519 | 2x |
)] <- .1 |
520 | 2x |
initial <- rbind(initial, final_res[, -1]) |
521 | 2x |
if (verbose) { |
522 | 1x |
message( |
523 | 1x |
"initializing cache with ", nrow(final_res), " result", |
524 | 1x |
if (nrow(final_res) > 1) "s", " (", round(proc.time()[[3]] - st, 4), ")" |
525 |
) |
|
526 |
} |
|
527 | 2x |
arrow::write_dataset(initial, temp, partitioning = "bin", format = cache_format) |
528 |
} else { |
|
529 | 24x |
fresh <- final_res[!duplicated(final_res$text_hash), -1] |
530 | 24x |
cached <- dplyr::filter(db, bin %in% unique(fresh$bin), text_hash %in% fresh$text_hash) |
531 | 24x |
if (!nrow(cached) || nrow(cached) != nrow(fresh)) { |
532 | 5x |
uncached_hashes <- if (nrow(cached)) { |
533 | 3x |
!fresh$text_hash %in% dplyr::collect(dplyr::select(cached, text_hash))[, 1] |
534 |
} else { |
|
535 | 2x |
rep(TRUE, nrow(fresh)) |
536 |
} |
|
537 | 5x |
if (any(uncached_hashes)) { |
538 | 5x |
if (verbose) { |
539 | 1x |
message( |
540 | 1x |
"updating cache with ", sum(uncached_hashes), " result", |
541 | 1x |
if (sum(uncached_hashes) > 1) "s", " (", round(proc.time()[[3]] - st, 4), ")" |
542 |
) |
|
543 |
} |
|
544 | 5x |
arrow::write_dataset(fresh[uncached_hashes, ], temp, partitioning = "bin", format = cache_format) |
545 |
} |
|
546 |
} |
|
547 |
} |
|
548 |
} |
|
549 | ||
550 |
# prepare final results |
|
551 | 2x |
if (verbose) message("preparing output (", round(proc.time()[[3]] - st, 4), ")") |
552 | 32x |
rownames(final_res) <- final_res$id |
553 | 32x |
rownames(data) <- data$id |
554 | 32x |
data$text_hash <- structure(final_res$text_hash, names = data[final_res$id, "text"])[data$text] |
555 | 32x |
final_res <- cbind( |
556 | 32x |
data[, c(if (return_text) "text", if (provided_id) "id", "text_hash"), drop = FALSE], |
557 | 32x |
final_res[ |
558 | 32x |
structure(final_res$id, names = final_res$text_hash)[data$text_hash], |
559 | 32x |
!colnames(final_res) %in% c("id", "bin", "text_hash", "custom") |
560 |
] |
|
561 |
) |
|
562 | 32x |
row.names(final_res) <- NULL |
563 | 32x |
if (!is.null(output)) { |
564 | ! |
if (!grepl(".csv", output, fixed = TRUE)) output <- paste0(output, ".csv") |
565 | 1x |
if (compress && !grepl(".xz", output, fixed = TRUE)) output <- paste0(output, ".xz") |
566 | 1x |
if (grepl(".xz", output, fixed = TRUE)) compress <- TRUE |
567 | 1x |
if (verbose) message("writing results to file: ", output, " (", round(proc.time()[[3]] - st, 4), ")") |
568 | 3x |
dir.create(dirname(output), FALSE, TRUE) |
569 | 2x |
if (overwrite) unlink(output) |
570 | 1x |
if (compress) output <- xzfile(output) |
571 | 3x |
write_csv_arrow(final_res, file = output) |
572 |
} |
|
573 |
} |
|
574 | 32x |
if (is.character(frameworks) && frameworks[1] != "all") { |
575 | ! |
if (verbose) message("selecting frameworks (", round(proc.time()[[3]] - st, 4), ")") |
576 | 4x |
vars <- colnames(final_res) |
577 | 4x |
sel <- grepl(paste0("^(?:", paste(tolower(frameworks), collapse = "|"), ")"), vars) |
578 | 4x |
if (any(sel)) { |
579 | 1x |
if (missing(framework_prefix) && (length(frameworks) == 1 && frameworks != "all")) framework_prefix <- FALSE |
580 | 3x |
sel <- unique(c("text", "id", "text_hash", vars[sel])) |
581 | 3x |
sel <- sel[sel %in% vars] |
582 | 3x |
final_res <- final_res[, sel] |
583 |
} else { |
|
584 | 1x |
warning("frameworks did not match any columns -- returning all", call. = FALSE) |
585 |
} |
|
586 |
} |
|
587 | 32x |
if (as_list) { |
588 | 1x |
if (missing(framework_prefix)) framework_prefix <- FALSE |
589 | 1x |
inall <- c("text", "id", "text_hash") |
590 | 1x |
cols <- colnames(final_res) |
591 | 1x |
inall <- inall[inall %in% cols] |
592 | 1x |
pre <- sub("\\..*$", "", cols) |
593 | 1x |
pre <- unique(pre[!pre %in% inall]) |
594 | 1x |
final_res <- lapply(structure(pre, names = pre), function(f) { |
595 | 9x |
res <- final_res[, c(inall, grep(paste0("^", f), cols, value = TRUE))] |
596 | 9x |
if (!framework_prefix) colnames(res) <- sub("^.+\\.", "", colnames(res)) |
597 | 9x |
res |
598 |
}) |
|
599 | 2x |
} else if (!framework_prefix) colnames(final_res) <- sub("^.+\\.", "", colnames(final_res)) |
600 | 2x |
if (verbose) message("done (", round(proc.time()[[3]] - st, 4), ")") |
601 | 32x |
invisible(final_res) |
602 |
} |
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 |
ping$status_message <- if (ping$status_code == 200) { |
14 | 36x |
ping$content$pong |
15 |
} else { |
|
16 | 3x |
paste0( |
17 | 3x |
if (length(ping$content$code)) paste0(ping$status_code, " (", ping$content$code, "): "), |
18 | 3x |
if (nchar(ping$content$message) > 500 || grepl("<", ping$content$message, fixed = TRUE)) { |
19 | 1x |
ping$status_code |
20 |
} else { |
|
21 | 2x |
ping$content$message |
22 |
} |
|
23 |
) |
|
24 |
} |
|
25 | 39x |
if (verbose) { |
26 | 3x |
message("Status: ", if (ping$status_code == 200) "OK" else "ERROR", "\nMessage: ", ping$status_message) |
27 | 3x |
if (include_headers) { |
28 | 1x |
ping$headers <- strsplit(rawToChar(ping$headers), "[\r\n]+", perl = TRUE)[[1]] |
29 | 1x |
json <- regexec("\\{.+\\}", ping$headers) |
30 | 1x |
for (i in seq_along(json)) { |
31 | 10x |
if (json[[i]] != -1) { |
32 | 2x |
regmatches(ping$headers[[i]], json[[i]]) <- paste(" ", strsplit(toJSON( |
33 | 2x |
fromJSON(regmatches(ping$headers[[i]], json[[i]])), |
34 | 2x |
auto_unbox = TRUE, pretty = TRUE |
35 | 2x |
), "\n")[[1]], collapse = "\n") |
36 |
} |
|
37 |
} |
|
38 | 1x |
message(paste0("\n", paste(" ", ping$headers, collapse = "\n"))) |
39 |
} |
|
40 |
} |
|
41 | 39x |
invisible(ping) |
42 |
} |