Spaces:
Sleeping
Sleeping
Download R/fields.R from fmegahed/structured_text_extraction: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/fmegahed/structured_text_extraction/resolve/main/R/fields.R
- Command line
-
hf download hf://spaces/fmegahed/structured_text_extraction/R/fields.R
-
curl -L -o fields.R https://huggingface.co/spaces/fmegahed/structured_text_extraction/resolve/main/R/fields.R
11.2 kB
| # Field definitions: creation, validation, sanitizing, JSON import/export, | |
| # templates, and conversion to an ellmer type. | |
| # | |
| # A field is a list with three character elements: | |
| # label column name in the results (and property name in the schema) | |
| # description instruction the model receives for the field | |
| # type one of names(FIELD_TYPES) | |
| # Field types offered in the UI (value = label shown to the user) | |
| FIELD_TYPES = c( | |
| text = "Text", | |
| number = "Number", | |
| yes_no = "Yes / No", | |
| list = "List of text" | |
| ) | |
| # Name used inside saved field-definition files | |
| FIELDS_FILE_FORMAT = "structured_text_extraction_fields" | |
| new_field = function(label = "", description = "", type = "text") { | |
| list( | |
| label = as.character(label), | |
| description = as.character(description), | |
| type = as.character(type) | |
| ) | |
| } | |
| # First "field_<k>" label that is not already used | |
| next_default_label = function(existing_labels) { | |
| k = 1 | |
| while (paste0("field_", k) %in% existing_labels) k = k + 1 | |
| paste0("field_", k) | |
| } | |
| # Grow or shrink a list of fields to n entries, keeping the existing entries | |
| resize_fields = function(fields, n) { | |
| n = as.integer(n) | |
| if (is.na(n) || n < 1) return(fields) | |
| if (length(fields) > n) return(fields[seq_len(n)]) | |
| while (length(fields) < n) { | |
| labels = vapply(fields, function(f) f$label, character(1)) | |
| # Prefer the label that matches the field's position | |
| label = paste0("field_", length(fields) + 1) | |
| if (label %in% labels) label = next_default_label(labels) | |
| fields[[length(fields) + 1]] = new_field(label) | |
| } | |
| fields | |
| } | |
| # Bring a user-supplied number of fields into the allowed range. | |
| # Returns NA when the value is not a usable number. | |
| clamp_num_fields = function(n, max_fields = MAX_FIELDS) { | |
| n = suppressWarnings(as.numeric(n)) | |
| if (length(n) != 1 || is.na(n)) return(NA_integer_) | |
| as.integer(min(max(round(n), 1), max_fields)) | |
| } | |
| # Ids of the three inputs of field i. The generation number changes every | |
| # time the app rebuilds the field inputs, so values typed into an earlier set | |
| # of inputs can never overwrite a newly loaded template or file. | |
| field_input_ids = function(gen, i) { | |
| list( | |
| label = paste0("field_label_", gen, "_", i), | |
| description = paste0("field_desc_", gen, "_", i), | |
| type = paste0("field_type_", gen, "_", i) | |
| ) | |
| } | |
| # Overlay what the user has typed on the stored field definitions. | |
| # get_input is a function(id) returning the input value or NULL. | |
| merge_field_inputs = function(fields, get_input, gen = 0) { | |
| lapply(seq_along(fields), function(i) { | |
| ids = field_input_ids(gen, i) | |
| field = fields[[i]] | |
| for (part in names(ids)) { | |
| value = get_input(ids[[part]]) | |
| if (!is.null(value) && length(value) == 1 && !is.na(value)) { | |
| field[[part]] = as.character(value) | |
| } | |
| } | |
| field | |
| }) | |
| } | |
| # Make a label safe to use as a JSON property name and a column name: | |
| # letters, digits and underscores only, not starting with a digit. | |
| sanitize_label = function(label, max_chars = MAX_LABEL_CHARS) { | |
| label = trimws(as.character(label)) | |
| label = gsub("[^A-Za-z0-9_]+", "_", label) | |
| label = gsub("^_+|_+$", "", label) | |
| if (nchar(label) > 0 && grepl("^[0-9]", label)) label = paste0("field_", label) | |
| substr(label, 1, max_chars) | |
| } | |
| # Check a list of fields. Returns | |
| # ok TRUE when the fields can be used for an extraction | |
| # errors problems that block the extraction | |
| # notes things the user should know that do not block it | |
| # fields the fields with sanitized labels and trimmed descriptions | |
| validate_fields = function(fields, max_fields = MAX_FIELDS, reserved = RESERVED_LABELS) { | |
| errors = character(0) | |
| notes = character(0) | |
| if (!is.list(fields) || length(fields) == 0) { | |
| return(list(ok = FALSE, errors = "Define at least one field.", notes = notes, fields = list())) | |
| } | |
| if (length(fields) > max_fields) { | |
| errors = c(errors, sprintf( | |
| "You defined %d fields. The maximum is %d.", length(fields), max_fields | |
| )) | |
| } | |
| clean = list() | |
| for (i in seq_along(fields)) { | |
| field = fields[[i]] | |
| raw_label = if (is.null(field$label)) "" else trimws(as.character(field$label)[1]) | |
| if (is.na(raw_label)) raw_label = "" | |
| description = if (is.null(field$description)) "" else trimws(as.character(field$description)[1]) | |
| if (is.na(description)) description = "" | |
| type = if (is.null(field$type)) "text" else as.character(field$type)[1] | |
| if (nchar(raw_label) == 0) { | |
| errors = c(errors, sprintf("Field %d has no label.", i)) | |
| next | |
| } | |
| label = sanitize_label(raw_label) | |
| if (nchar(label) == 0) { | |
| errors = c(errors, sprintf( | |
| "The label of field %d ('%s') has no letters or digits.", i, raw_label | |
| )) | |
| next | |
| } | |
| if (label != raw_label) { | |
| notes = c(notes, sprintf( | |
| "The label of field %d ('%s') was changed to '%s' (letters, digits and underscores only).", | |
| i, raw_label, label | |
| )) | |
| } | |
| if (tolower(label) %in% tolower(reserved)) { | |
| errors = c(errors, sprintf( | |
| "The label '%s' (field %d) is used by the app for its own column. Choose another label.", | |
| label, i | |
| )) | |
| } | |
| if (is.na(type) || !(type %in% names(FIELD_TYPES))) { | |
| errors = c(errors, sprintf( | |
| "Field %d has an unknown type ('%s'). Allowed types: %s.", | |
| i, type, paste(names(FIELD_TYPES), collapse = ", ") | |
| )) | |
| type = "text" | |
| } | |
| if (nchar(description) == 0) { | |
| notes = c(notes, sprintf( | |
| "Field %d ('%s') has no description, so the model only sees its label.", i, label | |
| )) | |
| } | |
| clean[[length(clean) + 1]] = new_field(label, description, type) | |
| } | |
| labels = tolower(vapply(clean, function(f) f$label, character(1))) | |
| duplicated_labels = unique(labels[duplicated(labels)]) | |
| for (dup in duplicated_labels) { | |
| errors = c(errors, sprintf( | |
| "The label '%s' is used by more than one field. Labels must be unique.", dup | |
| )) | |
| } | |
| list(ok = length(errors) == 0, errors = errors, notes = notes, fields = clean) | |
| } | |
| # ellmer type for one field. All fields are optional so that the model can | |
| # return nothing when a document does not contain the information. | |
| field_to_type = function(field) { | |
| description = if (nchar(field$description) > 0) field$description else NULL | |
| switch( | |
| field$type, | |
| text = ellmer::type_string(description = description, required = FALSE), | |
| number = ellmer::type_number(description = description, required = FALSE), | |
| yes_no = ellmer::type_boolean(description = description, required = FALSE), | |
| list = ellmer::type_array( | |
| items = ellmer::type_string(), | |
| description = description, | |
| required = FALSE | |
| ), | |
| stop("Unknown field type: ", field$type) | |
| ) | |
| } | |
| # Build the ellmer type_object for a list of validated fields | |
| build_type_object = function(fields) { | |
| if (length(fields) == 0) stop("At least one field is required.") | |
| type_list = lapply(fields, field_to_type) | |
| names(type_list) = vapply(fields, function(f) f$label, character(1)) | |
| do.call(ellmer::type_object, type_list) | |
| } | |
| # ---- JSON export and import ------------------------------------------------- | |
| fields_to_json = function(fields) { | |
| payload = list( | |
| format = FIELDS_FILE_FORMAT, | |
| version = 1, | |
| fields = lapply(fields, function(f) { | |
| list(label = f$label, description = f$description, type = f$type) | |
| }) | |
| ) | |
| as.character(jsonlite::toJSON(payload, auto_unbox = TRUE, pretty = TRUE)) | |
| } | |
| # Parse field definitions from JSON text. Accepts the format written by | |
| # fields_to_json(), a template file, or a bare array of fields. | |
| # Returns list(ok, error, fields). | |
| fields_from_json = function(json_text, max_fields = MAX_FIELDS) { | |
| fail = function(message) list(ok = FALSE, error = message, fields = list()) | |
| json_text = paste(json_text, collapse = "\n") | |
| if (!validUTF8(json_text)) return(fail("The file is not a text file with JSON content.")) | |
| if (nchar(trimws(json_text)) == 0) return(fail("The file is empty.")) | |
| parsed = tryCatch( | |
| jsonlite::fromJSON(json_text, simplifyVector = FALSE), | |
| error = function(e) NULL | |
| ) | |
| if (is.null(parsed)) return(fail("The file is not valid JSON.")) | |
| raw_fields = if (is.list(parsed) && !is.null(names(parsed))) parsed$fields else parsed | |
| if (!is.list(raw_fields) || length(raw_fields) == 0 || !is.null(names(raw_fields))) { | |
| return(fail("The file does not contain a list of fields (expected a \"fields\" array).")) | |
| } | |
| is_text = function(x) is.character(x) && length(x) == 1 && !is.na(x) | |
| fields = list() | |
| for (i in seq_along(raw_fields)) { | |
| entry = raw_fields[[i]] | |
| if (!is.list(entry) || is.null(names(entry))) { | |
| return(fail(sprintf("Field %d is not an object with a label, description and type.", i))) | |
| } | |
| if (!is_text(entry$label)) { | |
| return(fail(sprintf("Field %d has no text label.", i))) | |
| } | |
| description = if (is.null(entry$description)) "" else entry$description | |
| if (!is_text(description)) { | |
| return(fail(sprintf("The description of field %d is not text.", i))) | |
| } | |
| type = if (is.null(entry$type)) "text" else entry$type | |
| if (!is_text(type) || !(type %in% names(FIELD_TYPES))) { | |
| return(fail(sprintf( | |
| "Field %d has an unknown type. Allowed types: %s.", | |
| i, paste(names(FIELD_TYPES), collapse = ", ") | |
| ))) | |
| } | |
| fields[[i]] = new_field(entry$label, description, type) | |
| } | |
| checked = validate_fields(fields, max_fields = max_fields) | |
| if (!checked$ok) return(fail(paste(checked$errors, collapse = " "))) | |
| list(ok = TRUE, error = "", fields = checked$fields) | |
| } | |
| read_fields_json = function(path, max_fields = MAX_FIELDS) { | |
| json_text = tryCatch( | |
| suppressWarnings(readLines(path, warn = FALSE, encoding = "UTF-8")), | |
| error = function(e) NULL | |
| ) | |
| if (is.null(json_text)) { | |
| return(list(ok = FALSE, error = "The file could not be read.", fields = list())) | |
| } | |
| fields_from_json(json_text, max_fields = max_fields) | |
| } | |
| # ---- Templates -------------------------------------------------------------- | |
| # Read the field templates (one JSON file each) from a directory. | |
| # Returns a list named by template id, in the order given by each file's | |
| # "order" value. | |
| load_templates = function(dir = file.path("config", "templates")) { | |
| files = sort(list.files(dir, pattern = "\\.json$", full.names = TRUE)) | |
| templates = lapply(files, function(path) { | |
| raw = jsonlite::fromJSON( | |
| paste(readLines(path, warn = FALSE, encoding = "UTF-8"), collapse = "\n"), | |
| simplifyVector = FALSE | |
| ) | |
| list( | |
| id = raw$id, | |
| name = raw$name, | |
| description = raw$description, | |
| order = if (is.null(raw$order)) Inf else raw$order, | |
| fields = lapply(raw$fields, function(f) new_field(f$label, f$description, f$type)) | |
| ) | |
| }) | |
| if (length(templates) == 0) return(list()) | |
| templates = templates[order(vapply(templates, function(t) as.numeric(t$order), numeric(1)))] | |
| names(templates) = vapply(templates, function(t) t$id, character(1)) | |
| templates | |
| } | |
| # Choices for the template selector (name shown = template id) | |
| template_choices = function(templates) { | |
| ids = names(templates) | |
| names(ids) = vapply(templates, function(t) t$name, character(1)) | |
| ids | |
| } | |