Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1 | #' Class KorAPQuery |
| 2 | #' |
Marc Kupietz | a6e4ee6 | 2021-03-05 09:00:15 +0100 | [diff] [blame] | 3 | #' This class provides methods to perform different kinds of queries on the KorAP API server. |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 4 | #' `KorAPQuery` objects, which are typically created by the [corpusQuery()] method, |
Marc Kupietz | a6e4ee6 | 2021-03-05 09:00:15 +0100 | [diff] [blame] | 5 | #' represent the current state of a query to a KorAP server. |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 6 | #' |
| 7 | #' @include KorAPConnection.R |
Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 8 | #' @import httr2 |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 9 | #' |
Marc Kupietz | a6e4ee6 | 2021-03-05 09:00:15 +0100 | [diff] [blame] | 10 | #' @include RKorAPClient-package.R |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 11 | |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 12 | #' @export |
| 13 | KorAPQuery <- setClass("KorAPQuery", slots = c( |
Marc Kupietz | b897218 | 2019-09-20 21:33:46 +0200 | [diff] [blame] | 14 | "korapConnection", |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 15 | "request", |
| 16 | "vc", |
| 17 | "totalResults", |
| 18 | "nextStartIndex", |
| 19 | "fields", |
| 20 | "requestUrl", |
| 21 | "webUIRequestUrl", |
| 22 | "apiResponse", |
| 23 | "collectedMatches", |
| 24 | "hasMoreMatches" |
| 25 | )) |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 26 | |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 27 | #' Method initialize |
| 28 | #' |
| 29 | #' @rdname KorAPQuery-class |
| 30 | #' @param .Object … |
Marc Kupietz | b897218 | 2019-09-20 21:33:46 +0200 | [diff] [blame] | 31 | #' @param korapConnection KorAPConnection object |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 32 | #' @param request query part of the request URL |
| 33 | #' @param vc definition of a virtual corpus |
| 34 | #' @param totalResults number of hits the query has yielded |
| 35 | #' @param nextStartIndex at what index to start the next fetch of query results |
| 36 | #' @param fields what data / metadata fields should be collected |
| 37 | #' @param requestUrl complete URL of the API request |
| 38 | #' @param webUIRequestUrl URL of a web frontend request corresponding to the API request |
| 39 | #' @param apiResponse data-frame representation of the JSON response of the API request |
Marc Kupietz | 7776dec | 2019-09-27 16:59:02 +0200 | [diff] [blame] | 40 | #' @param hasMoreMatches logical that signals if more query results can be fetched |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 41 | #' @param collectedMatches matches already fetched from the KorAP-API-server |
Marc Kupietz | 97a1bca | 2019-10-04 22:52:09 +0200 | [diff] [blame] | 42 | #' |
| 43 | #' @importFrom tibble tibble |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 44 | #' @export |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 45 | setMethod( |
| 46 | "initialize", "KorAPQuery", |
| 47 | function(.Object, korapConnection = NULL, request = NULL, vc = "", totalResults = 0, nextStartIndex = 0, fields = c( |
| 48 | "corpusSigle", "textSigle", "pubDate", "pubPlace", |
| 49 | "availability", "textClass", "snippet", "tokens" |
| 50 | ), |
| 51 | requestUrl = "", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches = FALSE, collectedMatches = NULL) { |
| 52 | .Object <- callNextMethod() |
| 53 | .Object@korapConnection <- korapConnection |
| 54 | .Object@request <- request |
| 55 | .Object@vc <- vc |
| 56 | .Object@totalResults <- totalResults |
| 57 | .Object@nextStartIndex <- nextStartIndex |
| 58 | .Object@fields <- fields |
| 59 | .Object@requestUrl <- requestUrl |
| 60 | .Object@webUIRequestUrl <- webUIRequestUrl |
| 61 | .Object@apiResponse <- apiResponse |
| 62 | .Object@hasMoreMatches <- hasMoreMatches |
| 63 | .Object@collectedMatches <- collectedMatches |
| 64 | .Object |
| 65 | } |
| 66 | ) |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 67 | |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 68 | setGeneric("corpusQuery", function(kco, ...) standardGeneric("corpusQuery")) |
| 69 | setGeneric("fetchAll", function(kqo, ...) standardGeneric("fetchAll")) |
| 70 | setGeneric("fetchNext", function(kqo, ...) standardGeneric("fetchNext")) |
| 71 | setGeneric("fetchRest", function(kqo, ...) standardGeneric("fetchRest")) |
| 72 | setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery")) |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 73 | |
| 74 | maxResultsPerPage <- 50 |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 75 | |
Marc Kupietz | 4de53ec | 2019-10-04 09:12:00 +0200 | [diff] [blame] | 76 | ## quiets concerns of R CMD check re: the .'s that appear in pipelines |
Marc Kupietz | ef1ef4a | 2025-02-19 12:12:40 +0100 | [diff] [blame] | 77 | utils::globalVariables(c(".")) |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 78 | |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 79 | #' Corpus query |
| 80 | #' |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 81 | #' **`corpusQuery`** performs a corpus query via a connection to a KorAP-API-server |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 82 | #' |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 83 | #' @rdname KorAPQuery-class |
| 84 | #' @aliases corpusQuery |
| 85 | #' |
| 86 | #' @importFrom urltools url_encode |
| 87 | #' @importFrom purrr pmap |
| 88 | #' @importFrom dplyr bind_rows |
| 89 | #' |
Marc Kupietz | 617266d | 2025-02-27 10:43:07 +0100 | [diff] [blame] | 90 | #' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()` |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 91 | #' @param query string that contains the corpus query. The query language depends on the `ql` parameter. Either `query` must be provided or `KorAPUrl`. |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 92 | #' @param vc string describing the virtual corpus in which the query should be performed. An empty string (default) means the whole corpus, as far as it is license-wise accessible. |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 93 | #' @param KorAPUrl instead of providing the query and vc string parameters, you can also simply copy a KorAP query URL from your browser and use it here (and in `KorAPConnection`) to provide all necessary information for the query. |
Marc Kupietz | 132f005 | 2023-04-16 14:23:05 +0200 | [diff] [blame] | 94 | #' @param metadataOnly logical that determines whether queries should return only metadata without any snippets. This can also be useful to prevent access rewrites. Note that the default value is TRUE. |
| 95 | #' If you want your corpus queries to return not only metadata, but also KWICS, you need to authorize |
| 96 | #' your RKorAPClient application as explained in the |
| 97 | #' [authorization section](https://github.com/KorAP/RKorAPClient#authorization) |
| 98 | #' of the RKorAPClient Readme on GitHub and set the `metadataOnly` parameter to |
| 99 | #' `FALSE`. |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 100 | #' @param ql string to choose the query language (see [section on Query Parameters](https://github.com/KorAP/Kustvakt/wiki/Service:-Search-GET#user-content-parameters) in the Kustvakt-Wiki for possible values. |
Akron | 5e13546 | 2019-09-27 16:31:38 +0200 | [diff] [blame] | 101 | #' @param fields (meta)data fields that will be fetched for every match. |
Marc Kupietz | 43a6ade | 2020-02-18 17:01:44 +0100 | [diff] [blame] | 102 | #' @param accessRewriteFatal abort if query or given vc had to be rewritten due to insufficient rights (not yet implemented). |
Marc Kupietz | 25aebc3 | 2019-09-16 18:40:50 +0200 | [diff] [blame] | 103 | #' @param verbose print some info |
Marc Kupietz | 4de53ec | 2019-10-04 09:12:00 +0200 | [diff] [blame] | 104 | #' @param as.df return result as data frame instead of as S4 object? |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 105 | #' @param expand logical that decides if `query` and `vc` parameters are expanded to all of their combinations. Defaults to `TRUE`, iff `query` and `vc` have different lengths |
Marc Kupietz | d9b2fd7 | 2023-04-17 19:08:50 +0200 | [diff] [blame] | 106 | #' @param context string that specifies the size of the left and the right context returned in `snippet` |
| 107 | #' (provided that `metadataOnly` is set to `false` and that the necessary access right are met). |
| 108 | #' The format of the context size specifcation (e.g. `3-token,3-token`) is described in the [Service: Search GET documentation of the Kustvakt Wiki](https://github.com/KorAP/Kustvakt/wiki/Service:-Search-GET). |
| 109 | #' If the parameter is not set, the default context size secification of the KorAP server instance will be used. |
| 110 | #' Note that you cannot overrule the maximum context size set in the KorAP server instance, |
| 111 | #' as this is typically legally motivated. |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 112 | #' @return Depending on the `as.df` parameter, a tibble or a [KorAPQuery()] object that, among other information, contains the total number of results in `@totalResults`. The resulting object can be used to fetch all query results (with [fetchAll()]) or the next page of results (with [fetchNext()]). |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 113 | #' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl` |
| 114 | #' Please make sure to check `$collection$rewrites` to see if any unforeseen access rewrites of the query's virtual corpus had to be performed. |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 115 | #' |
| 116 | #' @examples |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 117 | #' \dontrun{ |
| 118 | #' |
Marc Kupietz | 603491f | 2019-09-18 14:01:02 +0200 | [diff] [blame] | 119 | #' # Fetch metadata of every query hit for "Ameisenplage" and show a summary |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 120 | #' KorAPConnection() %>% |
| 121 | #' corpusQuery("Ameisenplage") %>% |
| 122 | #' fetchAll() |
Marc Kupietz | 657d8e7 | 2020-02-25 18:31:50 +0100 | [diff] [blame] | 123 | #' } |
Marc Kupietz | 3c531f6 | 2019-09-13 12:17:24 +0200 | [diff] [blame] | 124 | #' |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 125 | #' \dontrun{ |
| 126 | #' |
Marc Kupietz | 603491f | 2019-09-18 14:01:02 +0200 | [diff] [blame] | 127 | #' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus |
| 128 | #' # and show the number of query hits (but don't fetch them). |
Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 129 | #' |
Marc Kupietz | 617266d | 2025-02-27 10:43:07 +0100 | [diff] [blame] | 130 | #' KorAPConnection(verbose = TRUE) %>% |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 131 | #' corpusQuery( |
| 132 | #' KorAPUrl = |
| 133 | #' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp" |
| 134 | #' ) |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 135 | #' } |
| 136 | #' |
| 137 | #' \dontrun{ |
Marc Kupietz | 3c531f6 | 2019-09-13 12:17:24 +0200 | [diff] [blame] | 138 | #' |
Marc Kupietz | 603491f | 2019-09-18 14:01:02 +0200 | [diff] [blame] | 139 | #' # Plot the time/frequency curve of "Ameisenplage" |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 140 | #' KorAPConnection(verbose = TRUE) %>% |
| 141 | #' { |
| 142 | #' . ->> kco |
| 143 | #' } %>% |
Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 144 | #' corpusQuery("Ameisenplage") %>% |
| 145 | #' fetchAll() %>% |
| 146 | #' slot("collectedMatches") %>% |
| 147 | #' mutate(year = lubridate::year(pubDate)) %>% |
Marc Kupietz | 19e2ebd | 2019-10-07 11:45:30 +0200 | [diff] [blame] | 148 | #' dplyr::select(year) %>% |
Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 149 | #' group_by(year) %>% |
Marc Kupietz | cb3c59e | 2020-06-02 10:10:43 +0200 | [diff] [blame] | 150 | #' summarise(Count = dplyr::n()) %>% |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 151 | #' mutate(Freq = mapply(function(f, y) { |
| 152 | #' f / corpusStats(kco, paste("pubDate in", y))@tokens |
| 153 | #' }, Count, year)) %>% |
Marc Kupietz | 19e2ebd | 2019-10-07 11:45:30 +0200 | [diff] [blame] | 154 | #' dplyr::select(-Count) %>% |
Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 155 | #' complete(year = min(year):max(year), fill = list(Freq = 0)) %>% |
| 156 | #' plot(type = "l") |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 157 | #' } |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 158 | #' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()] |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 159 | #' |
| 160 | #' @references |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 161 | #' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026> |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 162 | #' |
| 163 | #' @export |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 164 | setMethod( |
| 165 | "corpusQuery", "KorAPConnection", |
| 166 | function(kco, |
| 167 | query = if (missing(KorAPUrl)) { |
| 168 | stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE) |
| 169 | } else { |
| 170 | httr2::url_parse(KorAPUrl)$query$q |
| 171 | }, |
| 172 | vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq, |
| 173 | KorAPUrl, |
| 174 | metadataOnly = TRUE, |
| 175 | ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql, |
| 176 | fields = c( |
| 177 | "corpusSigle", |
| 178 | "textSigle", |
| 179 | "pubDate", |
| 180 | "pubPlace", |
| 181 | "availability", |
| 182 | "textClass", |
| 183 | "snippet", |
| 184 | "tokens" |
| 185 | ), |
| 186 | accessRewriteFatal = TRUE, |
| 187 | verbose = kco@verbose, |
| 188 | expand = length(vc) != length(query), |
| 189 | as.df = FALSE, |
| 190 | context = NULL) { |
| 191 | if (length(query) > 1 || length(vc) > 1) { |
| 192 | grid <- if (expand) expand_grid(query = query, vc = vc) else tibble(query = query, vc = vc) |
| 193 | purrr::pmap(grid, function(query, vc, ...) { |
| 194 | corpusQuery(kco, query = query, vc = vc, ql = ql, verbose = verbose, as.df = TRUE) |
| 195 | }) %>% |
| 196 | bind_rows() |
| 197 | } else { |
Marc Kupietz | 2078bde | 2023-08-27 16:46:15 +0200 | [diff] [blame] | 198 | contentFields <- c("snippet", "tokens") |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 199 | if (metadataOnly) { |
| 200 | fields <- fields[!fields %in% contentFields] |
| 201 | } |
Marc Kupietz | 80dc643 | 2025-02-07 16:57:40 +0100 | [diff] [blame] | 202 | if (!"textSigle" %in% fields) { |
| 203 | fields <- c(fields, "textSigle") |
| 204 | } |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 205 | request <- |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 206 | paste0( |
| 207 | "?q=", |
| 208 | url_encode(enc2utf8(query)), |
| 209 | ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""), |
| 210 | ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""), |
| 211 | ifelse(!metadataOnly, "&show-tokens=true", ""), |
| 212 | "&ql=", ql |
| 213 | ) |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 214 | webUIRequestUrl <- paste0(kco@KorAPUrl, request) |
| 215 | requestUrl <- paste0( |
| 216 | kco@apiUrl, |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 217 | "search", |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 218 | request, |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 219 | "&fields=", |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 220 | paste(fields, collapse = ","), |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 221 | if (metadataOnly) "&access-rewrite-disabled=true" else "" |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 222 | ) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 223 | log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"", |
| 224 | sep = |
| 225 | "" |
| 226 | ) |
| 227 | res <- apiCall(kco, paste0(requestUrl, "&count=0")) |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 228 | if (is.null(res)) { |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 229 | message("API call failed.") |
| 230 | totalResults <- 0 |
| 231 | } else { |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 232 | totalResults <- as.integer(res$meta$totalResults) |
Marc Kupietz | a47d150 | 2023-04-18 15:26:47 +0200 | [diff] [blame] | 233 | log_info(verbose, ": ", totalResults, " hits") |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 234 | if (!is.null(res$meta$cached)) { |
Marc Kupietz | a47d150 | 2023-04-18 15:26:47 +0200 | [diff] [blame] | 235 | log_info(verbose, " [cached]\n") |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 236 | } else if (!is.null(res$meta$benchmark)) { |
| 237 | log_info(verbose, ", took ", res$meta$benchmark, "\n", sep = "") |
| 238 | } else { |
| 239 | log_info(verbose, "\n") |
| 240 | } |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 241 | } |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 242 | if (as.df) { |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 243 | data.frame( |
| 244 | query = query, |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 245 | totalResults = totalResults, |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 246 | vc = vc, |
| 247 | webUIRequestUrl = webUIRequestUrl, |
| 248 | stringsAsFactors = FALSE |
| 249 | ) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 250 | } else { |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 251 | KorAPQuery( |
| 252 | korapConnection = kco, |
| 253 | nextStartIndex = 0, |
| 254 | fields = fields, |
| 255 | requestUrl = requestUrl, |
| 256 | request = request, |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 257 | totalResults = totalResults, |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 258 | vc = vc, |
| 259 | apiResponse = res, |
| 260 | webUIRequestUrl = webUIRequestUrl, |
Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 261 | hasMoreMatches = (totalResults > 0), |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 262 | ) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 263 | } |
Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 264 | } |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 265 | } |
| 266 | ) |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 267 | |
Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 268 | #' @importFrom purrr map |
| 269 | repair_data_strcuture <- function(x) { |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 270 | if (is.list(x)) { |
| 271 | as.character(purrr::map(x, ~ if (length(.x) > 1) { |
Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 272 | paste(.x, collapse = " ") |
| 273 | } else { |
| 274 | .x |
| 275 | })) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 276 | } else { |
Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 277 | ifelse(is.na(x), "", x) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 278 | } |
Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 279 | } |
| 280 | |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 281 | #' Fetch the next bunch of results of a KorAP query. |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 282 | #' |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 283 | #' **`fetchNext`** fetches the next bunch of results of a KorAP query. |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 284 | #' |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 285 | #' @param kqo object obtained from [corpusQuery()] |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 286 | #' @param offset start offset for query results to fetch |
| 287 | #' @param maxFetch maximum number of query results to fetch |
Marc Kupietz | 25aebc3 | 2019-09-16 18:40:50 +0200 | [diff] [blame] | 288 | #' @param verbose print progress information if true |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 289 | #' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results. |
| 290 | #' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches` |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 291 | #' |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 292 | #' @examples |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 293 | #' \dontrun{ |
| 294 | #' |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 295 | #' q <- KorAPConnection() %>% |
| 296 | #' corpusQuery("Ameisenplage") %>% |
| 297 | #' fetchNext() |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 298 | #' q@collectedMatches |
Marc Kupietz | 657d8e7 | 2020-02-25 18:31:50 +0100 | [diff] [blame] | 299 | #' } |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 300 | #' |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 301 | #' @references |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 302 | #' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026> |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 303 | #' |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 304 | #' @aliases fetchNext |
| 305 | #' @rdname KorAPQuery-class |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 306 | #' @importFrom dplyr rowwise mutate bind_rows select summarise n select |
Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 307 | #' @importFrom tibble enframe add_column |
| 308 | #' @importFrom stringr word |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 309 | #' @importFrom tidyr unnest unchop pivot_wider |
| 310 | #' @importFrom purrr map |
Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 311 | #' @export |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 312 | setMethod("fetchNext", "KorAPQuery", function(kqo, |
| 313 | offset = kqo@nextStartIndex, |
| 314 | maxFetch = maxResultsPerPage, |
| 315 | verbose = kqo@korapConnection@verbose, |
| 316 | randomizePageOrder = FALSE) { |
Marc Kupietz | a7a8f1b | 2024-12-18 15:56:19 +0100 | [diff] [blame] | 317 | # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 318 | results <- key <- name <- tmp_positions <- 0 |
Marc Kupietz | a7a8f1b | 2024-12-18 15:56:19 +0100 | [diff] [blame] | 319 | |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 320 | if (kqo@totalResults == 0 || offset >= kqo@totalResults) { |
| 321 | return(kqo) |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 322 | } |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 323 | use_korap_api <- Sys.getenv("USE_KORAP_API", unset = NA) |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 324 | # Calculate the initial page number (not used directly - keeping for reference) |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 325 | collectedMatches <- kqo@collectedMatches |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 326 | |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 327 | # For randomized page order, generate a list of randomized page indices |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 328 | if (randomizePageOrder) { |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 329 | # Calculate how many pages we need to fetch based on maxFetch |
| 330 | total_pages_to_fetch <- if (!is.na(maxFetch)) { |
| 331 | # Either limited by maxFetch or total results, whichever is smaller |
| 332 | min(ceiling(maxFetch / maxResultsPerPage), ceiling(kqo@totalResults / maxResultsPerPage)) |
| 333 | } else { |
| 334 | # All pages |
| 335 | ceiling(kqo@totalResults / maxResultsPerPage) |
| 336 | } |
| 337 | |
| 338 | # Generate randomized page indices (0-based for API) |
| 339 | pages <- sample.int(ceiling(kqo@totalResults / maxResultsPerPage), total_pages_to_fetch) - 1 |
| 340 | page_index <- 1 # Index to track which page in the randomized list we're on |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 341 | } |
| 342 | |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 343 | if (is.null(collectedMatches)) { |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 344 | collectedMatches <- data.frame() |
| 345 | } |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 346 | |
| 347 | # Initialize the page counter properly based on nextStartIndex and any previously fetched results |
| 348 | # We add 1 to make it 1-based for display purposes since users expect page numbers to start from 1 |
| 349 | # For first call, this will be 1, for subsequent calls, it will reflect our actual position |
| 350 | current_page_number <- ceiling(offset / maxResultsPerPage) + 1 |
| 351 | |
| 352 | # For sequential fetches, keep track of which global page we're on |
| 353 | # This is important for correctly showing page numbers in subsequent fetchNext calls |
| 354 | page_count_start <- current_page_number |
| 355 | |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 356 | repeat { |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 357 | # Determine which page to fetch next |
| 358 | if (randomizePageOrder) { |
| 359 | # In randomized mode, get the page from our randomized list using the page_index |
| 360 | # Make sure we don't exceed the array bounds |
| 361 | if (page_index > length(pages)) { |
| 362 | break # No more pages to fetch in randomized mode |
| 363 | } |
| 364 | current_offset_page <- pages[page_index] |
| 365 | # For display purposes in randomized mode, show which page out of the total we're fetching |
| 366 | display_page_number <- page_index |
| 367 | } else { |
| 368 | # In sequential mode, use the current_page_number to calculate the offset |
| 369 | current_offset_page <- (current_page_number - 1) |
| 370 | display_page_number <- current_page_number |
| 371 | } |
| 372 | |
| 373 | # Calculate the actual offset in tokens |
| 374 | currentOffset <- current_offset_page * maxResultsPerPage |
| 375 | |
| 376 | # Build the query with the appropriate count and offset |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 377 | query <- paste0(kqo@requestUrl, "&count=", min(if (!is.na(maxFetch)) maxFetch - results else maxResultsPerPage, maxResultsPerPage), "&offset=", currentOffset, "&cutoff=true") |
Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 378 | res <- apiCall(kqo@korapConnection, query) |
| 379 | if (length(res$matches) == 0) { |
| 380 | break |
| 381 | } |
| 382 | |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 383 | if ("fields" %in% colnames(res$matches) && (is.na(use_korap_api) || as.numeric(use_korap_api) >= 1.0)) { |
Marc Kupietz | 16ccf11 | 2025-01-26 13:25:27 +0100 | [diff] [blame] | 384 | log_info(verbose, "Using fields API: ") |
Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 385 | currentMatches <- res$matches$fields %>% |
| 386 | purrr::map(~ mutate(.x, value = repair_data_strcuture(value))) %>% |
| 387 | tibble::enframe() %>% |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 388 | tidyr::unnest(cols = value) %>% |
| 389 | tidyr::pivot_wider(names_from = key, id_cols = name, names_repair = "unique") %>% |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 390 | dplyr::select(-name) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 391 | if ("snippet" %in% colnames(res$matches)) { |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 392 | currentMatches$snippet <- res$matches$snippet |
| 393 | } |
Marc Kupietz | 3cd2c6c | 2025-01-08 20:35:39 +0100 | [diff] [blame] | 394 | if ("tokens" %in% colnames(res$matches)) { |
| 395 | currentMatches$tokens <- res$matches$tokens |
| 396 | } |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 397 | } else { |
| 398 | currentMatches <- res$matches |
| 399 | } |
| 400 | |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 401 | for (field in kqo@fields) { |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 402 | if (!field %in% colnames(currentMatches)) { |
| 403 | currentMatches[, field] <- NA |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 404 | } |
| 405 | } |
Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 406 | currentMatches <- currentMatches %>% |
| 407 | select(kqo@fields) %>% |
| 408 | mutate( |
Marc Kupietz | 0447da0 | 2025-01-08 20:51:09 +0100 | [diff] [blame] | 409 | tmp_positions = gsub(".*-p(\\d+)-(\\d+).*", "\\1 \\2", res$matches$matchID), |
Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 410 | matchStart = as.integer(stringr::word(tmp_positions, 1)), |
| 411 | matchEnd = as.integer(stringr::word(tmp_positions, 2)) - 1 |
| 412 | ) %>% |
| 413 | select(-tmp_positions) |
| 414 | |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 415 | if (!is.list(collectedMatches)) { |
| 416 | collectedMatches <- currentMatches |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 417 | } else { |
Marc Kupietz | 2078bde | 2023-08-27 16:46:15 +0200 | [diff] [blame] | 418 | collectedMatches <- bind_rows(collectedMatches, currentMatches) |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 419 | } |
Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 420 | |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 421 | # Get the actual items per page from the API response |
| 422 | # We now consistently use maxResultsPerPage instead |
Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 423 | |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 424 | # Calculate total pages consistently using fixed maxResultsPerPage |
| 425 | # This ensures consistent page counting across the function |
| 426 | total_pages <- ceiling(kqo@totalResults / maxResultsPerPage) |
| 427 | |
| 428 | # Calculate the total pages based on what we've already fetched plus what we'll fetch |
| 429 | # This ensures the correct denominator is displayed for subsequent fetchNext calls |
| 430 | |
| 431 | # Calculate the total number of pages for the entire result set |
| 432 | # This calculation is kept for reference and for showing in parentheses |
Marc Kupietz | 669114b | 2025-05-02 22:02:20 +0200 | [diff] [blame] | 433 | |
Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 434 | # Estimate remaining time |
| 435 | time_per_page <- NA |
| 436 | eta_str <- "N/A" |
| 437 | completion_time_str <- "N/A" |
Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 438 | |
Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 439 | if (!is.null(res$meta$benchmark) && is.character(res$meta$benchmark)) { |
| 440 | # benchmark looks like "0.123s" |
| 441 | time_per_page <- suppressWarnings(as.numeric(sub("s", "", res$meta$benchmark))) |
| 442 | if (!is.na(time_per_page)) { |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 443 | # First determine our current global position for ETA calculation |
| 444 | current_global_position <- if (randomizePageOrder) { |
| 445 | # In randomized mode, this is how many pages we've processed so far in this batch |
| 446 | page_index - 1 # -1 because we're calculating remaining |
| 447 | } else { |
| 448 | page_count_start + (current_page_number - 1) - 1 # -1 because we're calculating remaining |
| 449 | } |
| 450 | |
| 451 | # Calculate remaining pages based on maxFetch if specified |
| 452 | if (!is.na(maxFetch) && maxFetch < kqo@totalResults) { |
| 453 | # We need to fetch up to maxFetch results |
| 454 | remaining_items_to_fetch <- maxFetch - nrow(collectedMatches) |
| 455 | remaining_pages <- ceiling(remaining_items_to_fetch / maxResultsPerPage) |
| 456 | } else { |
| 457 | # We need to fetch all results - account for our actual global position |
| 458 | # For randomized order, calculate remaining pages based on the randomized list or maxFetch |
| 459 | if (randomizePageOrder) { |
| 460 | if (exists("pages") && length(pages) > 0) { |
| 461 | remaining_pages <- length(pages) - page_index |
| 462 | } else if (!is.na(maxFetch)) { |
| 463 | # If pages is not available, use maxFetch to estimate remaining pages |
| 464 | remaining_pages <- ceiling(maxFetch / maxResultsPerPage) - page_index |
| 465 | } else { |
| 466 | # Fallback to a reasonable default |
| 467 | remaining_pages <- 1 |
| 468 | } |
| 469 | } else { |
| 470 | # For sequential order, use the current global position |
| 471 | remaining_pages <- total_pages - current_global_position |
| 472 | } |
| 473 | } |
Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 474 | |
| 475 | estimated_remaining_seconds <- remaining_pages * time_per_page |
| 476 | estimated_completion_time <- Sys.time() + estimated_remaining_seconds |
| 477 | |
| 478 | # Format time nicely |
| 479 | format_duration <- function(seconds) { |
| 480 | if (is.na(seconds) || seconds < 0) { |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 481 | # Instead of "N/A", return "00s" as a fallback |
| 482 | return("00s") |
Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 483 | } |
| 484 | days <- floor(seconds / (24 * 3600)) |
| 485 | seconds <- seconds %% (24 * 3600) |
| 486 | hours <- floor(seconds / 3600) |
| 487 | seconds <- seconds %% 3600 |
| 488 | minutes <- floor(seconds / 60) |
| 489 | seconds <- floor(seconds %% 60) |
| 490 | paste0( |
| 491 | if (days > 0) paste0(days, "d ") else "", |
| 492 | if (hours > 0 || days > 0) paste0(sprintf("%02d", hours), "h ") else "", |
| 493 | if (minutes > 0 || hours > 0 || days > 0) paste0(sprintf("%02d", minutes), "m ") else "", |
| 494 | paste0(sprintf("%02d", seconds), "s") |
| 495 | ) |
| 496 | } |
| 497 | |
| 498 | eta_str <- format_duration(estimated_remaining_seconds) |
| 499 | completion_time_str <- format(estimated_completion_time, "%Y-%m-%d %H:%M:%S") |
Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 500 | } |
Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 501 | } |
| 502 | |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 503 | # Create the page display string with proper formatting |
Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 504 | |
Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame^] | 505 | # For global page tracking, calculate the absolute page number |
| 506 | actual_display_number <- if (randomizePageOrder) { |
| 507 | current_offset_page + 1 # In randomized mode, this is the actual page (0-based + 1) |
| 508 | } else { |
| 509 | # In sequential mode, the absolute page number is the actual offset page + 1 (to make it 1-based) |
| 510 | current_offset_page + 1 |
| 511 | } |
| 512 | |
| 513 | # For subsequent calls to fetchNext, we need to calculate the correct page numbers |
| 514 | # based on the current batch being fetched |
| 515 | |
| 516 | # For each call to fetchNext, we want to show 1/2, 2/2 (not 3/4, 4/4) |
| 517 | # Simply count from 1 within the current batch |
| 518 | |
| 519 | # The relative page number is simply the current position in this batch |
| 520 | if (randomizePageOrder) { |
| 521 | relative_page_number <- page_index # In randomized mode, we start from 1 in each batch |
| 522 | } else { |
| 523 | relative_page_number <- display_page_number - (page_count_start - 1) |
| 524 | } |
| 525 | |
| 526 | # How many pages will we fetch in this batch? |
| 527 | # If maxFetch is specified, calculate based on it |
| 528 | pages_in_this_batch <- if (!is.na(maxFetch)) { |
| 529 | ceiling(maxFetch / maxResultsPerPage) |
| 530 | } else { |
| 531 | # Otherwise fetch all remaining pages |
| 532 | total_pages - page_count_start + 1 |
| 533 | } |
| 534 | |
| 535 | # The total pages to be shown in this batch |
| 536 | batch_total_pages <- pages_in_this_batch |
| 537 | |
| 538 | page_display <- paste0( |
| 539 | "Retrieved page ", |
| 540 | sprintf(paste0("%", nchar(batch_total_pages), "d"), relative_page_number), |
| 541 | "/", |
| 542 | sprintf("%d", batch_total_pages) |
| 543 | ) |
| 544 | |
| 545 | # If randomized, also show which actual page we fetched |
| 546 | if (randomizePageOrder) { |
| 547 | # Determine the maximum width needed for page numbers (based on total pages) |
| 548 | # This ensures consistent alignment |
| 549 | max_page_width <- nchar(as.character(total_pages)) |
| 550 | # Add the actual page number that was fetched (0-based + 1 for display) with proper padding |
| 551 | page_display <- paste0(page_display, |
| 552 | sprintf(" (actual page %*d)", max_page_width, current_offset_page + 1)) |
| 553 | } |
| 554 | # Always show the absolute page number and total pages (for clarity) |
| 555 | else { |
| 556 | # Show the absolute page number (out of total possible pages) |
| 557 | page_display <- paste0(page_display, sprintf( |
| 558 | " (page %d of %d total)", |
| 559 | actual_display_number, total_pages |
| 560 | )) |
| 561 | } |
| 562 | |
| 563 | # Add caching or timing information |
| 564 | if (!is.null(res$meta$cached)) { |
| 565 | page_display <- paste0(page_display, " [cached]") |
| 566 | } else { |
| 567 | page_display <- paste0( |
| 568 | page_display, |
| 569 | " in ", |
| 570 | if (!is.na(time_per_page)) sprintf("%4.1f", time_per_page) else "?", |
| 571 | "s. ETA: ", |
| 572 | # Display ETA for both randomized and sequential modes |
| 573 | eta_str, |
| 574 | # Show completion time for both modes |
| 575 | paste0(" (", completion_time_str, ")") |
| 576 | ) |
| 577 | } |
| 578 | |
| 579 | log_info(verbose, paste0(page_display, "\n")) |
| 580 | |
| 581 | # Increment the appropriate counter based on mode |
| 582 | if (randomizePageOrder) { |
| 583 | page_index <- page_index + 1 |
| 584 | } else { |
| 585 | current_page_number <- current_page_number + 1 |
| 586 | } |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 587 | results <- results + res$meta$itemsPerPage |
Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 588 | if (nrow(collectedMatches) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) { |
Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 589 | break |
| 590 | } |
| 591 | } |
Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 592 | nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 593 | KorAPQuery( |
| 594 | nextStartIndex = nextStartIndex, |
Marc Kupietz | d0d3e9b | 2019-09-24 17:36:03 +0200 | [diff] [blame] | 595 | korapConnection = kqo@korapConnection, |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 596 | fields = kqo@fields, |
| 597 | requestUrl = kqo@requestUrl, |
| 598 | request = kqo@request, |
Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 599 | totalResults = kqo@totalResults, |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 600 | vc = kqo@vc, |
| 601 | webUIRequestUrl = kqo@webUIRequestUrl, |
Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 602 | hasMoreMatches = (kqo@totalResults > nextStartIndex), |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 603 | apiResponse = res, |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 604 | collectedMatches = collectedMatches |
| 605 | ) |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 606 | }) |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 607 | |
| 608 | #' Fetch all results of a KorAP query. |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 609 | #' |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 610 | #' **`fetchAll`** fetches all results of a KorAP query. |
Marc Kupietz | a6e4ee6 | 2021-03-05 09:00:15 +0100 | [diff] [blame] | 611 | #' |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 612 | #' @examples |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 613 | #' \dontrun{ |
| 614 | #' |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 615 | #' q <- KorAPConnection() %>% |
| 616 | #' corpusQuery("Ameisenplage") %>% |
| 617 | #' fetchAll() |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 618 | #' q@collectedMatches |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 619 | #' } |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 620 | #' |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 621 | #' @aliases fetchAll |
| 622 | #' @rdname KorAPQuery-class |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 623 | #' @export |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 624 | setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) { |
| 625 | return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...)) |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 626 | }) |
| 627 | |
| 628 | #' Fetches the remaining results of a KorAP query. |
| 629 | #' |
| 630 | #' @examples |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 631 | #' \dontrun{ |
| 632 | #' |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 633 | #' q <- KorAPConnection() %>% |
| 634 | #' corpusQuery("Ameisenplage") %>% |
| 635 | #' fetchRest() |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 636 | #' q@collectedMatches |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 637 | #' } |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 638 | #' |
| 639 | #' @aliases fetchRest |
| 640 | #' @rdname KorAPQuery-class |
| 641 | #' @export |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 642 | setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) { |
| 643 | return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...)) |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 644 | }) |
| 645 | |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 646 | #' Query frequencies of search expressions in virtual corpora |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 647 | #' |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 648 | #' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 649 | #' [ci()] to compute a tibble with the absolute and relative frequencies and |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 650 | #' confidence intervals of one ore multiple search terms across one or multiple |
| 651 | #' virtual corpora. |
| 652 | #' |
| 653 | #' @aliases frequencyQuery |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 654 | #' @examples |
Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 655 | #' \dontrun{ |
| 656 | #' |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 657 | #' KorAPConnection(verbose = TRUE) |> |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 658 | #' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003)) |
Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 659 | #' } |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 660 | #' |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 661 | # @inheritParams corpusQuery |
Marc Kupietz | 617266d | 2025-02-27 10:43:07 +0100 | [diff] [blame] | 662 | #' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()` |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 663 | #' @param query corpus query string(s.) (can be a vector). The query language depends on the `ql` parameter. Either `query` must be provided or `KorAPUrl`. |
| 664 | #' @param vc virtual corpus definition(s) (can be a vector) |
Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 665 | #' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]). |
| 666 | #' @param as.alternatives LOGICAL that specifies if the query terms should be treated as alternatives. If `as.alternatives` is TRUE, the sum over all query hits, instead of the respective vc token sizes is used as total for the calculation of relative frequencies. |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 667 | #' @param ... further arguments passed to or from other methods (see [corpusQuery()]), most notably `expand`, a logical that decides if `query` and `vc` parameters are expanded to all of their combinations. It defaults to `TRUE`, if `query` and `vc` have different lengths, and to `FALSE` otherwise. |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 668 | #' @export |
Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 669 | #' |
| 670 | #' @return A tibble, with each row containing the following result columns for query and vc combinations: |
| 671 | #' - **query**: the query string used for the frequency analysis. |
| 672 | #' - **totalResults**: absolute frequency of query matches in the vc. |
| 673 | #' - **vc**: virtual corpus used for the query. |
| 674 | #' - **webUIRequestUrl**: URL of the corresponding web UI request with respect to query and vc. |
| 675 | #' - **total**: total number of words in vc. |
| 676 | #' - **f**: relative frequency of query matches in the vc. |
| 677 | #' - **conf.low**: lower bound of the confidence interval for the relative frequency, given `conf.level`. |
| 678 | #' - **conf.high**: upper bound of the confidence interval for the relative frequency, given `conf.level`. |
| 679 | |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 680 | setMethod( |
| 681 | "frequencyQuery", "KorAPConnection", |
Marc Kupietz | 71d6e05 | 2019-11-22 18:42:10 +0100 | [diff] [blame] | 682 | function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE, ...) { |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 683 | (if (as.alternatives) { |
| 684 | corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |> |
Marc Kupietz | 71d6e05 | 2019-11-22 18:42:10 +0100 | [diff] [blame] | 685 | group_by(vc) %>% |
| 686 | mutate(total = sum(totalResults)) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 687 | } else { |
| 688 | corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |> |
| 689 | mutate(total = corpusStats(kco, vc = vc, as.df = TRUE)$tokens) |
| 690 | }) %>% |
Marc Kupietz | 0c29cea | 2019-10-09 08:44:36 +0200 | [diff] [blame] | 691 | ci(conf.level = conf.level) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 692 | } |
| 693 | ) |
Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 694 | |
Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 695 | #' buildWebUIRequestUrlFromString |
| 696 | #' |
| 697 | #' @rdname KorAPQuery-class |
| 698 | #' @importFrom urltools url_encode |
| 699 | #' @export |
| 700 | buildWebUIRequestUrlFromString <- function(KorAPUrl, |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 701 | query, |
| 702 | vc = "", |
| 703 | ql = "poliqarp") { |
Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 704 | if ("KorAPConnection" %in% class(KorAPUrl)) { |
| 705 | KorAPUrl <- KorAPUrl@KorAPUrl |
| 706 | } |
| 707 | |
| 708 | request <- |
| 709 | paste0( |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 710 | "?q=", |
Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 711 | urltools::url_encode(enc2utf8(as.character(query))), |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 712 | ifelse(vc != "", |
| 713 | paste0("&cq=", urltools::url_encode(enc2utf8(vc))), |
| 714 | "" |
| 715 | ), |
| 716 | "&ql=", |
Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 717 | ql |
| 718 | ) |
| 719 | paste0(KorAPUrl, request) |
| 720 | } |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 721 | |
| 722 | #' buildWebUIRequestUrl |
| 723 | #' |
| 724 | #' @rdname KorAPQuery-class |
Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 725 | #' @importFrom httr2 url_parse |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 726 | #' @export |
| 727 | buildWebUIRequestUrl <- function(kco, |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 728 | query = if (missing(KorAPUrl)) { |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 729 | stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE) |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 730 | } else { |
| 731 | httr2::url_parse(KorAPUrl)$query$q |
| 732 | }, |
Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 733 | vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq, |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 734 | KorAPUrl, |
Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 735 | ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql) { |
Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 736 | buildWebUIRequestUrlFromString(kco@KorAPUrl, query, vc, ql) |
Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 737 | } |
| 738 | |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 739 | #' format() |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 740 | #' @rdname KorAPQuery-class |
| 741 | #' @param x KorAPQuery object |
| 742 | #' @param ... further arguments passed to or from other methods |
Marc Kupietz | b73ca0f | 2025-01-28 20:45:01 +0100 | [diff] [blame] | 743 | #' @importFrom urltools param_get url_decode |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 744 | #' @export |
| 745 | format.KorAPQuery <- function(x, ...) { |
| 746 | cat("<KorAPQuery>\n") |
| 747 | q <- x |
Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 748 | param <- urltools::param_get(q@request) |> lapply(urltools::url_decode) |
Marc Kupietz | b73ca0f | 2025-01-28 20:45:01 +0100 | [diff] [blame] | 749 | cat(" Query: ", param$q, "\n") |
| 750 | if (!is.null(param$cq) && param$cq != "") { |
| 751 | cat(" Virtual corpus: ", param$cq, "\n") |
| 752 | } |
| 753 | if (!is.null(q@collectedMatches)) { |
| 754 | cat("==============================================================================================================", "\n") |
| 755 | print(summary(q@collectedMatches)) |
| 756 | cat("==============================================================================================================", "\n") |
| 757 | } |
| 758 | cat(" Total results: ", q@totalResults, "\n") |
| 759 | cat(" Fetched results: ", q@nextStartIndex, "\n") |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 760 | } |
| 761 | |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 762 | #' show() |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 763 | #' |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 764 | #' @rdname KorAPQuery-class |
| 765 | #' @param object KorAPQuery object |
Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 766 | #' @export |
Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 767 | setMethod("show", "KorAPQuery", function(object) { |
| 768 | format(object) |
| 769 | }) |