## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE,
  comment = "#>"
)
source("cache-hook.R")

## ----message=FALSE, warning=FALSE---------------------------------------------
library(textpress)
library(dplyr)

## ----web-urls, cache_rds = c("feeds", "web_urls")-----------------------------
# feeds <- c(
#   textpress::rss_politics |>
#     filter(source == "Pew Research Center") |>
#     pull(url),
#   "https://theconversation.com/us/politics/articles.atom"
# )
# 
# web_urls <- textpress::fetch_rss(feeds) |>
#   filter(grepl(
#     "midterm|election|voter|Congress",
#     paste(title, description),
#     ignore.case = TRUE
#   )) |>
#   select(-doc_id) |>
#   distinct(url, .keep_all = TRUE)

## ----web-text, cache_rds = c("web_text_list", "web_ss")-----------------------
# web_text_list <- web_urls |>
#   textpress::read_urls(cores = 4)
# 
# web_ss <- web_text_list$text |>
#   textpress::nlp_split_sentences(by = c("doc_id", "node_id"))

## ----chunks-------------------------------------------------------------------
chunks <- textpress::nlp_roll_chunks(
  web_ss,
  by = c("doc_id", "node_id", "sentence_id"),
  id_col = 'uid',
  chunk_size = 1,
  context_size = 1)

## ----embeddings, cache_rds = "embeddings"-------------------------------------
# embeddings <- textpress::util_fetch_embeddings(
#   chunks,
#   by = "uid"
# )

## ----show-embeddings----------------------------------------------------------
dim(embeddings)
head(rownames(embeddings))

## ----index--------------------------------------------------------------------
index <- textpress::nlp_tokenize_text(
  chunks,
  by = c("uid"),
  include_spans = FALSE
  ) |>
  textpress::nlp_index_tokens(stem = T)

## -----------------------------------------------------------------------------
query_text <- "Why did Democrats gain in the 2026 midterms and which voters shifted?"

## ----search-bm25, message=FALSE, warning=FALSE--------------------------------
bm25_hits <- search_index(index,
                          query_text,
                          n = 25,
                          stem = TRUE)

bm25_hits |>
  DT::datatable(
    rownames = FALSE,
    options = list(dom = "lrtip",
                   pageLength = 5))

## ----query-embed, cache_rds = "query_embed"-----------------------------------
# query_embed <- textpress::util_fetch_embeddings(query_text)

## ----search-semantic----------------------------------------------------------
semantic_hits <- search_vector(embeddings, query_embed, n = 25)

semantic_hits |>
  DT::datatable(
    rownames = FALSE,
    options = list(dom = "lrtip",
                   pageLength = 5))

## ----rrf, message=FALSE, warning=FALSE----------------------------------------
k <- 60
both <- bind_rows(bm25_hits, semantic_hits) |>
  group_by(query, method) |>
  mutate(rank = row_number()) |>
  ungroup()

fused <- both |>
  mutate(rrf = 1 / (k + rank)) |>
  group_by(uid) |>
  summarise(rrf_score = round(100 * sum(rrf), 3), .groups = "drop") |>
  arrange(desc(rrf_score))

ff <- fused |>
  left_join(chunks) |>
  group_by(doc_id, node_id) |>
  slice_max(nchar(text), n = 1, with_ties = FALSE) |>
  ungroup() |>
  slice_max(rrf_score, n = 15)

## ----llm-setup, cache_rds = "context"-----------------------------------------
# library(ellmer)
# meta <- web_text_list$meta |> select(doc_id, date)
# ff_meta <- ff |> left_join(meta, by = "doc_id") |>
#   mutate(
#     header = if_else(!is.na(date) & nzchar(trimws(date)),
#       paste0("## Source ", doc_id, " (", date, ")\n\n"),
#       paste0("## Source ", doc_id, "\n\n")
#     ),
#     block = paste0(header, text)
#   )
# context <- paste(ff_meta$block, collapse = "\n\n---\n\n")
# chat <- ellmer::chat_openai(model = "gpt-4o-mini")

## ----llm-explanations, cache_rds = "explanations_out"-------------------------
# explanation_schema <- ellmer::type_object(
#   "Explanations the passages give for the 2026 midterm results.",
#   explanations = ellmer::type_array(
#     ellmer::type_object(
#       "One explanation.",
#       factor  = ellmer::type_string("Short name, e.g. turnout, economy, candidate quality."),
#       claim   = ellmer::type_string("What the passages say about it, in one or two sentences."),
#       voters  = ellmer::type_string("Voter groups involved, if the passages name any."),
#       sources = ellmer::type_string("Source numbers that support it, e.g. 3, 7.")
#     )
#   )
# )
# explanations_out <- chat$chat_structured(
#   glue::glue(
#     "Based solely on the passages, list the explanations given for the
#    results of the 2026 US midterm elections. Use one row per distinct
#    explanation and cite the source numbers that support it.
# 
#    PASSAGES:\n{context}"
#   ),
#   type = explanation_schema
# )

## ----show-explanations--------------------------------------------------------
explanations_out$explanations |> DT::datatable(rownames = F)

