| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 1 | #' KorAPQuery class (internal) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 2 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 3 | #' Internal class for query state management. Users work with `corpusQuery()`, `fetchAll()`, and `fetchNext()` instead. |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 4 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 5 | #' @keywords internal |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 6 | #' @include KorAPConnection.R |
| Marc Kupietz | 6dfeed9 | 2025-06-03 11:58:06 +0200 | [diff] [blame] | 7 | #' @include logging.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", |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 24 | "hasMoreMatches" |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 25 | )) |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 26 | |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 27 | #' Initialize KorAPQuery object |
| 28 | #' @keywords internal |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 29 | #' @param .Object … |
| Marc Kupietz | b897218 | 2019-09-20 21:33:46 +0200 | [diff] [blame] | 30 | #' @param korapConnection KorAPConnection object |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 31 | #' @param request query part of the request URL |
| 32 | #' @param vc definition of a virtual corpus |
| 33 | #' @param totalResults number of hits the query has yielded |
| 34 | #' @param nextStartIndex at what index to start the next fetch of query results |
| 35 | #' @param fields what data / metadata fields should be collected |
| 36 | #' @param requestUrl complete URL of the API request |
| 37 | #' @param webUIRequestUrl URL of a web frontend request corresponding to the API request |
| 38 | #' @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] | 39 | #' @param hasMoreMatches logical that signals if more query results can be fetched |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 40 | #' @param collectedMatches matches already fetched from the KorAP-API-server |
| Marc Kupietz | 97a1bca | 2019-10-04 22:52:09 +0200 | [diff] [blame] | 41 | #' |
| 42 | #' @importFrom tibble tibble |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 43 | #' @export |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 44 | setMethod( |
| 45 | "initialize", "KorAPQuery", |
| 46 | function(.Object, korapConnection = NULL, request = NULL, vc = "", totalResults = 0, nextStartIndex = 0, fields = c( |
| 47 | "corpusSigle", "textSigle", "pubDate", "pubPlace", |
| Marc Kupietz | 8ad0746 | 2026-09-14 11:58:36 +0200 | [diff] [blame^] | 48 | "availability", "textClass", "dmozDomain", "wikiDomain", |
| 49 | "snippet", "tokens" |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 50 | ), |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 51 | requestUrl = "", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches = FALSE, collectedMatches = NULL) { |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 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")) |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 72 | setGeneric( |
| 73 | "fetchAnnotations", |
| 74 | function(kqo, |
| 75 | foundry = "tt", |
| 76 | overwrite = FALSE, |
| 77 | verbose = kqo@korapConnection@verbose) standardGeneric("fetchAnnotations") |
| 78 | ) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 79 | setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery")) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 80 | |
| 81 | maxResultsPerPage <- 50 |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 82 | |
| Marc Kupietz | 4de53ec | 2019-10-04 09:12:00 +0200 | [diff] [blame] | 83 | ## 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] | 84 | utils::globalVariables(c(".")) |
| Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 85 | |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 86 | #' Search corpus for query terms |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 87 | #' |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 88 | #' **`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] | 89 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 90 | #' @family corpus search functions |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 91 | #' @aliases corpusQuery |
| 92 | #' |
| 93 | #' @importFrom urltools url_encode |
| 94 | #' @importFrom purrr pmap |
| Marc Kupietz | ea34b81 | 2025-06-25 15:49:00 +0200 | [diff] [blame] | 95 | #' @importFrom dplyr bind_rows group_by |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 96 | #' |
| Marc Kupietz | 617266d | 2025-02-27 10:43:07 +0100 | [diff] [blame] | 97 | #' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()` |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 98 | #' @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] | 99 | #' @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] | 100 | #' @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] | 101 | #' @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. |
| 102 | #' If you want your corpus queries to return not only metadata, but also KWICS, you need to authorize |
| 103 | #' your RKorAPClient application as explained in the |
| 104 | #' [authorization section](https://github.com/KorAP/RKorAPClient#authorization) |
| 105 | #' of the RKorAPClient Readme on GitHub and set the `metadataOnly` parameter to |
| 106 | #' `FALSE`. |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 107 | #' @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. |
| Marc Kupietz | 1623fe8 | 2025-06-24 16:31:46 +0200 | [diff] [blame] | 108 | #' @param fields character vector specifying which metadata fields to retrieve for each match. |
| 109 | #' Available fields depend on the corpus. For DeReKo (German Reference Corpus), possible fields include: |
| 110 | #' \describe{ |
| 111 | #' \item{**Text identification**:}{`textSigle`, `docSigle`, `corpusSigle` - hierarchical text identifiers} |
| 112 | #' \item{**Publication info**:}{`author`, `editor`, `title`, `docTitle`, `corpusTitle` - authorship and titles} |
| 113 | #' \item{**Temporal data**:}{`pubDate`, `creationDate` - when text was published/created} |
| 114 | #' \item{**Publication details**:}{`pubPlace`, `publisher`, `reference` - where/how published} |
| Marc Kupietz | 8ad0746 | 2026-09-14 11:58:36 +0200 | [diff] [blame^] | 115 | #' \item{**Text classification**:}{`textClass`, `dmozDomain`, `wikiDomain`, `textType`, `textTypeArt`, `textDomain`, `textColumn` - topic domain, genre, text type and column} |
| Marc Kupietz | 1623fe8 | 2025-06-24 16:31:46 +0200 | [diff] [blame] | 116 | #' \item{**Adminstrative and technical info**:}{`corpusEditor`, `availability`, `language`, `foundries` - access rights and annotations} |
| 117 | #' \item{**Content data**:}{`snippet`, `tokens`, `tokenSource`, `externalLink` - actual text content, tokenization, and link to source text} |
| 118 | #' \item{**System data**:}{`indexCreationDate`, `indexLastModified` - corpus indexing info} |
| 119 | #' } |
| 120 | #' Use `c("textSigle", "pubDate", "author")` to retrieve multiple fields. |
| 121 | #' Default fields provide basic text identification and publication metadata. The actual text content (`snippet` and `tokens`) are activated by default if `metadataOnly` is set to `FALSE`. |
| Marc Kupietz | 43a6ade | 2020-02-18 17:01:44 +0100 | [diff] [blame] | 122 | #' @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] | 123 | #' @param verbose print some info |
| Marc Kupietz | 4de53ec | 2019-10-04 09:12:00 +0200 | [diff] [blame] | 124 | #' @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] | 125 | #' @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] | 126 | #' @param context string that specifies the size of the left and the right context returned in `snippet` |
| 127 | #' (provided that `metadataOnly` is set to `false` and that the necessary access right are met). |
| 128 | #' 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). |
| 129 | #' If the parameter is not set, the default context size secification of the KorAP server instance will be used. |
| 130 | #' Note that you cannot overrule the maximum context size set in the KorAP server instance, |
| 131 | #' as this is typically legally motivated. |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 132 | #' @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] | 133 | #' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl` |
| 134 | #' 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] | 135 | #' |
| 136 | #' @examples |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 137 | #' \dontrun{ |
| 138 | #' |
| Marc Kupietz | 1623fe8 | 2025-06-24 16:31:46 +0200 | [diff] [blame] | 139 | #' # Fetch basic metadata for "Ameisenplage" |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 140 | #' KorAPConnection() |> |
| 141 | #' corpusQuery("Ameisenplage") |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 142 | #' fetchAll() |
| Marc Kupietz | 1623fe8 | 2025-06-24 16:31:46 +0200 | [diff] [blame] | 143 | #' |
| 144 | #' # Fetch specific metadata fields for bibliographic analysis |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 145 | #' query <- KorAPConnection() |> |
| Marc Kupietz | 1623fe8 | 2025-06-24 16:31:46 +0200 | [diff] [blame] | 146 | #' corpusQuery("Ameisenplage", |
| 147 | #' fields = c("textSigle", "author", "title", "pubDate", "pubPlace", "textType")) |
| 148 | #' results <- fetchAll(query) |
| 149 | #' results@collectedMatches |
| Marc Kupietz | 657d8e7 | 2020-02-25 18:31:50 +0100 | [diff] [blame] | 150 | #' } |
| Marc Kupietz | 3c531f6 | 2019-09-13 12:17:24 +0200 | [diff] [blame] | 151 | #' |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 152 | #' \dontrun{ |
| 153 | #' |
| Marc Kupietz | 603491f | 2019-09-18 14:01:02 +0200 | [diff] [blame] | 154 | #' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus |
| 155 | #' # and show the number of query hits (but don't fetch them). |
| Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 156 | #' |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 157 | #' KorAPConnection(verbose = TRUE) |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 158 | #' corpusQuery( |
| 159 | #' KorAPUrl = |
| 160 | #' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp" |
| 161 | #' ) |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 162 | #' } |
| 163 | #' |
| 164 | #' \dontrun{ |
| Marc Kupietz | 3c531f6 | 2019-09-13 12:17:24 +0200 | [diff] [blame] | 165 | #' |
| Marc Kupietz | 603491f | 2019-09-18 14:01:02 +0200 | [diff] [blame] | 166 | #' # Plot the time/frequency curve of "Ameisenplage" |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 167 | #' KorAPConnection(verbose = TRUE) |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 168 | #' { |
| 169 | #' . ->> kco |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 170 | #' } |> |
| 171 | #' corpusQuery("Ameisenplage") |> |
| 172 | #' fetchAll() |> |
| 173 | #' slot("collectedMatches") |> |
| 174 | #' mutate(year = lubridate::year(pubDate)) |> |
| 175 | #' dplyr::select(year) |> |
| 176 | #' group_by(year) |> |
| 177 | #' summarise(Count = dplyr::n()) |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 178 | #' mutate(Freq = mapply(function(f, y) { |
| 179 | #' f / corpusStats(kco, paste("pubDate in", y))@tokens |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 180 | #' }, Count, year)) |> |
| 181 | #' dplyr::select(-Count) |> |
| 182 | #' complete(year = min(year):max(year), fill = list(Freq = 0)) |> |
| Marc Kupietz | 69cc54a | 2019-09-30 12:06:54 +0200 | [diff] [blame] | 183 | #' plot(type = "l") |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 184 | #' } |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 185 | #' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()] |
| Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 186 | #' |
| 187 | #' @references |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 188 | #' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026> |
| Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 189 | #' |
| 190 | #' @export |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 191 | setMethod( |
| 192 | "corpusQuery", "KorAPConnection", |
| 193 | function(kco, |
| 194 | query = if (missing(KorAPUrl)) { |
| 195 | stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE) |
| 196 | } else { |
| 197 | httr2::url_parse(KorAPUrl)$query$q |
| 198 | }, |
| 199 | vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq, |
| 200 | KorAPUrl, |
| 201 | metadataOnly = TRUE, |
| 202 | ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql, |
| 203 | fields = c( |
| 204 | "corpusSigle", |
| 205 | "textSigle", |
| 206 | "pubDate", |
| 207 | "pubPlace", |
| 208 | "availability", |
| 209 | "textClass", |
| Marc Kupietz | 8ad0746 | 2026-09-14 11:58:36 +0200 | [diff] [blame^] | 210 | "dmozDomain", |
| 211 | "wikiDomain", |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 212 | "snippet", |
| 213 | "tokens" |
| 214 | ), |
| 215 | accessRewriteFatal = TRUE, |
| 216 | verbose = kco@verbose, |
| 217 | expand = length(vc) != length(query), |
| 218 | as.df = FALSE, |
| 219 | context = NULL) { |
| 220 | if (length(query) > 1 || length(vc) > 1) { |
| Marc Kupietz | f632fe3 | 2026-09-08 07:58:46 +0200 | [diff] [blame] | 221 | # expand_grid() and tibble() drop the names of vc, so the labels the |
| 222 | # caller gave their virtual corpora are carried along as a column |
| 223 | vcLabel <- vcLabels(vc) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 224 | grid <- if (expand) expand_grid(query = query, vc = vc) else tibble(query = query, vc = vc) |
| Marc Kupietz | f632fe3 | 2026-09-08 07:58:46 +0200 | [diff] [blame] | 225 | if (!is.null(vcLabel)) { |
| 226 | grid$label <- if (expand) rep(vcLabel, times = length(query)) else vcLabel |
| 227 | } |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 228 | |
| 229 | # Initialize timing variables for ETA calculation |
| 230 | total_queries <- nrow(grid) |
| 231 | current_query <- 0 |
| 232 | start_time <- Sys.time() |
| 233 | |
| Marc Kupietz | f632fe3 | 2026-09-08 07:58:46 +0200 | [diff] [blame] | 234 | results <- purrr::pmap(grid, function(query, vc, label = NULL, ...) { |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 235 | current_query <<- current_query + 1 |
| 236 | |
| 237 | # Execute the single query directly (avoiding recursive call) |
| 238 | contentFields <- c("snippet", "tokens") |
| 239 | query_fields <- fields |
| 240 | if (metadataOnly) { |
| 241 | query_fields <- query_fields[!query_fields %in% contentFields] |
| 242 | } |
| 243 | if (!"textSigle" %in% query_fields) { |
| 244 | query_fields <- c(query_fields, "textSigle") |
| 245 | } |
| 246 | request <- |
| 247 | paste0( |
| 248 | "?q=", |
| 249 | url_encode(enc2utf8(query)), |
| 250 | ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""), |
| 251 | ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""), |
| 252 | ifelse(!metadataOnly, "&show-tokens=true", ""), |
| 253 | "&ql=", ql |
| 254 | ) |
| 255 | webUIRequestUrl <- paste0(kco@KorAPUrl, request) |
| 256 | requestUrl <- paste0( |
| 257 | kco@apiUrl, |
| 258 | "search", |
| 259 | request, |
| 260 | "&fields=", |
| 261 | paste(query_fields, collapse = ","), |
| 262 | if (metadataOnly) "&access-rewrite-disabled=true" else "" |
| 263 | ) |
| 264 | |
| 265 | # Show individual query progress |
| 266 | log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"", sep = "") |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 267 | queryStart <- Sys.time() |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 268 | res <- apiCall(kco, paste0(requestUrl, "&count=0")) |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 269 | queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs")) |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 270 | if (is.null(res)) { |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 271 | log_info(verbose, ": API call failed after ", sprintf("%.1f", queryDuration), "s\n") |
| 272 | warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE) |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 273 | totalResults <- 0 |
| 274 | } else { |
| 275 | totalResults <- as.integer(res$meta$totalResults) |
| 276 | log_info(verbose, ": ", totalResults, " hits") |
| 277 | if (!is.null(res$meta$cached)) { |
| 278 | log_info(verbose, " [cached]") |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 279 | } |
| 280 | log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s") |
| 281 | if (!is.null(res$meta$timeExceeded)) { |
| 282 | warning( |
| 283 | "The query \u201c", query, "\u201d was cut short by the KorAP server ", |
| 284 | "(timeExceeded); the reported results are incomplete.", |
| 285 | call. = FALSE |
| 286 | ) |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 287 | } |
| Marc Kupietz | 365660e | 2025-06-25 15:09:55 +0200 | [diff] [blame] | 288 | |
| 289 | # Calculate and display ETA information on the same line if verbose and we have more than one query |
| 290 | if (verbose && total_queries > 1) { |
| 291 | eta_info <- calculate_eta(current_query, total_queries, start_time) |
| 292 | if (eta_info != "") { |
| 293 | elapsed_time <- as.numeric(difftime(Sys.time(), start_time, units = "secs")) |
| 294 | avg_time_per_query <- elapsed_time / current_query |
| 295 | |
| 296 | # Add ETA info to the same line - remove the leading ". " for cleaner formatting |
| 297 | clean_eta_info <- sub("^\\. ", ". ", eta_info) |
| 298 | log_info(verbose, clean_eta_info) |
| 299 | } |
| 300 | } |
| 301 | |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 302 | log_info(verbose, "\n") |
| 303 | } |
| 304 | |
| 305 | result <- data.frame( |
| 306 | query = query, |
| 307 | totalResults = totalResults, |
| 308 | vc = vc, |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 309 | queryDuration = queryDuration, |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 310 | webUIRequestUrl = webUIRequestUrl, |
| 311 | stringsAsFactors = FALSE |
| 312 | ) |
| Marc Kupietz | f632fe3 | 2026-09-08 07:58:46 +0200 | [diff] [blame] | 313 | if (!is.null(label)) { |
| 314 | result <- tibble::add_column(result, label = label, .after = "vc") |
| 315 | } |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 316 | |
| Marc Kupietz | 6ef61a8 | 2025-05-29 16:07:03 +0200 | [diff] [blame] | 317 | return(result) |
| 318 | }) |
| 319 | |
| 320 | results %>% bind_rows() |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 321 | } else { |
| Marc Kupietz | 2078bde | 2023-08-27 16:46:15 +0200 | [diff] [blame] | 322 | contentFields <- c("snippet", "tokens") |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 323 | if (metadataOnly) { |
| 324 | fields <- fields[!fields %in% contentFields] |
| 325 | } |
| Marc Kupietz | 80dc643 | 2025-02-07 16:57:40 +0100 | [diff] [blame] | 326 | if (!"textSigle" %in% fields) { |
| 327 | fields <- c(fields, "textSigle") |
| 328 | } |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 329 | request <- |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 330 | paste0( |
| 331 | "?q=", |
| 332 | url_encode(enc2utf8(query)), |
| 333 | ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""), |
| 334 | ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""), |
| 335 | ifelse(!metadataOnly, "&show-tokens=true", ""), |
| 336 | "&ql=", ql |
| 337 | ) |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 338 | webUIRequestUrl <- paste0(kco@KorAPUrl, request) |
| 339 | requestUrl <- paste0( |
| 340 | kco@apiUrl, |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 341 | "search", |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 342 | request, |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 343 | "&fields=", |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 344 | paste(fields, collapse = ","), |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 345 | if (metadataOnly) "&access-rewrite-disabled=true" else "" |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 346 | ) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 347 | log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"", |
| 348 | sep = |
| 349 | "" |
| 350 | ) |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 351 | queryStart <- Sys.time() |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 352 | res <- apiCall(kco, paste0(requestUrl, "&count=0")) |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 353 | queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs")) |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 354 | if (is.null(res)) { |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 355 | message("API call failed.") |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 356 | warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE) |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 357 | totalResults <- 0 |
| 358 | } else { |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 359 | totalResults <- as.integer(res$meta$totalResults) |
| Marc Kupietz | a47d150 | 2023-04-18 15:26:47 +0200 | [diff] [blame] | 360 | log_info(verbose, ": ", totalResults, " hits") |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 361 | if (!is.null(res$meta$cached)) { |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 362 | log_info(verbose, " [cached]") |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 363 | } |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 364 | log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s") |
| 365 | if (!is.null(res$meta$timeExceeded)) { |
| 366 | warning( |
| 367 | "The query \u201c", query, "\u201d was cut short by the KorAP server ", |
| 368 | "(timeExceeded); the reported results are incomplete.", |
| 369 | call. = FALSE |
| 370 | ) |
| 371 | } |
| 372 | log_info(verbose, "\n") |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 373 | } |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 374 | if (as.df) { |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 375 | data.frame( |
| 376 | query = query, |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 377 | totalResults = totalResults, |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 378 | vc = vc, |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 379 | queryDuration = queryDuration, |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 380 | webUIRequestUrl = webUIRequestUrl, |
| 381 | stringsAsFactors = FALSE |
| 382 | ) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 383 | } else { |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 384 | KorAPQuery( |
| 385 | korapConnection = kco, |
| 386 | nextStartIndex = 0, |
| 387 | fields = fields, |
| 388 | requestUrl = requestUrl, |
| 389 | request = request, |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 390 | totalResults = totalResults, |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 391 | vc = vc, |
| 392 | apiResponse = res, |
| 393 | webUIRequestUrl = webUIRequestUrl, |
| Marc Kupietz | a467572 | 2022-02-23 23:55:15 +0100 | [diff] [blame] | 394 | hasMoreMatches = (totalResults > 0), |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 395 | ) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 396 | } |
| Marc Kupietz | a96537f | 2019-11-09 23:07:44 +0100 | [diff] [blame] | 397 | } |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 398 | } |
| 399 | ) |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 400 | |
| Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 401 | #' @importFrom purrr map |
| 402 | repair_data_strcuture <- function(x) { |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 403 | if (is.list(x)) { |
| 404 | as.character(purrr::map(x, ~ if (length(.x) > 1) { |
| Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 405 | paste(.x, collapse = " ") |
| 406 | } else { |
| 407 | .x |
| 408 | })) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 409 | } else { |
| Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 410 | ifelse(is.na(x), "", x) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 411 | } |
| Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 412 | } |
| 413 | |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 414 | #' Fetch the next bunch of results of a KorAP query. |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 415 | #' |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 416 | #' **`fetchNext`** fetches the next bunch of results of a KorAP query. |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 417 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 418 | #' @family corpus search functions |
| 419 | #' |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 420 | #' @param kqo object obtained from [corpusQuery()] |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 421 | #' @param offset start offset for query results to fetch |
| 422 | #' @param maxFetch maximum number of query results to fetch |
| Marc Kupietz | 25aebc3 | 2019-09-16 18:40:50 +0200 | [diff] [blame] | 423 | #' @param verbose print progress information if true |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 424 | #' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results. |
| 425 | #' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches` |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 426 | #' |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 427 | #' @examples |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 428 | #' \dontrun{ |
| 429 | #' |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 430 | #' q <- KorAPConnection() |> |
| 431 | #' corpusQuery("Ameisenplage") |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 432 | #' fetchNext() |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 433 | #' q@collectedMatches |
| Marc Kupietz | 657d8e7 | 2020-02-25 18:31:50 +0100 | [diff] [blame] | 434 | #' } |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 435 | #' |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 436 | #' @references |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 437 | #' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026> |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 438 | #' |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 439 | #' @aliases fetchNext |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 440 | #' @importFrom dplyr rowwise mutate bind_rows select summarise n select |
| Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 441 | #' @importFrom tibble enframe add_column |
| 442 | #' @importFrom stringr word |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 443 | #' @importFrom tidyr unnest unchop pivot_wider |
| 444 | #' @importFrom purrr map |
| Marc Kupietz | 632cbd4 | 2019-09-06 16:04:51 +0200 | [diff] [blame] | 445 | #' @export |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 446 | setMethod("fetchNext", "KorAPQuery", function(kqo, |
| 447 | offset = kqo@nextStartIndex, |
| 448 | maxFetch = maxResultsPerPage, |
| 449 | verbose = kqo@korapConnection@verbose, |
| 450 | randomizePageOrder = FALSE) { |
| Marc Kupietz | a7a8f1b | 2024-12-18 15:56:19 +0100 | [diff] [blame] | 451 | # 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] | 452 | results <- key <- name <- tmp_positions <- 0 |
| Marc Kupietz | a7a8f1b | 2024-12-18 15:56:19 +0100 | [diff] [blame] | 453 | |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 454 | if (kqo@totalResults == 0 || offset >= kqo@totalResults) { |
| 455 | return(kqo) |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 456 | } |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 457 | use_korap_api <- Sys.getenv("USE_KORAP_API", unset = NA) |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 458 | # Calculate the initial page number (not used directly - keeping for reference) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 459 | collectedMatches <- kqo@collectedMatches |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 460 | |
| Marc Kupietz | 24799fd | 2025-06-25 14:15:36 +0200 | [diff] [blame] | 461 | # Track start time for ETA calculation |
| 462 | start_time <- Sys.time() |
| 463 | |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 464 | # For randomized page order, generate a list of randomized page indices |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 465 | if (randomizePageOrder) { |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 466 | # Calculate how many pages we need to fetch based on maxFetch |
| 467 | total_pages_to_fetch <- if (!is.na(maxFetch)) { |
| 468 | # Either limited by maxFetch or total results, whichever is smaller |
| 469 | min(ceiling(maxFetch / maxResultsPerPage), ceiling(kqo@totalResults / maxResultsPerPage)) |
| 470 | } else { |
| 471 | # All pages |
| 472 | ceiling(kqo@totalResults / maxResultsPerPage) |
| 473 | } |
| 474 | |
| 475 | # Generate randomized page indices (0-based for API) |
| 476 | pages <- sample.int(ceiling(kqo@totalResults / maxResultsPerPage), total_pages_to_fetch) - 1 |
| 477 | 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] | 478 | } |
| 479 | |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 480 | if (is.null(collectedMatches)) { |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 481 | collectedMatches <- data.frame() |
| 482 | } |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 483 | |
| 484 | # Initialize the page counter properly based on nextStartIndex and any previously fetched results |
| 485 | # We add 1 to make it 1-based for display purposes since users expect page numbers to start from 1 |
| 486 | # For first call, this will be 1, for subsequent calls, it will reflect our actual position |
| 487 | current_page_number <- ceiling(offset / maxResultsPerPage) + 1 |
| 488 | |
| 489 | # For sequential fetches, keep track of which global page we're on |
| 490 | # This is important for correctly showing page numbers in subsequent fetchNext calls |
| 491 | page_count_start <- current_page_number |
| 492 | |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 493 | repeat { |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 494 | # Determine which page to fetch next |
| 495 | if (randomizePageOrder) { |
| 496 | # In randomized mode, get the page from our randomized list using the page_index |
| 497 | # Make sure we don't exceed the array bounds |
| 498 | if (page_index > length(pages)) { |
| 499 | break # No more pages to fetch in randomized mode |
| 500 | } |
| 501 | current_offset_page <- pages[page_index] |
| 502 | # For display purposes in randomized mode, show which page out of the total we're fetching |
| 503 | display_page_number <- page_index |
| 504 | } else { |
| 505 | # In sequential mode, use the current_page_number to calculate the offset |
| 506 | current_offset_page <- (current_page_number - 1) |
| 507 | display_page_number <- current_page_number |
| 508 | } |
| 509 | |
| 510 | # Calculate the actual offset in tokens |
| 511 | currentOffset <- current_offset_page * maxResultsPerPage |
| 512 | |
| Marc Kupietz | ef0e939 | 2025-06-18 12:21:49 +0200 | [diff] [blame] | 513 | # Build the query with the appropriate count and offset using httr2 |
| 514 | count_param <- min(if (!is.na(maxFetch)) maxFetch - results else maxResultsPerPage, maxResultsPerPage) |
| Marc Kupietz | ecc8670 | 2025-06-24 12:12:51 +0200 | [diff] [blame] | 515 | |
| Marc Kupietz | ef0e939 | 2025-06-18 12:21:49 +0200 | [diff] [blame] | 516 | # Parse existing URL to preserve all query parameters |
| 517 | parsed_url <- httr2::url_parse(kqo@requestUrl) |
| 518 | existing_query <- parsed_url$query |
| Marc Kupietz | ecc8670 | 2025-06-24 12:12:51 +0200 | [diff] [blame] | 519 | |
| Marc Kupietz | ef0e939 | 2025-06-18 12:21:49 +0200 | [diff] [blame] | 520 | # Add/update count and offset parameters |
| 521 | existing_query$count <- count_param |
| 522 | existing_query$offset <- currentOffset |
| Marc Kupietz | ecc8670 | 2025-06-24 12:12:51 +0200 | [diff] [blame] | 523 | |
| Marc Kupietz | ef0e939 | 2025-06-18 12:21:49 +0200 | [diff] [blame] | 524 | # Rebuild the URL with all parameters |
| 525 | query <- httr2::url_modify(kqo@requestUrl, query = existing_query) |
| Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 526 | res <- apiCall(kqo@korapConnection, query) |
| 527 | if (length(res$matches) == 0) { |
| 528 | break |
| 529 | } |
| 530 | |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 531 | 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] | 532 | log_info(verbose, "Using fields API: ") |
| Marc Kupietz | 05a6079 | 2024-12-07 16:23:31 +0100 | [diff] [blame] | 533 | currentMatches <- res$matches$fields %>% |
| 534 | purrr::map(~ mutate(.x, value = repair_data_strcuture(value))) %>% |
| 535 | tibble::enframe() %>% |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 536 | tidyr::unnest(cols = value) %>% |
| 537 | tidyr::pivot_wider(names_from = key, id_cols = name, names_repair = "unique") %>% |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 538 | dplyr::select(-name) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 539 | if ("snippet" %in% colnames(res$matches)) { |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 540 | currentMatches$snippet <- res$matches$snippet |
| 541 | } |
| Marc Kupietz | 3cd2c6c | 2025-01-08 20:35:39 +0100 | [diff] [blame] | 542 | if ("tokens" %in% colnames(res$matches)) { |
| 543 | currentMatches$tokens <- res$matches$tokens |
| 544 | } |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 545 | } else { |
| 546 | currentMatches <- res$matches |
| 547 | } |
| 548 | |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 549 | for (field in kqo@fields) { |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 550 | if (!field %in% colnames(currentMatches)) { |
| 551 | currentMatches[, field] <- NA |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 552 | } |
| 553 | } |
| Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 554 | currentMatches <- currentMatches %>% |
| 555 | select(kqo@fields) %>% |
| 556 | mutate( |
| Marc Kupietz | ff712a9 | 2025-07-18 09:07:23 +0200 | [diff] [blame] | 557 | matchID = res$matches$matchID, |
| Marc Kupietz | 0447da0 | 2025-01-08 20:51:09 +0100 | [diff] [blame] | 558 | tmp_positions = gsub(".*-p(\\d+)-(\\d+).*", "\\1 \\2", res$matches$matchID), |
| Marc Kupietz | f488112 | 2024-12-17 14:55:39 +0100 | [diff] [blame] | 559 | matchStart = as.integer(stringr::word(tmp_positions, 1)), |
| 560 | matchEnd = as.integer(stringr::word(tmp_positions, 2)) - 1 |
| 561 | ) %>% |
| 562 | select(-tmp_positions) |
| 563 | |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 564 | if (!is.list(collectedMatches)) { |
| 565 | collectedMatches <- currentMatches |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 566 | } else { |
| Marc Kupietz | 2078bde | 2023-08-27 16:46:15 +0200 | [diff] [blame] | 567 | collectedMatches <- bind_rows(collectedMatches, currentMatches) |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 568 | } |
| Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 569 | |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 570 | # Get the actual items per page from the API response |
| 571 | # We now consistently use maxResultsPerPage instead |
| Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 572 | |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 573 | # Calculate total pages consistently using fixed maxResultsPerPage |
| 574 | # This ensures consistent page counting across the function |
| 575 | total_pages <- ceiling(kqo@totalResults / maxResultsPerPage) |
| 576 | |
| Marc Kupietz | 24799fd | 2025-06-25 14:15:36 +0200 | [diff] [blame] | 577 | # Calculate ETA using the centralized function from logging.R |
| 578 | current_page <- if (randomizePageOrder) page_index else display_page_number |
| 579 | total_pages_to_fetch <- if (!is.na(maxFetch)) { |
| 580 | # Account for offset - we can only fetch from the remaining results after offset |
| 581 | remaining_results_after_offset <- max(0, kqo@totalResults - offset) |
| 582 | min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage)) |
| 583 | } else { |
| 584 | total_pages |
| 585 | } |
| Marc Kupietz | 365660e | 2025-06-25 15:09:55 +0200 | [diff] [blame] | 586 | |
| Marc Kupietz | 24799fd | 2025-06-25 14:15:36 +0200 | [diff] [blame] | 587 | eta_info <- calculate_eta(current_page, total_pages_to_fetch, start_time) |
| Marc Kupietz | 365660e | 2025-06-25 15:09:55 +0200 | [diff] [blame] | 588 | |
| Marc Kupietz | 24799fd | 2025-06-25 14:15:36 +0200 | [diff] [blame] | 589 | # Extract timing information for display |
| Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 590 | time_per_page <- NA |
| Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 591 | if (!is.null(res$meta$benchmark) && is.character(res$meta$benchmark)) { |
| Marc Kupietz | ae9b617 | 2025-05-02 15:50:01 +0200 | [diff] [blame] | 592 | time_per_page <- suppressWarnings(as.numeric(sub("s", "", res$meta$benchmark))) |
| Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 593 | } |
| 594 | |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 595 | # Create the page display string with proper formatting |
| Marc Kupietz | acbaab0 | 2025-05-01 10:56:35 +0200 | [diff] [blame] | 596 | |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 597 | # For global page tracking, calculate the absolute page number |
| 598 | actual_display_number <- if (randomizePageOrder) { |
| 599 | current_offset_page + 1 # In randomized mode, this is the actual page (0-based + 1) |
| 600 | } else { |
| 601 | # In sequential mode, the absolute page number is the actual offset page + 1 (to make it 1-based) |
| 602 | current_offset_page + 1 |
| 603 | } |
| 604 | |
| 605 | # For subsequent calls to fetchNext, we need to calculate the correct page numbers |
| 606 | # based on the current batch being fetched |
| 607 | |
| 608 | # For each call to fetchNext, we want to show 1/2, 2/2 (not 3/4, 4/4) |
| 609 | # Simply count from 1 within the current batch |
| 610 | |
| 611 | # The relative page number is simply the current position in this batch |
| 612 | if (randomizePageOrder) { |
| 613 | relative_page_number <- page_index # In randomized mode, we start from 1 in each batch |
| 614 | } else { |
| 615 | relative_page_number <- display_page_number - (page_count_start - 1) |
| 616 | } |
| 617 | |
| 618 | # How many pages will we fetch in this batch? |
| Marc Kupietz | 021663d | 2025-06-18 17:49:22 +0200 | [diff] [blame] | 619 | # If maxFetch is specified, calculate the total pages for this fetch operation |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 620 | pages_in_this_batch <- if (!is.na(maxFetch)) { |
| Marc Kupietz | 021663d | 2025-06-18 17:49:22 +0200 | [diff] [blame] | 621 | # Account for offset - we can only fetch from the remaining results after offset |
| 622 | remaining_results_after_offset <- max(0, kqo@totalResults - offset) |
| 623 | min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage)) |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 624 | } else { |
| 625 | # Otherwise fetch all remaining pages |
| 626 | total_pages - page_count_start + 1 |
| 627 | } |
| 628 | |
| 629 | # The total pages to be shown in this batch |
| 630 | batch_total_pages <- pages_in_this_batch |
| 631 | |
| 632 | page_display <- paste0( |
| 633 | "Retrieved page ", |
| 634 | sprintf(paste0("%", nchar(batch_total_pages), "d"), relative_page_number), |
| 635 | "/", |
| 636 | sprintf("%d", batch_total_pages) |
| 637 | ) |
| 638 | |
| 639 | # If randomized, also show which actual page we fetched |
| 640 | if (randomizePageOrder) { |
| 641 | # Determine the maximum width needed for page numbers (based on total pages) |
| 642 | # This ensures consistent alignment |
| 643 | max_page_width <- nchar(as.character(total_pages)) |
| 644 | # Add the actual page number that was fetched (0-based + 1 for display) with proper padding |
| Marc Kupietz | 7638ca4 | 2025-05-25 13:18:16 +0200 | [diff] [blame] | 645 | page_display <- paste0( |
| 646 | page_display, |
| 647 | sprintf(" (actual page %*d)", max_page_width, current_offset_page + 1) |
| 648 | ) |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 649 | } |
| 650 | # Always show the absolute page number and total pages (for clarity) |
| 651 | else { |
| 652 | # Show the absolute page number (out of total possible pages) |
| 653 | page_display <- paste0(page_display, sprintf( |
| 654 | " (page %d of %d total)", |
| 655 | actual_display_number, total_pages |
| 656 | )) |
| 657 | } |
| 658 | |
| 659 | # Add caching or timing information |
| 660 | if (!is.null(res$meta$cached)) { |
| 661 | page_display <- paste0(page_display, " [cached]") |
| 662 | } else { |
| 663 | page_display <- paste0( |
| 664 | page_display, |
| 665 | " in ", |
| 666 | if (!is.na(time_per_page)) sprintf("%4.1f", time_per_page) else "?", |
| Marc Kupietz | 24799fd | 2025-06-25 14:15:36 +0200 | [diff] [blame] | 667 | "s", |
| 668 | eta_info |
| Marc Kupietz | 623d712 | 2025-05-25 12:46:12 +0200 | [diff] [blame] | 669 | ) |
| 670 | } |
| 671 | |
| 672 | log_info(verbose, paste0(page_display, "\n")) |
| 673 | |
| 674 | # Increment the appropriate counter based on mode |
| 675 | if (randomizePageOrder) { |
| 676 | page_index <- page_index + 1 |
| 677 | } else { |
| 678 | current_page_number <- current_page_number + 1 |
| 679 | } |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 680 | results <- results + res$meta$itemsPerPage |
| Marc Kupietz | e8bd49b | 2024-06-28 07:24:44 +0200 | [diff] [blame] | 681 | if (nrow(collectedMatches) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) { |
| Marc Kupietz | 5bbc9db | 2019-08-30 16:30:45 +0200 | [diff] [blame] | 682 | break |
| 683 | } |
| 684 | } |
| Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 685 | nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 686 | KorAPQuery( |
| 687 | nextStartIndex = nextStartIndex, |
| Marc Kupietz | d0d3e9b | 2019-09-24 17:36:03 +0200 | [diff] [blame] | 688 | korapConnection = kqo@korapConnection, |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 689 | fields = kqo@fields, |
| 690 | requestUrl = kqo@requestUrl, |
| 691 | request = kqo@request, |
| Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 692 | totalResults = kqo@totalResults, |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 693 | vc = kqo@vc, |
| 694 | webUIRequestUrl = kqo@webUIRequestUrl, |
| Marc Kupietz | 6817095 | 2021-06-30 09:37:21 +0200 | [diff] [blame] | 695 | hasMoreMatches = (kqo@totalResults > nextStartIndex), |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 696 | apiResponse = res, |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 697 | collectedMatches = collectedMatches |
| 698 | ) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 699 | }) |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 700 | |
| 701 | #' Fetch all results of a KorAP query. |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 702 | #' |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 703 | #' **`fetchAll`** fetches all results of a KorAP query. |
| Marc Kupietz | a6e4ee6 | 2021-03-05 09:00:15 +0100 | [diff] [blame] | 704 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 705 | #' @family corpus search functions |
| Marc Kupietz | dc880ac | 2025-06-24 20:34:43 +0200 | [diff] [blame] | 706 | #' @param kqo object obtained from [corpusQuery()] |
| 707 | #' @param verbose print progress information if true |
| 708 | #' @param ... further arguments passed to [fetchNext()] |
| 709 | #' @return The updated `kqo` object with all results in `@collectedMatches` |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 710 | #' |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 711 | #' @examples |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 712 | #' \dontrun{ |
| Marc Kupietz | ecc8670 | 2025-06-24 12:12:51 +0200 | [diff] [blame] | 713 | #' # Fetch all metadata of every query hit for "Ameisenplage" and show a summary |
| 714 | #' q <- KorAPConnection() |> |
| 715 | #' corpusQuery("Ameisenplage") |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 716 | #' fetchAll() |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 717 | #' q@collectedMatches |
| Marc Kupietz | ecc8670 | 2025-06-24 12:12:51 +0200 | [diff] [blame] | 718 | #' |
| 719 | #' # Fetch also all KWICs |
| 720 | #' q <- KorAPConnection() |> auth() |> |
| 721 | #' corpusQuery("Ameisenplage", metadataOnly = FALSE) |> |
| 722 | #' fetchAll() |
| 723 | #' q@collectedMatches |
| 724 | #' |
| 725 | #' # Retrieve title and text sigle metadata of all texts published on 1958-03-12 |
| 726 | #' q <- KorAPConnection() |> |
| 727 | #' corpusQuery("<base/s=t>", # this matches each text once |
| 728 | #' vc = "pubDate in 1958-03-12", |
| 729 | #' fields = c("textSigle", "title"), |
| 730 | #' ) |> |
| 731 | #' fetchAll() |
| 732 | #' q@collectedMatches |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 733 | #' } |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 734 | #' |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 735 | #' @aliases fetchAll |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 736 | #' @export |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 737 | setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) { |
| 738 | return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...)) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 739 | }) |
| 740 | |
| 741 | #' Fetches the remaining results of a KorAP query. |
| 742 | #' |
| Marc Kupietz | dc880ac | 2025-06-24 20:34:43 +0200 | [diff] [blame] | 743 | #' @param kqo object obtained from [corpusQuery()] |
| 744 | #' @param verbose print progress information if true |
| 745 | #' @param ... further arguments passed to [fetchNext()] |
| 746 | #' @return The updated `kqo` object with remaining results in `@collectedMatches` |
| 747 | #' |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 748 | #' @examples |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 749 | #' \dontrun{ |
| 750 | #' |
| Marc Kupietz | d352642 | 2025-06-25 09:16:15 +0200 | [diff] [blame] | 751 | #' q <- KorAPConnection() |> |
| 752 | #' corpusQuery("Ameisenplage") |> |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 753 | #' fetchRest() |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 754 | #' q@collectedMatches |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 755 | #' } |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 756 | #' |
| 757 | #' @aliases fetchRest |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 758 | #' @export |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 759 | setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) { |
| 760 | return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...)) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 761 | }) |
| 762 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 763 | # Helper to collapse multiple annotation values while preserving order |
| 764 | collapse_features <- function(values) { |
| 765 | if (length(values) == 0) { |
| 766 | return(NA_character_) |
| 767 | } |
| 768 | unique_values <- values[!duplicated(values)] |
| 769 | paste(unique_values, collapse = "|") |
| 770 | } |
| 771 | |
| 772 | # Extract token-level annotations from a DOM node |
| 773 | collect_token_annotations <- function(parent_node) { |
| 774 | if (inherits(parent_node, "xml_missing")) { |
| 775 | return(list( |
| 776 | node = list(), |
| 777 | token = character(0), |
| 778 | lemma = character(0), |
| 779 | pos = character(0), |
| 780 | morph = character(0) |
| 781 | )) |
| 782 | } |
| 783 | |
| 784 | leaf_nodes <- xml2::xml_find_all(parent_node, ".//span[not(.//span)]") |
| 785 | |
| 786 | if (length(leaf_nodes) == 0) { |
| 787 | return(list( |
| 788 | node = list(), |
| 789 | token = character(0), |
| 790 | lemma = character(0), |
| 791 | pos = character(0), |
| 792 | morph = character(0) |
| 793 | )) |
| 794 | } |
| 795 | |
| 796 | tokens <- character(0) |
| 797 | lemmas <- character(0) |
| 798 | pos_tags <- character(0) |
| 799 | morph_tags <- character(0) |
| 800 | kept_nodes <- list() |
| 801 | |
| 802 | for (idx in seq_along(leaf_nodes)) { |
| 803 | leaf <- leaf_nodes[[idx]] |
| 804 | token_text <- trimws(xml2::xml_text(leaf)) |
| 805 | if (identical(token_text, "")) { |
| 806 | next |
| 807 | } |
| 808 | |
| 809 | kept_nodes[[length(kept_nodes) + 1]] <- leaf |
| 810 | tokens <- c(tokens, token_text) |
| 811 | |
| 812 | ancestors <- xml2::xml_find_all(leaf, "ancestor-or-self::span") |
| 813 | titles <- xml2::xml_attr(ancestors, "title") |
| 814 | titles <- titles[!is.na(titles)] |
| 815 | |
| 816 | feature_pieces <- if (length(titles) > 0) unlist(strsplit(titles, "[[:space:]]+")) else character(0) |
| 817 | |
| 818 | lemma_values <- sub('.*?/l:(.*)$', '\\1', feature_pieces[grepl('/l:', feature_pieces)], perl = TRUE) |
| 819 | pos_values <- sub('.*?/p:(.*)$', '\\1', feature_pieces[grepl('/p:', feature_pieces)], perl = TRUE) |
| 820 | morph_values <- sub('.*?/m:(.*)$', '\\1', feature_pieces[grepl('/m:', feature_pieces)], perl = TRUE) |
| 821 | |
| 822 | lemmas <- c(lemmas, collapse_features(lemma_values)) |
| 823 | pos_tags <- c(pos_tags, collapse_features(pos_values)) |
| 824 | morph_tags <- c(morph_tags, collapse_features(morph_values)) |
| 825 | } |
| 826 | |
| 827 | list( |
| 828 | node = kept_nodes, |
| 829 | token = tokens, |
| 830 | lemma = lemmas, |
| 831 | pos = pos_tags, |
| 832 | morph = morph_tags |
| 833 | ) |
| 834 | } |
| 835 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 836 | #' |
| 837 | #' Parse XML annotations into linguistic layers |
| 838 | #' |
| 839 | #' Internal helper function to extract linguistic annotations (lemma, POS, morphology) |
| 840 | #' from XML annotation snippets returned by the KorAP API. |
| 841 | #' |
| 842 | #' @param xml_snippet XML string containing annotation data |
| 843 | #' @return Named list with vectors for 'token', 'lemma', 'pos', and 'morph' |
| 844 | #' @keywords internal |
| 845 | parse_xml_annotations <- function(xml_snippet) { |
| 846 | if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") { |
| 847 | return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0))) |
| 848 | } |
| 849 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 850 | doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL) |
| 851 | if (is.null(doc)) { |
| 852 | return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0))) |
| Marc Kupietz | cd45218 | 2025-10-09 13:28:41 +0200 | [diff] [blame] | 853 | } |
| 854 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 855 | match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]") |
| 856 | if (inherits(match_node, "xml_missing")) { |
| 857 | match_node <- xml2::xml_find_first(doc, ".//span") |
| 858 | if (inherits(match_node, "xml_missing")) { |
| 859 | return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0))) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 860 | } |
| 861 | } |
| 862 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 863 | token_info <- collect_token_annotations(match_node) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 864 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 865 | list( |
| 866 | token = token_info$token, |
| 867 | lemma = token_info$lemma, |
| 868 | pos = token_info$pos, |
| 869 | morph = token_info$morph |
| 870 | ) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 871 | } |
| 872 | |
| 873 | #' |
| 874 | #' Parse XML annotations into linguistic layers with left/match/right structure |
| 875 | #' |
| 876 | #' Internal helper function to extract linguistic annotations (lemma, POS, morphology) |
| 877 | #' from XML annotation snippets returned by the KorAP API, split into left context, |
| 878 | #' match, and right context sections like the tokens field. |
| 879 | #' |
| 880 | #' @param xml_snippet XML string containing annotation data |
| 881 | #' @return Named list with nested structure containing left/match/right for 'atokens', 'lemma', 'pos', and 'morph' |
| 882 | #' @keywords internal |
| 883 | parse_xml_annotations_structured <- function(xml_snippet) { |
| 884 | if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") { |
| 885 | empty_result <- list(left = character(0), match = character(0), right = character(0)) |
| 886 | return(list( |
| 887 | atokens = empty_result, |
| 888 | lemma = empty_result, |
| 889 | pos = empty_result, |
| 890 | morph = empty_result |
| 891 | )) |
| 892 | } |
| 893 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 894 | doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL) |
| 895 | if (is.null(doc)) { |
| 896 | empty_result <- list(left = character(0), match = character(0), right = character(0)) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 897 | return(list( |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 898 | atokens = empty_result, |
| 899 | lemma = empty_result, |
| 900 | pos = empty_result, |
| 901 | morph = empty_result |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 902 | )) |
| 903 | } |
| 904 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 905 | match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]") |
| 906 | if (inherits(match_node, "xml_missing")) { |
| 907 | empty_result <- list(left = character(0), match = character(0), right = character(0)) |
| 908 | return(list( |
| 909 | atokens = empty_result, |
| 910 | lemma = empty_result, |
| 911 | pos = empty_result, |
| 912 | morph = empty_result |
| 913 | )) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 914 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 915 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 916 | token_info <- collect_token_annotations(match_node) |
| 917 | tokens <- token_info$token |
| 918 | lemmas <- token_info$lemma |
| 919 | pos_tags <- token_info$pos |
| 920 | morph_tags <- token_info$morph |
| 921 | nodes <- token_info$node |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 922 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 923 | if (length(tokens) == 0) { |
| 924 | empty_result <- list(left = character(0), match = character(0), right = character(0)) |
| 925 | return(list( |
| 926 | atokens = empty_result, |
| 927 | lemma = empty_result, |
| 928 | pos = empty_result, |
| 929 | morph = empty_result |
| 930 | )) |
| 931 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 932 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 933 | mark_flags <- vapply(nodes, function(n) { |
| 934 | !inherits(xml2::xml_find_first(n, "ancestor::mark"), "xml_missing") |
| 935 | }, logical(1)) |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 936 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 937 | if (any(mark_flags)) { |
| 938 | first_idx <- which(mark_flags)[1] |
| 939 | last_idx <- tail(which(mark_flags), 1) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 940 | } else { |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 941 | first_idx <- 1 |
| 942 | last_idx <- length(tokens) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 943 | } |
| 944 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 945 | sections <- rep("match", length(tokens)) |
| 946 | if (first_idx > 1) { |
| 947 | sections[seq_len(first_idx - 1)] <- "left" |
| 948 | } |
| 949 | if (last_idx < length(tokens)) { |
| 950 | sections[seq(from = last_idx + 1, to = length(tokens))] <- "right" |
| 951 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 952 | |
| Marc Kupietz | bdedd02 | 2025-10-09 14:14:15 +0200 | [diff] [blame] | 953 | subset_by_section <- function(values, section) { |
| 954 | idx <- sections == section |
| 955 | if (!any(idx)) { |
| 956 | return(character(0)) |
| 957 | } |
| 958 | values[idx] |
| 959 | } |
| 960 | |
| 961 | atokens <- list( |
| 962 | left = subset_by_section(tokens, "left"), |
| 963 | match = subset_by_section(tokens, "match"), |
| 964 | right = subset_by_section(tokens, "right") |
| 965 | ) |
| 966 | |
| 967 | lemma <- list( |
| 968 | left = subset_by_section(lemmas, "left"), |
| 969 | match = subset_by_section(lemmas, "match"), |
| 970 | right = subset_by_section(lemmas, "right") |
| 971 | ) |
| 972 | |
| 973 | pos <- list( |
| 974 | left = subset_by_section(pos_tags, "left"), |
| 975 | match = subset_by_section(pos_tags, "match"), |
| 976 | right = subset_by_section(pos_tags, "right") |
| 977 | ) |
| 978 | |
| 979 | morph <- list( |
| 980 | left = subset_by_section(morph_tags, "left"), |
| 981 | match = subset_by_section(morph_tags, "match"), |
| 982 | right = subset_by_section(morph_tags, "right") |
| 983 | ) |
| 984 | |
| 985 | list( |
| 986 | atokens = atokens, |
| 987 | lemma = lemma, |
| 988 | pos = pos, |
| 989 | morph = morph |
| 990 | ) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 991 | } |
| 992 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 993 | #' Fetch annotations for all collected matches |
| 994 | #' |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 995 | #' `r lifecycle::badge("experimental")` |
| 996 | #' |
| 997 | #' **`fetchAnnotations`** fetches annotations (only token annotations, for now) |
| 998 | #' for all matches in the `@collectedMatches` slot |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 999 | #' of a KorAPQuery object and adds annotation columns directly to the `@collectedMatches` |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 1000 | #' data frame. The method uses the `matchID` from collected matches. |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1001 | #' |
| 1002 | #' **Important**: For copyright-restricted corpora, users must be authorized via [auth()] |
| 1003 | #' and the initial corpus query must have `metadataOnly = FALSE` to ensure snippets are |
| 1004 | #' available for annotation parsing. |
| 1005 | #' |
| 1006 | #' The method parses XML snippet annotations and adds linguistic columns to the data frame: |
| 1007 | #' - `pos`: data frame with `left`, `match`, `right` columns, each containing list vectors of part-of-speech tags |
| 1008 | #' - `lemma`: data frame with `left`, `match`, `right` columns, each containing list vectors of lemmas |
| 1009 | #' - `morph`: data frame with `left`, `match`, `right` columns, each containing list vectors of morphological tags |
| 1010 | #' - `atokens`: data frame with `left`, `match`, `right` columns, each containing list vectors of token text (from annotations) |
| 1011 | #' - `annotation_snippet`: original XML snippet from the annotation API |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1012 | #' |
| 1013 | #' @family corpus search functions |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 1014 | #' @concept Annotations |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1015 | #' |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1016 | #' @param kqo object obtained from [corpusQuery()] with collected matches. Note: the original corpus query should have `metadataOnly = FALSE` for annotation parsing to work. |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1017 | #' @param foundry string specifying the foundry to use for annotations (default: "tt" for Tree-Tagger) |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1018 | #' @param overwrite logical; if TRUE, re-fetch and replace any existing |
| 1019 | #' annotation columns. If FALSE (default), only add missing annotation layers |
| 1020 | #' and preserve already fetched ones (e.g., keep POS/lemma from a previous |
| 1021 | #' foundry while adding morph from another). |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1022 | #' @param verbose print progress information if true |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 1023 | #' @return The updated `kqo` object with annotation columns |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 1024 | #' like `pos`, `lemma`, `morph` (and `atokens` and `annotation_snippet`) |
| 1025 | #' in the `@collectedMatches` slot. Each column is a data frame |
| 1026 | #' with `left`, `match`, and `right` columns containing list vectors of annotations |
| 1027 | #' for the left context, matched tokens, and right context, respectively. |
| 1028 | #' The original XML snippet for each match is also stored in `annotation_snippet`. |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1029 | #' |
| 1030 | #' @examples |
| 1031 | #' \dontrun{ |
| 1032 | #' |
| 1033 | #' # Fetch annotations for matches using Tree-Tagger foundry |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1034 | #' # Note: Authorization required for copyright-restricted corpora |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1035 | #' q <- KorAPConnection() |> |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1036 | #' auth() |> |
| 1037 | #' corpusQuery("Ameisenplage", metadataOnly = FALSE) |> |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1038 | #' fetchNext(maxFetch = 10) |> |
| 1039 | #' fetchAnnotations() |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1040 | #' |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1041 | #' # Access linguistic annotations for match i: |
| Marc Kupietz | 6aa5a0d | 2025-09-08 17:51:47 +0200 | [diff] [blame] | 1042 | #' pos_tags <- q@collectedMatches$pos |
| 1043 | #' # Data frame with left/match/right columns for POS tags |
| 1044 | #' lemmas <- q@collectedMatches$lemma |
| 1045 | #' # Data frame with left/match/right columns for lemmas |
| 1046 | #' morphology <- q@collectedMatches$morph |
| 1047 | #' # Data frame with left/match/right columns for morphological tags |
| 1048 | #' atokens <- q@collectedMatches$atokens |
| 1049 | #' # Data frame with left/match/right columns for annotation token text |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 1050 | #' # Original XML snippet for match i |
| 1051 | #' raw_snippet <- q@collectedMatches$annotation_snippet[[i]] |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1052 | #' |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1053 | #' # Access specific components: |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 1054 | #' # POS tags for the matched tokens in match i |
| 1055 | #' match_pos <- q@collectedMatches$pos$match[[i]] |
| 1056 | #' # Lemmas for the left context in match i |
| 1057 | #' left_lemmas <- q@collectedMatches$lemma$left[[i]] |
| 1058 | #' # Token text for the right context in match i |
| 1059 | #' right_tokens <- q@collectedMatches$atokens$right[[i]] |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1060 | #' |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 1061 | #' # Use a different foundry (e.g., MarMoT) |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1062 | #' q <- KorAPConnection() |> |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1063 | #' auth() |> |
| 1064 | #' corpusQuery("Ameisenplage", metadataOnly = FALSE) |> |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1065 | #' fetchNext(maxFetch = 10) |> |
| Marc Kupietz | 89f796e | 2025-07-19 09:05:06 +0200 | [diff] [blame] | 1066 | #' fetchAnnotations(foundry = "marmot") |
| 1067 | #' q@collectedMatches$pos$left[1] # POS tags for the left context of the first match |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1068 | #' } |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1069 | #' @export |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 1070 | setMethod("fetchAnnotations", "KorAPQuery", function(kqo, |
| 1071 | foundry = "tt", |
| 1072 | overwrite = FALSE, |
| 1073 | verbose = kqo@korapConnection@verbose) { |
| 1074 | if (is.null(kqo@collectedMatches) || |
| 1075 | nrow(kqo@collectedMatches) == 0) { |
| 1076 | warning("No collected matches found. Please run fetchNext() or fetchAll() first.") |
| 1077 | return(kqo) |
| 1078 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1079 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1080 | df <- kqo@collectedMatches |
| 1081 | kco <- kqo@korapConnection |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1082 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1083 | # Initialize annotation columns as data frames (like tokens field) |
| 1084 | # Create the structure more explicitly to avoid assignment issues |
| 1085 | nrows <- nrow(df) |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1086 | |
| Marc Kupietz | 03d2b1a | 2025-07-19 09:14:45 +0200 | [diff] [blame] | 1087 | # Pre-compute the empty character vector list to avoid repeated computation |
| 1088 | empty_char_list <- I(replicate(nrows, character(0), simplify = FALSE)) |
| Marc Kupietz | 0af7593 | 2025-09-09 18:14:16 +0200 | [diff] [blame] | 1089 | |
| Marc Kupietz | 03d2b1a | 2025-07-19 09:14:45 +0200 | [diff] [blame] | 1090 | # Helper function to create annotation data frame structure |
| 1091 | create_annotation_df <- function(empty_list) { |
| 1092 | data.frame( |
| 1093 | left = empty_list, |
| 1094 | match = empty_list, |
| 1095 | right = empty_list, |
| 1096 | stringsAsFactors = FALSE |
| 1097 | ) |
| 1098 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1099 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1100 | # Track which annotation columns already existed to decide overwrite behavior |
| 1101 | existing_types <- list( |
| 1102 | pos = "pos" %in% colnames(df), |
| 1103 | lemma = "lemma" %in% colnames(df), |
| 1104 | morph = "morph" %in% colnames(df), |
| 1105 | atokens = "atokens" %in% colnames(df), |
| 1106 | annotation_snippet = "annotation_snippet" %in% colnames(df) |
| 1107 | ) |
| 1108 | |
| 1109 | # Initialize annotation columns using the helper function |
| Marc Kupietz | 03d2b1a | 2025-07-19 09:14:45 +0200 | [diff] [blame] | 1110 | annotation_types <- c("pos", "lemma", "morph", "atokens") |
| 1111 | for (type in annotation_types) { |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1112 | if (overwrite || !existing_types[[type]]) { |
| 1113 | df[[type]] <- create_annotation_df(empty_char_list) |
| 1114 | } |
| Marc Kupietz | 03d2b1a | 2025-07-19 09:14:45 +0200 | [diff] [blame] | 1115 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1116 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1117 | if (overwrite || !existing_types$annotation_snippet) { |
| feldmueller | a02f193 | 2025-09-15 16:38:06 +0200 | [diff] [blame] | 1118 | df$annotation_snippet <- rep(NA_character_, nrows) # Fixed line |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1119 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1120 | |
| Marc Kupietz | e8c0fef | 2025-07-18 19:59:04 +0200 | [diff] [blame] | 1121 | # Initialize timing for ETA calculation |
| 1122 | start_time <- Sys.time() |
| 1123 | if (verbose) { |
| 1124 | log_info(verbose, paste("Starting to fetch annotations for", nrows, "matches\n")) |
| 1125 | } |
| 1126 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1127 | # Helper to decide if existing annotation row is effectively empty |
| 1128 | is_empty_annotation_row <- function(ann_df, row_index) { |
| 1129 | if (is.null(ann_df) || nrow(ann_df) < row_index) return(TRUE) |
| 1130 | left_val <- ann_df$left[[row_index]] |
| 1131 | match_val <- ann_df$match[[row_index]] |
| 1132 | right_val <- ann_df$right[[row_index]] |
| 1133 | all( |
| 1134 | (is.null(left_val) || (length(left_val) == 0) || all(is.na(left_val))), |
| 1135 | (is.null(match_val) || (length(match_val) == 0) || all(is.na(match_val))), |
| 1136 | (is.null(right_val) || (length(right_val) == 0) || all(is.na(right_val))) |
| 1137 | ) |
| 1138 | } |
| 1139 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1140 | for (i in seq_len(nrow(df))) { |
| Marc Kupietz | e8c0fef | 2025-07-18 19:59:04 +0200 | [diff] [blame] | 1141 | # ETA logging |
| 1142 | if (verbose && i > 1) { |
| 1143 | eta_info <- calculate_eta(i, nrows, start_time) |
| 1144 | log_info(verbose, paste("Fetching annotations for match", i, "of", nrows, eta_info, "\n")) |
| 1145 | } |
| Marc Kupietz | ff712a9 | 2025-07-18 09:07:23 +0200 | [diff] [blame] | 1146 | # Use matchID if available, otherwise fall back to constructing from matchStart/matchEnd |
| 1147 | if ("matchID" %in% colnames(df) && !is.na(df$matchID[i])) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1148 | # matchID format: "match-match-A00/JUN/39609-p202-203" or encrypted format like |
| 1149 | # "match-DNB10/CSL/80400-p2343-2344x_MinDOhu_P6dd2MMZJyyus_7MairdKnr1LxY07Cya-Ow" |
| 1150 | # Extract document path and position, handling both regular and encrypted formats |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1151 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1152 | # More flexible regex to extract the document path with position and encryption |
| 1153 | # Look for pattern: match-(...)-p(\d+)-(\d+)(.*) where (.*) is the encrypted part |
| 1154 | # We need to capture the entire path including the encrypted suffix |
| 1155 | match_result <- regexpr("match-(.+?-p\\d+-\\d+.*)", df$matchID[i], perl = TRUE) |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1156 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1157 | if (match_result > 0) { |
| 1158 | # Extract the complete path including encryption (everything after "match-") |
| 1159 | doc_path_with_pos_and_encryption <- gsub("^match-(.+)$", "\\1", df$matchID[i], perl = TRUE) |
| 1160 | # Convert the dash before position to slash, but keep everything after the position |
| 1161 | match_path <- gsub("-p(\\d+-\\d+.*)", "/p\\1", doc_path_with_pos_and_encryption) |
| Marc Kupietz | 2512130 | 2025-07-19 08:45:43 +0200 | [diff] [blame] | 1162 | # Use httr2 to construct URL safely |
| 1163 | base_url <- paste0(kco@apiUrl, "corpus/", match_path) |
| 1164 | req <- httr2::url_modify(base_url, query = list(foundry = foundry)) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1165 | } else { |
| Marc Kupietz | 2512130 | 2025-07-19 08:45:43 +0200 | [diff] [blame] | 1166 | # If regex fails, fall back to the old method with httr2 |
| 1167 | # Format numbers to avoid scientific notation |
| 1168 | match_start <- format(df$matchStart[i], scientific = FALSE) |
| 1169 | match_end <- format(df$matchEnd[i], scientific = FALSE) |
| 1170 | base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end) |
| 1171 | req <- httr2::url_modify(base_url, query = list(foundry = foundry)) |
| Marc Kupietz | ff712a9 | 2025-07-18 09:07:23 +0200 | [diff] [blame] | 1172 | } |
| 1173 | } else { |
| Marc Kupietz | 2512130 | 2025-07-19 08:45:43 +0200 | [diff] [blame] | 1174 | # Fallback to the old method with httr2 |
| 1175 | # Format numbers to avoid scientific notation |
| 1176 | match_start <- format(df$matchStart[i], scientific = FALSE) |
| 1177 | match_end <- format(df$matchEnd[i], scientific = FALSE) |
| 1178 | base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end) |
| 1179 | req <- httr2::url_modify(base_url, query = list(foundry = foundry)) |
| Marc Kupietz | ff712a9 | 2025-07-18 09:07:23 +0200 | [diff] [blame] | 1180 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1181 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1182 | tryCatch({ |
| 1183 | res <- apiCall(kco, req) |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1184 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1185 | if (!is.null(res)) { |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1186 | # Store the raw annotation snippet (respect overwrite flag) |
| 1187 | if (overwrite || !existing_types$annotation_snippet || is.null(df$annotation_snippet[[i]]) || is.na(df$annotation_snippet[[i]])) { |
| 1188 | df$annotation_snippet[[i]] <- if (is.list(res) && "snippet" %in% names(res)) res$snippet else NA |
| 1189 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1190 | |
| 1191 | # Parse XML annotations if snippet is available |
| 1192 | if (is.list(res) && "snippet" %in% names(res)) { |
| 1193 | parsed_annotations <- parse_xml_annotations_structured(res$snippet) |
| 1194 | |
| 1195 | # Store the parsed linguistic data in data frame format (like tokens) |
| 1196 | # Use individual assignment to avoid data frame mismatch errors |
| 1197 | tryCatch({ |
| 1198 | # Assign POS annotations |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1199 | if (overwrite || !existing_types$pos || is_empty_annotation_row(df$pos, i)) { |
| 1200 | df$pos$left[i] <- list(parsed_annotations$pos$left) |
| 1201 | df$pos$match[i] <- list(parsed_annotations$pos$match) |
| 1202 | df$pos$right[i] <- list(parsed_annotations$pos$right) |
| 1203 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1204 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1205 | # Assign lemma annotations |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1206 | if (overwrite || !existing_types$lemma || is_empty_annotation_row(df$lemma, i)) { |
| 1207 | df$lemma$left[i] <- list(parsed_annotations$lemma$left) |
| 1208 | df$lemma$match[i] <- list(parsed_annotations$lemma$match) |
| 1209 | df$lemma$right[i] <- list(parsed_annotations$lemma$right) |
| 1210 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1211 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1212 | # Assign morphology annotations |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1213 | if (overwrite || !existing_types$morph || is_empty_annotation_row(df$morph, i)) { |
| 1214 | df$morph$left[i] <- list(parsed_annotations$morph$left) |
| 1215 | df$morph$match[i] <- list(parsed_annotations$morph$match) |
| 1216 | df$morph$right[i] <- list(parsed_annotations$morph$right) |
| 1217 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1218 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1219 | # Assign token annotations |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1220 | if (overwrite || !existing_types$atokens || is_empty_annotation_row(df$atokens, i)) { |
| 1221 | df$atokens$left[i] <- list(parsed_annotations$atokens$left) |
| 1222 | df$atokens$match[i] <- list(parsed_annotations$atokens$match) |
| 1223 | df$atokens$right[i] <- list(parsed_annotations$atokens$right) |
| 1224 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1225 | }, error = function(assign_error) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1226 | # Set empty character vectors on assignment error using list assignment |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1227 | if (overwrite || !existing_types$pos) { |
| 1228 | df$pos$left[i] <<- list(character(0)) |
| 1229 | df$pos$match[i] <<- list(character(0)) |
| 1230 | df$pos$right[i] <<- list(character(0)) |
| 1231 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1232 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1233 | if (overwrite || !existing_types$lemma) { |
| 1234 | df$lemma$left[i] <<- list(character(0)) |
| 1235 | df$lemma$match[i] <<- list(character(0)) |
| 1236 | df$lemma$right[i] <<- list(character(0)) |
| 1237 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1238 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1239 | if (overwrite || !existing_types$morph) { |
| 1240 | df$morph$left[i] <<- list(character(0)) |
| 1241 | df$morph$match[i] <<- list(character(0)) |
| 1242 | df$morph$right[i] <<- list(character(0)) |
| 1243 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1244 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1245 | if (overwrite || !existing_types$atokens) { |
| 1246 | df$atokens$left[i] <<- list(character(0)) |
| 1247 | df$atokens$match[i] <<- list(character(0)) |
| 1248 | df$atokens$right[i] <<- list(character(0)) |
| 1249 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1250 | }) |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1251 | } else { |
| 1252 | # No snippet available, store empty vectors |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1253 | if (overwrite || !existing_types$pos) { |
| 1254 | df$pos$left[i] <- list(character(0)) |
| 1255 | df$pos$match[i] <- list(character(0)) |
| 1256 | df$pos$right[i] <- list(character(0)) |
| 1257 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1258 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1259 | if (overwrite || !existing_types$lemma) { |
| 1260 | df$lemma$left[i] <- list(character(0)) |
| 1261 | df$lemma$match[i] <- list(character(0)) |
| 1262 | df$lemma$right[i] <- list(character(0)) |
| 1263 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1264 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1265 | if (overwrite || !existing_types$morph) { |
| 1266 | df$morph$left[i] <- list(character(0)) |
| 1267 | df$morph$match[i] <- list(character(0)) |
| 1268 | df$morph$right[i] <- list(character(0)) |
| 1269 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1270 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1271 | if (overwrite || !existing_types$atokens) { |
| 1272 | df$atokens$left[i] <- list(character(0)) |
| 1273 | df$atokens$match[i] <- list(character(0)) |
| 1274 | df$atokens$right[i] <- list(character(0)) |
| 1275 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1276 | } |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1277 | } else { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1278 | # Store NAs for failed requests |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1279 | if (overwrite || !existing_types$pos) { |
| 1280 | df$pos$left[i] <- list(NA) |
| 1281 | df$pos$match[i] <- list(NA) |
| 1282 | df$pos$right[i] <- list(NA) |
| 1283 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1284 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1285 | if (overwrite || !existing_types$lemma) { |
| 1286 | df$lemma$left[i] <- list(NA) |
| 1287 | df$lemma$match[i] <- list(NA) |
| 1288 | df$lemma$right[i] <- list(NA) |
| 1289 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1290 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1291 | if (overwrite || !existing_types$morph) { |
| 1292 | df$morph$left[i] <- list(NA) |
| 1293 | df$morph$match[i] <- list(NA) |
| 1294 | df$morph$right[i] <- list(NA) |
| 1295 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1296 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1297 | if (overwrite || !existing_types$atokens) { |
| 1298 | df$atokens$left[i] <- list(NA) |
| 1299 | df$atokens$match[i] <- list(NA) |
| 1300 | df$atokens$right[i] <- list(NA) |
| 1301 | } |
| 1302 | if (overwrite || !existing_types$annotation_snippet) { |
| 1303 | df$annotation_snippet[[i]] <- NA |
| 1304 | } |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1305 | } |
| 1306 | }, error = function(e) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1307 | # Store NAs for failed requests |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1308 | if (overwrite || !existing_types$pos) { |
| 1309 | df$pos$left[i] <- list(NA) |
| 1310 | df$pos$match[i] <- list(NA) |
| 1311 | df$pos$right[i] <- list(NA) |
| 1312 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1313 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1314 | if (overwrite || !existing_types$lemma) { |
| 1315 | df$lemma$left[i] <- list(NA) |
| 1316 | df$lemma$match[i] <- list(NA) |
| 1317 | df$lemma$right[i] <- list(NA) |
| 1318 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1319 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1320 | if (overwrite || !existing_types$morph) { |
| 1321 | df$morph$left[i] <- list(NA) |
| 1322 | df$morph$match[i] <- list(NA) |
| 1323 | df$morph$right[i] <- list(NA) |
| 1324 | } |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1325 | |
| Marc Kupietz | 93787d5 | 2025-09-03 13:33:25 +0200 | [diff] [blame] | 1326 | if (overwrite || !existing_types$atokens) { |
| 1327 | df$atokens$left[i] <- list(NA) |
| 1328 | df$atokens$match[i] <- list(NA) |
| 1329 | df$atokens$right[i] <- list(NA) |
| 1330 | } |
| 1331 | if (overwrite || !existing_types$annotation_snippet) { |
| 1332 | df$annotation_snippet[[i]] <- NA |
| 1333 | } |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1334 | }) |
| 1335 | } |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1336 | |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1337 | # Validate data frame structure before assignment |
| 1338 | if (nrow(df) != nrow(kqo@collectedMatches)) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1339 | } |
| 1340 | |
| 1341 | # Update the collectedMatches with annotation data |
| 1342 | tryCatch({ |
| 1343 | kqo@collectedMatches <- df |
| 1344 | }, error = function(assign_error) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1345 | # Try a safer approach: add columns individually |
| 1346 | tryCatch({ |
| 1347 | kqo@collectedMatches$pos <- df$pos |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1348 | kqo@collectedMatches$lemma <- df$lemma |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1349 | kqo@collectedMatches$morph <- df$morph |
| 1350 | kqo@collectedMatches$atokens <- df$atokens |
| 1351 | kqo@collectedMatches$annotation_snippet <- df$annotation_snippet |
| 1352 | }, error = function(col_error) { |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1353 | warning("Failed to add annotation data to collectedMatches") |
| 1354 | }) |
| 1355 | }) |
| 1356 | |
| Marc Kupietz | e8c0fef | 2025-07-18 19:59:04 +0200 | [diff] [blame] | 1357 | if (verbose) { |
| 1358 | elapsed_time <- Sys.time() - start_time |
| 1359 | log_info(verbose, paste("Finished fetching annotations for", nrows, "matches in", format_duration(as.numeric(elapsed_time, units = "secs")), "\n")) |
| 1360 | } |
| 1361 | |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1362 | return(kqo) |
| 1363 | }) |
| 1364 | |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1365 | #' Query frequencies of search expressions in virtual corpora |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1366 | #' |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 1367 | #' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1368 | #' [ci()] to compute a tibble with the absolute and relative frequencies and |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1369 | #' confidence intervals of one ore multiple search terms across one or multiple |
| 1370 | #' virtual corpora. |
| 1371 | #' |
| Marc Kupietz | a8c40f4 | 2025-06-24 15:49:52 +0200 | [diff] [blame] | 1372 | #' @family frequency analysis |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1373 | #' @aliases frequencyQuery |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1374 | #' @examples |
| Marc Kupietz | 6ae7605 | 2021-09-21 10:34:00 +0200 | [diff] [blame] | 1375 | #' \dontrun{ |
| 1376 | #' |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1377 | #' KorAPConnection(verbose = TRUE) |> |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1378 | #' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003)) |
| Marc Kupietz | 05b2277 | 2020-02-18 21:58:42 +0100 | [diff] [blame] | 1379 | #' } |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1380 | #' |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1381 | # @inheritParams corpusQuery |
| Marc Kupietz | 617266d | 2025-02-27 10:43:07 +0100 | [diff] [blame] | 1382 | #' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()` |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1383 | #' @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`. |
| 1384 | #' @param vc virtual corpus definition(s) (can be a vector) |
| Marc Kupietz | 67edcb5 | 2021-09-20 21:54:24 +0200 | [diff] [blame] | 1385 | #' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]). |
| 1386 | #' @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 | a3a8cd9 | 2026-09-08 07:59:04 +0200 | [diff] [blame] | 1387 | #' @param cacheAs path to an RDS file to keep the result in. If the file exists and records the same call, it is read back instead of contacting the server; otherwise the query is run and its result stored there. Unlike the connection's `cache`, this file belongs to the caller, which is what keeps an analysis reproducible once the corpus has grown or the scores have changed. Defaults to \code{NULL} (no file). |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1388 | #' @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] | 1389 | #' @export |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1390 | #' |
| 1391 | #' @return A tibble, with each row containing the following result columns for query and vc combinations: |
| 1392 | #' - **query**: the query string used for the frequency analysis. |
| 1393 | #' - **totalResults**: absolute frequency of query matches in the vc. |
| 1394 | #' - **vc**: virtual corpus used for the query. |
| Marc Kupietz | 10eff99 | 2026-09-14 08:31:41 +0200 | [diff] [blame] | 1395 | #' - **queryDuration**: client-side duration of the request in seconds. |
| Marc Kupietz | ad8d2ed | 2025-04-05 15:37:38 +0200 | [diff] [blame] | 1396 | #' - **webUIRequestUrl**: URL of the corresponding web UI request with respect to query and vc. |
| 1397 | #' - **total**: total number of words in vc. |
| 1398 | #' - **f**: relative frequency of query matches in the vc. |
| 1399 | #' - **conf.low**: lower bound of the confidence interval for the relative frequency, given `conf.level`. |
| 1400 | #' - **conf.high**: upper bound of the confidence interval for the relative frequency, given `conf.level`. |
| 1401 | |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1402 | setMethod( |
| 1403 | "frequencyQuery", "KorAPConnection", |
| Marc Kupietz | a3a8cd9 | 2026-09-08 07:59:04 +0200 | [diff] [blame] | 1404 | function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE, |
| 1405 | cacheAs = NULL, ...) { |
| 1406 | cacheRecord <- NULL |
| 1407 | if (!is.null(cacheAs)) { |
| 1408 | cacheAs <- cacheAsFileName(cacheAs) |
| 1409 | cacheRecord <- cacheAsRecord(environment(), list(...), kco) |
| 1410 | cached <- readCacheAs(cacheAs, kco, cacheRecord, "frequency query") |
| 1411 | if (!is.null(cached)) { |
| 1412 | return(cached) |
| 1413 | } |
| 1414 | } |
| 1415 | |
| 1416 | result <- (if (as.alternatives) { |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1417 | corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |> |
| Marc Kupietz | ea34b81 | 2025-06-25 15:49:00 +0200 | [diff] [blame] | 1418 | group_by(vc) |> |
| Marc Kupietz | 71d6e05 | 2019-11-22 18:42:10 +0100 | [diff] [blame] | 1419 | mutate(total = sum(totalResults)) |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1420 | } else { |
| 1421 | corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |> |
| 1422 | mutate(total = corpusStats(kco, vc = vc, as.df = TRUE)$tokens) |
| Marc Kupietz | ea34b81 | 2025-06-25 15:49:00 +0200 | [diff] [blame] | 1423 | }) |> |
| Marc Kupietz | 0c29cea | 2019-10-09 08:44:36 +0200 | [diff] [blame] | 1424 | ci(conf.level = conf.level) |
| Marc Kupietz | a3a8cd9 | 2026-09-08 07:59:04 +0200 | [diff] [blame] | 1425 | |
| 1426 | if (!is.null(cacheAs)) { |
| 1427 | writeCacheAs(cacheAs, kco, cacheRecord, "frequency query", result) |
| 1428 | } |
| 1429 | result |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1430 | } |
| 1431 | ) |
| Marc Kupietz | 3f57528 | 2019-10-04 14:46:04 +0200 | [diff] [blame] | 1432 | |
| Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 1433 | #' buildWebUIRequestUrlFromString |
| 1434 | #' |
| 1435 | #' @rdname KorAPQuery-class |
| 1436 | #' @importFrom urltools url_encode |
| 1437 | #' @export |
| 1438 | buildWebUIRequestUrlFromString <- function(KorAPUrl, |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1439 | query, |
| 1440 | vc = "", |
| 1441 | ql = "poliqarp") { |
| Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 1442 | if ("KorAPConnection" %in% class(KorAPUrl)) { |
| 1443 | KorAPUrl <- KorAPUrl@KorAPUrl |
| 1444 | } |
| 1445 | |
| 1446 | request <- |
| 1447 | paste0( |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1448 | "?q=", |
| Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 1449 | urltools::url_encode(enc2utf8(as.character(query))), |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1450 | ifelse(vc != "", |
| 1451 | paste0("&cq=", urltools::url_encode(enc2utf8(vc))), |
| 1452 | "" |
| 1453 | ), |
| 1454 | "&ql=", |
| Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 1455 | ql |
| 1456 | ) |
| 1457 | paste0(KorAPUrl, request) |
| 1458 | } |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 1459 | |
| 1460 | #' buildWebUIRequestUrl |
| 1461 | #' |
| 1462 | #' @rdname KorAPQuery-class |
| Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 1463 | #' @importFrom httr2 url_parse |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 1464 | #' @export |
| 1465 | buildWebUIRequestUrl <- function(kco, |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1466 | query = if (missing(KorAPUrl)) { |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 1467 | 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] | 1468 | } else { |
| 1469 | httr2::url_parse(KorAPUrl)$query$q |
| 1470 | }, |
| Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 1471 | vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq, |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 1472 | KorAPUrl, |
| Marc Kupietz | f912959 | 2025-01-26 19:17:54 +0100 | [diff] [blame] | 1473 | ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql) { |
| Marc Kupietz | 38a9d68 | 2024-12-06 16:17:09 +0100 | [diff] [blame] | 1474 | buildWebUIRequestUrlFromString(kco@KorAPUrl, query, vc, ql) |
| Marc Kupietz | dbd431a | 2021-08-29 12:17:45 +0200 | [diff] [blame] | 1475 | } |
| 1476 | |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1477 | #' format() |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1478 | #' @rdname KorAPQuery-class |
| 1479 | #' @param x KorAPQuery object |
| 1480 | #' @param ... further arguments passed to or from other methods |
| Marc Kupietz | b73ca0f | 2025-01-28 20:45:01 +0100 | [diff] [blame] | 1481 | #' @importFrom urltools param_get url_decode |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1482 | #' @export |
| 1483 | format.KorAPQuery <- function(x, ...) { |
| 1484 | cat("<KorAPQuery>\n") |
| 1485 | q <- x |
| Marc Kupietz | d885122 | 2025-05-01 10:57:19 +0200 | [diff] [blame] | 1486 | param <- urltools::param_get(q@request) |> lapply(urltools::url_decode) |
| Marc Kupietz | b73ca0f | 2025-01-28 20:45:01 +0100 | [diff] [blame] | 1487 | cat(" Query: ", param$q, "\n") |
| 1488 | if (!is.null(param$cq) && param$cq != "") { |
| 1489 | cat(" Virtual corpus: ", param$cq, "\n") |
| 1490 | } |
| 1491 | if (!is.null(q@collectedMatches)) { |
| 1492 | cat("==============================================================================================================", "\n") |
| 1493 | print(summary(q@collectedMatches)) |
| 1494 | cat("==============================================================================================================", "\n") |
| 1495 | } |
| 1496 | cat(" Total results: ", q@totalResults, "\n") |
| 1497 | cat(" Fetched results: ", q@nextStartIndex, "\n") |
| Marc Kupietz | a29f3d4 | 2025-07-18 10:14:43 +0200 | [diff] [blame] | 1498 | if (!is.null(q@collectedMatches) && "pos" %in% colnames(q@collectedMatches)) { |
| 1499 | successful_annotations <- sum(!is.na(q@collectedMatches$annotation_snippet)) |
| 1500 | parsed_annotations <- sum(!is.na(q@collectedMatches$pos)) |
| 1501 | cat(" Annotations: ", successful_annotations, " of ", nrow(q@collectedMatches), " matches") |
| 1502 | if (parsed_annotations > 0) { |
| 1503 | cat(" (", parsed_annotations, " with parsed linguistic data)") |
| 1504 | } |
| 1505 | cat("\n") |
| Marc Kupietz | e52b295 | 2025-07-17 16:53:02 +0200 | [diff] [blame] | 1506 | } |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 1507 | } |
| 1508 | |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1509 | #' show() |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 1510 | #' |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1511 | #' @rdname KorAPQuery-class |
| 1512 | #' @param object KorAPQuery object |
| Marc Kupietz | 62da2b5 | 2019-09-12 17:43:34 +0200 | [diff] [blame] | 1513 | #' @export |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1514 | setMethod("show", "KorAPQuery", function(object) { |
| 1515 | format(object) |
| Marc Kupietz | c643a12 | 2025-07-18 18:18:36 +0200 | [diff] [blame] | 1516 | invisible(object) |
| Marc Kupietz | e95108e | 2019-09-18 13:23:58 +0200 | [diff] [blame] | 1517 | }) |