R Script to Produce a Dataframe of the Most Popular Downloaded Books on Project Gutenberg
The gutenbergr package provides access to Project Gutenberg's metadata and book texts, but it does not directly provide download statistics or a built-in list of "most popular" books. Project Gutenberg itself publishes a Top 100 list, but this is not available via an API or the gutenbergr package. However, you can manually obtain the IDs of the most downloaded books from that page and use gutenbergr to download their metadata and texts.
Below is an R script that demonstrates how to:
Manually specify a vector of popular Gutenberg IDs (e.g., from the Top 100 list).
Retrieve metadata for these books.
Download their texts into a dataframe.
# Load required packages
library(gutenbergr)
library(dplyr)
# Example: Gutenberg IDs for some of the most downloaded books
# (Replace or extend this list with IDs from the current Top 100 page)
popular_ids <- c(
1342, # Pride and Prejudice by Jane Austen
84, # Frankenstein by Mary Shelley
11, # Alice's Adventures in Wonderland by Lewis Carroll
1661, # The Adventures of Sherlock Holmes by Arthur Conan Doyle
2701, # Moby Dick by Herman Melville
76, # Adventures of Huckleberry Finn by Mark Twain
2542, # A Doll's House by Henrik Ibsen
345, # Dracula by Bram Stoker
98, # A Tale of Two Cities by Charles Dickens
74 # The Adventures of Tom Sawyer by Mark Twain
)
# Get metadata for these books
popular_books_metadata <- gutenberg_metadata %>%
filter(gutenberg_id %in% popular_ids)
# Download the texts with metadata fields
popular_books_text <- gutenberg_download(
popular_ids,
meta_fields = c("title", "author")
)
# View the resulting dataframe
head(popular_books_text)
Explanation
popular_ids: Replace or extend this vector with the Gutenberg IDs of the most popular books, which you can find on the Project Gutenberg Top 100 page.
gutenberg_metadata: Contains metadata for all books; filtering by gutenberg_id gives you details for the selected books[1][2][8].
gutenberg_download(): Downloads the full text for each book, with one row per line of text, and includes the title and author as extra columns[1][2][5][6][8].
Result: The resulting dataframe (popular_books_text) contains the Gutenberg ID, line of text, title, and author for each selected book.
Notes
The list of IDs must be updated manually, as gutenbergr does not fetch download counts or rankings automatically.
For a larger or regularly updated list, consider scraping the Top 100 page and extracting IDs, but be mindful of Project Gutenberg's terms of service regarding automated access[4][7][14].
The resulting dataframe is ready for further analysis or text mining, especially when combined with the tidytext package[2][8].
This approach leverages the strengths of gutenbergr for reproducible research and text analysis in R, while respecting Project Gutenberg's access policies.
User
How could I use the pageviews package to identify trends in popular books people are looking into?
Assistant
Using the pageviews Package to Identify Trends in Popular Books
The pageviews R package provides access to Wikimedia pageview data, including Wikipedia. Since many popular books have dedicated Wikipedia articles, you can use this package to track which books are being searched for and read about, revealing public interest trends over time.
Key Functions for Trend Analysis
top_articles(): Retrieves the most viewed Wikipedia articles for a given date or date range. This is useful for discovering which book-related articles are trending on a daily or monthly basis[3][12][14].
article_pageviews(): Retrieves time-series pageview data for a specific article, allowing you to analyze interest in a particular book over time[3][13][15].
project_pageviews(): Retrieves overall pageview counts for a Wikipedia project (e.g., all of English Wikipedia), which can be useful for normalization or broader trend analysis[3][6][7].
Example Workflow
1. Identify Trending Book Articles
Use top_articles() to get the top-viewed articles on English Wikipedia for a specific day or month. Filter the results for articles about books.
library(pageviews)
library(dplyr)
# Get top articles for a specific date
top <- top_articles(
project = "en.wikipedia",
start = as.Date("2025-04-01"),
granularity = "daily"
)
# Filter for likely book articles (e.g., by matching known book titles or using additional metadata)
book_titles <- c("Pride_and_Prejudice", "Moby-Dick", "To_Kill_a_Mockingbird") # Example list
top_books <- top %>% filter(article %in% book_titles)
print(top_books)
This gives you a snapshot of which book articles were most popular on a given day[12][14].
2. Analyze Trends Over Time for Specific Books
Use article_pageviews() to get daily or monthly pageviews for a book's Wikipedia article, revealing how interest changes (e.g., after a movie adaptation or anniversary).
# Get daily pageviews for "Pride and Prejudice" over the last year
views <- article_pageviews(
project = "en.wikipedia",
article = "Pride_and_Prejudice",
start = "2024040100",
end = "2025040100",
granularity = "monthly"
)
# Plot the trend
library(ggplot2)
ggplot(views, aes(x = date, y = views)) +
geom_line() +
labs(title = "Wikipedia Pageviews: Pride and Prejudice")
This approach lets you visualize spikes or declines in public interest[3][13][14].
3. Compare Multiple Books
You can repeat the above for several book articles and compare their trends side by side.
User
write me a function that downloads a project gutenberg text and then spilts the text by sentence
Assistant
Here is an R function that downloads a Project Gutenberg text using the gutenbergr package and splits the text into sentences. This example uses the split_sentence() function from the textshape package, which is robust for sentence boundary detection in English. Make sure you have both gutenbergr and textshape installed.
download_and_split_gutenberg <- function(gutenberg_id) {
# Load required packages
library(gutenbergr)
library(textshape)
library(dplyr)
# Download the book as a data frame (one row per line)
book <- gutenberg_download(gutenberg_id)
# Collapse all lines into a single string
full_text <- paste(book$text, collapse = " ")
# Split into sentences
sentences <- unlist(split_sentence(full_text))
# Return as a data frame
data.frame(
gutenberg_id = gutenberg_id,
sentence = sentences,
stringsAsFactors = FALSE
)
}
# Example usage:
# pride_sentences <- download_and_split_gutenberg(1342) # Pride and Prejudice
# head(pride_sentences)
Notes:
This function takes a single Gutenberg ID, downloads the text, collapses it into a single string, and splits it into sentences.
The result is a data frame with one sentence per row and the Gutenberg ID as a column.
The textshape::split_sentence() function is used for accurate sentence splitting[8].
You can look up Gutenberg IDs using gutenberg_works() or the gutenberg_metadata dataset[2][4][7].
This approach is robust and suitable for most English-language texts from Project Gutenberg.
User
Make another function that gets a chapter dataframe from the book dataframe
Assistant
Certainly! Here’s a function that takes the book dataframe (as returned by gutenberg_download()) and splits it into chapters, returning a dataframe where each row is a chapter. This works for most English novels on Project Gutenberg, where chapters are typically marked with lines like CHAPTER 1, Chapter I, etc.
We’ll use regular expressions to detect chapter headings. The function will:
Detect chapter starts using a regex.
Group lines between chapter headings.
Return a dataframe with columns for gutenberg_id, chapter_number, and chapter_text.
get_chapters_from_book <- function(book_df) {
library(dplyr)
library(stringr)
# Regular expression for common chapter headings
chapter_regex <- regex(
"^\\s*(chapter|CHAPTER)\\s+([0-9]+|[ivxlcIVXLC]+)\\b",
ignore_case = TRUE
)
# Identify which rows are chapter headings
book_df <- book_df %>%
mutate(
is_chapter = str_detect(text, chapter_regex),
chapter_number = cumsum(is_chapter)
)
# Remove any leading text before the first chapter
first_chapter <- min(book_df$chapter_number[book_df$is_chapter])
book_df <- book_df %>% filter(chapter_number >= first_chapter)
# Group lines by chapter and collapse into single text per chapter
chapters_df <- book_df %>%
group_by(gutenberg_id, chapter_number) %>%
summarise(
chapter_text = paste(text, collapse = " "),
.groups = "drop"
)
return(chapters_df)
}
# Example usage:
# book_df <- gutenberg_download(1342) # Pride and Prejudice
# chapters <- get_chapters_from_book(book_df)
# head(chapters)
Notes:
This function assumes the book is in the standard Project Gutenberg format, with clear chapter headings.
The regular expression can be adjusted for books with different chapter heading formats.
The output dataframe has one row per chapter, with the full chapter text in each row.
Let me know if you need a version that works with other chapter heading formats or languages!
User
How do I finetune a tinyllama model
Assistant
How to Finetune a TinyLlama Model
Fine-tuning TinyLlama—a lightweight, open-source language model—can be done efficiently on consumer hardware or free cloud GPUs (like Google Colab). The process is similar to fine-tuning other Llama-family models, but TinyLlama’s small size makes it especially suitable for experimentation and edge deployment. Below is a step-by-step guide using the most up-to-date community and official resources.
1. Environment Setup
Recommended Hardware: At least a T4 GPU (available for free on Google Colab), or a local machine with a modern GPU.
Using Unsloth (optimized for speed and memory efficiency):
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/tinyllama-bnb-4bit", # or "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
max_seq_length=2048,
dtype=None, # Auto-detects best dtype
load_in_4bit=True,
)
Or, with Hugging Face Transformers:
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
[2][6]
3. Prepare and Format Your Dataset
Format: Most LLMs expect data in a prompt-response format. For instruction tuning, use a template like Alpaca or ChatML.
Example Prompt Template:
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{instruction}
### Input:
{input}
### Response:
{output}
Load and Format Dataset:
from datasets import load_dataset
dataset = load_dataset("tatsu-lab/alpaca", split="train") # Or your own dataset
EOS_TOKEN = tokenizer.eos_token
def formatting_prompts_func(examples):
instructions = examples["instruction"]
inputs = examples["input"]
outputs = examples["output"]
texts = []
for instruction, input, output in zip(instructions, inputs, outputs):
text = f"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n{output}{EOS_TOKEN}"
texts.append(text)
return {"text": texts}
dataset = dataset.map(formatting_prompts_func, batched=True)
User
How can I finetune the tinyllama model for working with a specific dataset for sentence splitting
Assistant
To finetune TinyLlama for sentence splitting on your specific dataset, you need to frame the task as a supervised sequence-to-sequence or instruction-following problem. This means you’ll train the model to take a text input and output the same text, but with explicit sentence boundaries (e.g., by inserting a special token or newline at each sentence break). Here’s a step-by-step guide tailored for this use case:
1. Prepare Your Dataset
Input: Raw text (without sentence splits).
Output: The same text, but with sentence boundaries clearly marked (e.g., each sentence on a new line, or with a [SENT] token).
Format: For instruction tuning, use a prompt/response format such as:
### Instruction: Split the following text into sentences.
### Input: <raw text="">
### Response: <sentence1>\n<sentence2>\n...
Example:
{
"instruction": "Split the following text into sentences.",
"input": "This is a test. Here is another sentence.",
"output": "This is a test.\nHere is another sentence."
}
Tip: Use a script to generate these pairs from your corpus using a sentence splitter (e.g., spaCy, NLTK) for ground truth.
2. Format the Dataset for TinyLlama
Combine instruction, input, and output into a single text field for each example:
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="outputs",
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
num_train_epochs=1,
learning_rate=2e-4,
fp16=True, # or bf16 if supported
logging_steps=1,
optim="adamw_8bit",
max_steps=100, # Adjust as needed
report_to="none", # Or "wandb" for Weights & Biases logging
)
from transformers import pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
result = pipe("Your custom prompt here", max_new_tokens=64)
print(result['generated_text'])
[6][2]
Tips and Best Practices
Use small batch sizes and gradient accumulation if you have limited GPU memory.
Monitor training loss and use early stopping or validation sets to avoid overfitting.
Format your dataset carefully—prompt formatting is critical for good results.
Experiment with LoRA rank and learning rate for best results on your specific task.
References and Further Reading
[Hugging Face TinyLlama finetuning blog][2][8]
[Unsloth fine-tuning tutorial][6]
[YouTube step-by-step guides][1][4][9]
In summary:
Fine-tuning TinyLlama involves preparing your dataset in the right format, loading the model and tokenizer, configuring LoRA/PEFT for efficient training, setting training arguments, and running the training loop with a trainer like SFTTrainer from the trl library. The process is accessible, efficient, and well-supported by open-source tools and tutorials[2][6][1].
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16
)
model = AutoModelForCausalLM.from_pretrained(
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
quantization_config=bnb_config,
device_map="auto"
)
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
5. Training Setup
Use Hugging Face’s Trainer or trl.SFTTrainer[1][2][6][11].
Evaluate on a held-out set by comparing the model’s output to the ground truth splits.
Use metrics like accuracy, F1, or BLEU for sentence boundary detection[6][11].
7. Best Practices and Tips
Keep input/output formats consistent and explicit—TinyLlama is sensitive to prompt structure[6][11].
Use small batch sizes with gradient accumulation to avoid out-of-memory errors[6].
Monitor for overfitting—small models like TinyLlama can memorize small datasets quickly[6][11].
Test your tokenizer on sample data before full training to avoid silent errors[6][11].
Data augmentation (e.g., paraphrasing) can help generalization[6].
8. Sample Prompt for Inference
After fine-tuning, you can prompt the model like this:
### Instruction: Split the following text into sentences.
### Input: The quick brown fox jumps over the lazy dog. It then runs away.
### Response:
The model should output:
The quick brown fox jumps over the lazy dog.
It then runs away.
Summary Table: Key Steps
Step
What to Do
Data Prep
Create input/output pairs with explicit sentence boundaries
Formatting
Use instruction-following prompt format
Tokenization
Use TinyLlama tokenizer, truncate/pad as needed
Model Setup
Load TinyLlama, apply LoRA/PEFT for efficient fine-tuning
Training
Use Trainer/SFTTrainer, monitor for overfitting
Evaluation
Compare model output to ground truth, use BLEU/F1/accuracy
References:
[Hugging Face TinyLlama finetuning tutorial][1]
[Unsloth/Lablab TinyLlama LoRA guide][2]
[Data Scientist's Diary: TinyLlama fine-tuning best practices][6][11]
This approach will enable TinyLlama to learn sentence boundary detection tailored to your dataset, leveraging instruction tuning for robust, explicit sentence splitting performance.