File size: 9,981 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | /**
* OpenStax source provider for grounded teaching content.
*
* Uses the OpenStax CMS (Wagtail) API to search for relevant textbook chapters,
* then fetches page content from the public reader (openstax.org/books/{slug}/pages/{page}).
*
* All OpenStax CC BY textbooks are licensed under Creative Commons Attribution 4.0.
* OpenStax is a nonprofit initiative by Rice University providing free, peer-reviewed textbooks.
*
* API docs: https://github.com/openstax/cnx-archive/blob/master/docs/content_api_doc.md
* Book list: https://openstax.org/apps/cms/api/v2/pages/?type=books.Book&fields=title,slug
*/
const OPENSTAX_CMS_API = "https://openstax.org/apps/cms/api/v2/pages";
const OPENSTAX_BOOKS_BASE = "https://openstax.org/books";
const USER_AGENT = "RotNot/1.0 (educational app; contact: github.com/CuriosityQuantified/rotnot)";
export interface OpenStaxBook {
id: number;
title: string;
slug: string;
url: string;
}
export interface OpenStaxSection {
bookTitle: string;
bookSlug: string;
sectionTitle: string;
sectionSlug: string;
url: string;
excerpt: string;
}
/**
* Maps Feynman topic domains to relevant OpenStax book slugs.
* Prefers latest editions (2e, 3e). All listed books are CC BY 4.0.
*/
const DOMAIN_BOOK_MAP: Record<string, string[]> = {
Physics: ["college-physics-2e", "university-physics-volume-1", "university-physics-volume-2", "university-physics-volume-3"],
Biology: ["biology-2e", "concepts-biology", "microbiology", "anatomy-and-physiology-2e"],
Chemistry: ["chemistry-2e", "chemistry-atoms-first-2e", "organic-chemistry"],
Economics: ["principles-economics-3e", "principles-microeconomics-3e", "principles-macroeconomics-3e"],
Psychology: ["psychology-2e", "introduction-sociology-3e"],
Mathematics: ["calculus-volume-1", "calculus-volume-2", "calculus-volume-3", "introductory-statistics-2e", "prealgebra-2e"],
CS: ["introduction-computer-science"],
History: ["us-history", "world-history-volume-1", "world-history-volume-2"],
Philosophy: ["introduction-philosophy", "introduction-logic-critical-thinking"],
};
/**
* Search the OpenStax CMS for books matching a query.
* Uses the Wagtail API `search` parameter on Book page types.
* Returns up to `limit` results (default 3).
*/
export async function searchOpenStaxBooks(
query: string,
limit: number = 3,
): Promise<OpenStaxBook[]> {
const params = new URLSearchParams({
type: "books.Book",
fields: "title,slug",
format: "json",
limit: String(limit),
search: query,
});
const response = await fetch(`${OPENSTAX_CMS_API}?${params}`, {
headers: { "User-Agent": USER_AGENT },
});
if (!response.ok) {
throw new Error(`OpenStax book search failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const items = data?.items ?? [];
return items.map((item: { id: number; title: string; meta: { slug: string; html_url: string } }) => ({
id: item.id,
title: item.title,
slug: item.meta.slug,
url: item.meta.html_url || `https://openstax.org/details/books/${item.meta.slug}`,
}));
}
/**
* Fetch text content from an OpenStax book page URL.
* Strips HTML to return clean, readable text.
* Returns null if the page is not accessible or empty.
*/
export async function fetchOpenStaxPageContent(
bookSlug: string,
pageSlug: string,
maxChars: number = 4000,
): Promise<{ title: string; content: string; url: string } | null> {
const url = `${OPENSTAX_BOOKS_BASE}/${bookSlug}/pages/${pageSlug}`;
const response = await fetch(url, {
headers: { "User-Agent": USER_AGENT },
});
if (!response.ok) {
return null;
}
const html = await response.text();
// Extract page title from <title> tag
const titleMatch = html.match(/<title[^>]*>([^<]+)</);
const rawTitle = titleMatch ? titleMatch[1] : pageSlug;
// Clean up title: "1.1 Physics: Definitions - Physics | OpenStax" → "1.1 Physics: Definitions"
const title = rawTitle.replace(/\s*[-–|].*OpenStax.*$/i, "").replace(/\s*[-–|]\s*$/, "").trim();
// Extract main content — OpenStax wraps content in data-type="page" or class with page content
// We'll extract text from the main content area, stripping HTML
let content = extractMainContent(html);
// Truncate to maxChars
if (content.length > maxChars) {
content = content.slice(0, maxChars) + "…";
}
if (content.length < 100) {
return null; // too little content
}
return { title, content, url };
}
/**
* Search OpenStax for content relevant to a Feynman topic.
* Uses domain-based book selection + keyword matching in page slugs.
*
* Returns up to `maxResults` section excerpts.
*/
export async function fetchOpenStaxSources(
topicName: string,
domain?: string,
maxResults: number = 2,
): Promise<OpenStaxSection[]> {
const sections: OpenStaxSection[] = [];
// Step 1: Determine candidate books
const candidateSlugs = domain ? (DOMAIN_BOOK_MAP[domain] ?? []) : [];
// Step 2: Also try CMS search for additional coverage
let searchBooks: OpenStaxBook[] = [];
try {
// Extract key terms from the topic for a focused search
const searchTerms = extractSearchTerms(topicName);
searchBooks = await searchOpenStaxBooks(searchTerms, 3);
} catch {
// Search failure is non-critical
}
// Combine: domain-mapped books first, then search results
const allSlugs = [...new Set([
...candidateSlugs,
...searchBooks.map((b) => b.slug),
])];
if (allSlugs.length === 0) {
return [];
}
// Step 3: For each candidate book, try to find a relevant page
// We generate plausible page slugs from the topic name
const pageSlugs = generatePageSlugs(topicName);
for (const bookSlug of allSlugs) {
if (sections.length >= maxResults) break;
for (const pageSlug of pageSlugs) {
if (sections.length >= maxResults) break;
const page = await fetchOpenStaxPageContent(bookSlug, pageSlug);
if (page && page.content.length >= 200) {
sections.push({
bookTitle: searchBooks.find((b) => b.slug === bookSlug)?.title ?? formatSlugAsTitle(bookSlug),
bookSlug,
sectionTitle: page.title,
sectionSlug: pageSlug,
url: page.url,
excerpt: page.content,
});
break; // Found content in this book, move to next
}
}
}
return sections;
}
/**
* Extract key search terms from a topic name.
* Removes common filler words to improve CMS search quality.
*/
export function extractSearchTerms(topic: string): string {
const stopWords = new Set([
"how", "what", "why", "the", "a", "an", "and", "or", "of", "in", "to",
"is", "are", "was", "were", "works", "work", "does", "do", "between",
"its", "it", "that", "this", "for", "with", "from", "three", "two",
]);
return topic
.toLowerCase()
.replace(/['']/g, "'")
.replace(/[^\w\s'-]/g, " ")
.split(/\s+/)
.filter((w) => !stopWords.has(w) && w.length > 1)
.slice(0, 4) // CMS search works best with fewer terms
.join(" ");
}
/**
* Generate plausible OpenStax page slugs from a topic name.
* OpenStax uses slugs like "1-1-physics-definitions-and-applications".
* Since we can't know the chapter number, we generate the keyword portion
* and also try the topic index page.
*/
export function generatePageSlugs(topicName: string): string[] {
// Convert topic to slug format: lowercase, spaces to hyphens, strip non-alphanumeric
const baseSlug = topicName
.toLowerCase()
.replace(/['']/g, "")
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
// Also extract key concepts for shorter slug attempts
const keyTerms = extractSearchTerms(topicName)
.replace(/['']/g, "")
.replace(/\s+/g, "-");
const slugs = new Set<string>();
// Full topic as slug
slugs.add(baseSlug);
// Key terms as slug
if (keyTerms && keyTerms !== baseSlug) {
slugs.add(keyTerms);
}
// First 2-3 key words (common OpenStax pattern)
const words = baseSlug.split("-").filter((w) => w.length > 2);
if (words.length > 3) {
slugs.add(words.slice(0, 3).join("-"));
}
if (words.length > 2) {
slugs.add(words.slice(0, 2).join("-"));
}
return Array.from(slugs);
}
/**
* Extract main content text from an OpenStax HTML page.
* Strips HTML tags, teacher support blocks, and navigation chrome.
*/
function extractMainContent(html: string): string {
// Remove script and style tags entirely
let cleaned = html
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
.replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, "")
.replace(/<header[^>]*>[\s\S]*?<\/header>/gi, "")
.replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, "");
// Remove Teacher Support sections (OpenStax K-12 content includes these)
cleaned = cleaned.replace(/<[^>]*class="[^"]*teacher[^"]*"[^>]*>[\s\S]*?(?=<\/(?:div|section)>)/gi, "");
// Strip all HTML tags
cleaned = cleaned
.replace(/<[^>]+>/g, " ")
.replace(/ /g, " ")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/'/g, "'")
.replace(/\s+/g, " ")
.trim();
// Remove common noise patterns
cleaned = cleaned
.replace(/Want to cite, share, or modify this book\?.*$/i, "")
.replace(/Citation\/Attribution.*$/i, "")
.replace(/This book may not be used in the training.*$/i, "")
.replace(/Order a print copy.*$/i, "");
return cleaned.trim();
}
/**
* Format a book slug into a readable title.
* "college-physics-2e" → "College Physics 2e"
*/
function formatSlugAsTitle(slug: string): string {
return slug
.split("-")
.map((word) => {
if (word.match(/^\d/)) return word; // numbers/editions like "2e"
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(" ");
}
|