openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Import bookdash.org as a Trusted Book Provider (with editions for all languages)

Open mekarpeles opened this issue 1 year ago • 18 comments

Feature Request

Here is the sitemap of books for bookdash https://bookdash.org/books-sitemap.xml

This python code gives us a list of the ~850 urls:

import requests
import xml.etree.ElementTree as ET

# Step 1: Get the XML from the sitemap URL
url = "https://bookdash.org/books-sitemap.xml"
response = requests.get(url)
response.raise_for_status()  # Raises an error if the request failed

# Step 2: Parse the XML
root = ET.fromstring(response.content)

# Step 3: Extract all <loc> elements (which are like the rows of the sitemap)
namespaces = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}  # Define XML namespace
locs = root.findall('.//ns:loc', namespaces)

# Step 4: Print each URL (you could treat this like the "td" values)
book_urls = [loc.text for loc in locs]
print(json.dumps(book_urls))

Here is the list of the URLs: https://gist.githubusercontent.com/mekarpeles/dc5e89708bbf7cae38b35f071021a12a/raw/99abd429075ae5246caa15b8878ad0c59456f38a/bookdashorg_urls.json

re: metadata:

Problem / Opportunity

Write a basic python request scraper to respectfully curl each book page, extract the metadata in the right formats, as an openlibrary book in json

Proposal

Breakdown

Related files

Refer to this map of common Endpoints: *

Requirements Checklist

Checklist of requirements that need to be satisfied in order for this issue to be closed:

  • [ ]

Stakeholders


Instructions for Contributors

mekarpeles avatar May 27 '25 14:05 mekarpeles

This is approximately what the script should look like:

import requests
import xml.etree.ElementTree as ET
import json
from bs4 import BeautifulSoup
import re # For finding ISBN and Publication Date

# Step 1: Get the XML from the sitemap URL
sitemap_url = "https://bookdash.org/books-sitemap.xml"
try:
    response = requests.get(sitemap_url)
    response.raise_for_status()  # Raises an error if the request failed
except requests.exceptions.RequestException as e:
    print(f"Error fetching sitemap: {e}")
    exit()

# Step 2: Parse the XML
try:
    root = ET.fromstring(response.content)
except ET.ParseError as e:
    print(f"Error parsing sitemap XML: {e}")
    exit()

# Step 3: Extract all <loc> elements
namespaces = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
locs = root.findall('.//ns:loc', namespaces)
book_urls = [loc.text for loc in locs]

all_books_data = []

# Step 4: Iterate through each book URL and extract data
for book_url in book_urls[1:]:
    print(f"Processing: {book_url}")
    try:
        book_response = requests.get(book_url, timeout=10) # Added timeout
        book_response.raise_for_status()
        soup = BeautifulSoup(book_response.content, 'html.parser')

        book_data = {}

        # Cover image
        book_data['cover_image'] = None

        # Try to get the Open Graph image first (most reliable)
        meta_og_image = soup.find('meta', property='og:image')
        if meta_og_image and meta_og_image.get('content'):
            book_data['cover_image'] = meta_og_image['content'].strip()
        else:
            # Fallback to existing logic if og:image is not found
            picture_tag = soup.find('picture')
            if picture_tag:
                img_tag = picture_tag.find('img')
                if img_tag and img_tag.get('src') and not "preload" in img_tag['src']: # Avoid preload images
                    book_data['cover_image'] = img_tag['src']
                else:
                    # Check source tags within picture for srcset
                    source_tag = picture_tag.find('source')
                    if source_tag and source_tag.get('srcset'):
                        # Take the first URL from srcset, it's usually the smallest/default
                        # and ensure it's not a preload image
                        srcset_urls = [s.strip().split(' ')[0] for s in source_tag['srcset'].split(',') if "preload" not in s]
                        if srcset_urls:
                            book_data['cover_image'] = srcset_urls[0]
            # If still no image, look for a prominent <img> tag directly
            if not book_data['cover_image']:
                main_content_div = soup.find('div', class_='book-hero-image') # Assuming a class for the main image
                if main_content_div:
                    img_tag = main_content_div.find('img')
                    if img_tag and img_tag.get('src') and not "preload" in img_tag['src']:
                        book_data['cover_image'] = img_tag['src']

        # Title
        title_tag = soup.find('h1')
        book_data['title'] = title_tag.text.strip() if title_tag else None

        # ISBN
        # Search for "ISBN:" and get the text that follows.
        # This is a bit fragile and depends on consistent formatting.
        isbn = None
        isbn_element = soup.find(string=re.compile(r"ISBN:"))
        if isbn_element:
            # Try to get the text immediately following "ISBN:"
            # This might need adjustment based on actual HTML structure
            potential_isbn = isbn_element.split("ISBN:")[1].strip()
            # Basic validation for an ISBN-like structure (10 or 13 digits, possibly with hyphens)
            if re.match(r'^[\dX-]+$', potential_isbn):
                 isbn = potential_isbn.split()[0] # Take the first part if there are spaces after
            else: # If not directly after, check parent or siblings
                parent_text = isbn_element.parent.get_text(separator=' ', strip=True)
                match = re.search(r"ISBN:\s*([\d\-X]+)", parent_text)
                if match:
                    isbn = match.group(1)
        book_data['isbn'] = isbn

        # Language
        # Contents within the <a> tag where the href contains "/languages/"
        language_tag = soup.find('a', href=lambda href: href and "/languages/" in href)
        book_data['language'] = language_tag.text.strip() if language_tag else None

        # Description (meta og:description)
        meta_description_og = soup.find('meta', property='og:description')
        meta_description_name = soup.find('meta', attrs={'name': 'description'})
        if meta_description_og and meta_description_og.get('content'):
            book_data['description'] = meta_description_og['content'].strip()
        elif meta_description_name and meta_description_name.get('content'):
            book_data['description'] = meta_description_name['content'].strip()
        else:
            book_data['description'] = None


        # Subjects (contents of a tags with hrefs that start with "/themes")
        subject_tags = soup.find_all('a', href=lambda href: href and href.startswith("/themes"))
        book_data['subjects'] = [tag.text.strip() for tag in subject_tags] if subject_tags else []

        # Authors (author names will be in a tags where href starts with "https://bookdash.org/team-members/")
        author_tags = soup.find_all('a', href=lambda href: href and href.startswith("https://bookdash.org/team-members/"))
        book_data['authors'] = [tag.text.strip() for tag in author_tags] if author_tags else []

        # Publisher
        book_data['publisher'] = "BookDash"

        # Publication Date (will always be "20XX")
        # Attempt to find a year in the format 20XX in the page content.
        # This might be on a copyright line or similar.
        publication_date = None
        # Search for a 4-digit year starting with "20"
        year_match = re.search(r'\b(20\d{2})\b', soup.get_text())
        if year_match:
            publication_date = year_match.group(1)
        else:
            # Fallback based on user note if no specific year found
            publication_date = "20XX" # Or None, if "20XX" isn't desired as a literal fallback
        book_data['publication_date'] = publication_date

        book_data['url'] = book_url # Add the source URL for reference

        all_books_data.append(book_data)
        print(book_data)
    except requests.exceptions.RequestException as e:
        print(f"Error fetching book page {book_url}: {e}")
    except Exception as e:
        print(f"Error processing book page {book_url}: {e}")
        # Optionally, add a placeholder or skip the entry
        all_books_data.append({
            "url": book_url,
            "error": str(e),
            "title": "Error processing this book"
        })

mekarpeles avatar May 28 '25 01:05 mekarpeles

Hi @mekarpeles 👋

Using the code you provided above, here’s a sample of data I extracted from a Book Dash page: https://bookdash.org/...

Sample output:

{
  "cover_image": "https://bookdash.org/wp-content/uploads/2019/05/babys-first-family-photo_en_20190506_cover.jpg",
  "title": "Baby’s First Family Photo",
  "isbn": "978-1-928497-28-8",
  "language": "English",
  "description": "Baby’s family is excited about their first family photo. What will Mama, Papa, Big Sister, Baby and Gogo wear?",
  "subjects": ["Family, friends, and home", "Let's learn!"],
  "authors": ["Megan Andrews (Illustrator)", "Nadene Kriel (Designer)", "Glynis Lloyd (Editor)", "Edem Torkornoo (Writer)"],
  "publisher": "BookDash",
  "publication_date": "2019",
  "url": "https://bookdash.org/books/babys-first-family-photo/"
}

Could you kindly provide a brief example of the expected JSON format for Open Library Trusted Provider imports? I want to confirm it matches before proceeding. Also, please assign me to this issue—I’m eager to work on it!

sai-krishna-kotha avatar May 29 '25 14:05 sai-krishna-kotha

Hi @sai-krishna-kotha here's what Open Library's import schema looks like:

https://github.com/internetarchive/openlibrary-client/blob/master/olclient/schemata/import.schema.json

For the isbn, you'll want to remove dashes "-"

You'll also want to make sure the json is in jsonl format (i.e. all on one line)

Then you can use the Import Queue web UI: https://github.com/internetarchive/openlibrary/wiki/The-Import-Pipeline#web-interface

https://openlibrary.org/import/batch/new

Each book will need to have a field called identifiers with the slug of the book title e.g.

 "identifiers": {"bookdash": "babys-first-family-photo"}

each line will need to be its own json object e.g.

{...}
{...}
{...}

I think right now the cover url may not work automatically 😞 (this is our fault) but if the field gets written to the item, we can fix this later!

Once the items are submitted, a member of staff may have to approve them so you can send me a message and I will happily review! Thank you!!

mekarpeles avatar Jul 11 '25 15:07 mekarpeles

Hey @mekarpeles,

Good news! After a bit of a marathon, the scraper is finally working perfectly.

I've just finished running it and have uploaded the bookdash_import.jsonl file to the import queue. It should be ready for you to review and approve whenever you get a chance.

Thanks again for all the help and patience!

sai-krishna-kotha avatar Jul 31 '25 14:07 sai-krishna-kotha

🎉 @sai-krishna-kotha can you link to a gist or some version of the scraper you've created so we can review?

Also, can you share your Open Library username so we can review the batch?

mekarpeles avatar Sep 05 '25 16:09 mekarpeles

I think this may be the batch?

https://openlibrary.org/import/batch/1516

mekarpeles avatar Sep 05 '25 16:09 mekarpeles

@mekarpeles Here is the Gist for the scraper script. Yes, the batch you linked is the correct one from this script's output. https://gist.github.com/sai-krishna-kotha/2602c9d13b0f3da4c4a0e701096b0219

sai-krishna-kotha avatar Sep 05 '25 17:09 sai-krishna-kotha

Thank you so much @sai-krishna-kotha -- one potential issue @cdrini noticed is that we may be appending the author role to their name (which can cause duplicate author creation)

We don't have a great way to handle this as...

  • a batch cannot be deleted yet through the UI 😅

We could delete the batch for you but would hate to do so without coordinating with you. The ideal is that we delete, create a new batch w/ corrected author names.. OR we update the author import flow on our side to ignore parens ()'s...

mekarpeles avatar Sep 08 '25 20:09 mekarpeles

@scottbarnes this is an example where unblocking cover uploads from our server via WAF would be helpful.

The domain for this trusted provider is https://bookdash.org/wp-content (cover images)

mekarpeles avatar Sep 08 '25 20:09 mekarpeles

@mekarpeles Got it, thanks for flagging! I’m fine with whichever is easier on your end

happy to go with either deleting/re-creating the batch or updating the import flow to ignore parentheses. Just let me know what you prefer.

sai-krishna-kotha avatar Sep 09 '25 11:09 sai-krishna-kotha

@sai-krishna-kotha I think we'll try to update these for you! :)

mekarpeles avatar Sep 12 '25 07:09 mekarpeles

Language also shouldn't be empty. :)

I'll take care of it.

We also need to add bookdash to WAF + python allow list @scottbarnes

mekarpeles avatar Sep 16 '25 19:09 mekarpeles

This fixes the authors field; it doesn't fix the language(s) or covers but perhaps that's fine for now.

import web
import infogami
import os
import json
from openlibrary.config import load_config
path = '/olsystem/etc/openlibrary.yml'  # prod
load_config(path)
infogami._setup()
from infogami import config
from openlibrary.core import db
oldb = db.get_db() # i.e. web.database(**web.config.db_parameters)
records = list(oldb.query("select * from import_item where ia_id LIKE 'bookdash:%';"))

# Fix the records
for i in range(len(records)):
    data = json.loads(records[i]['data'])
    print(data)
    for j in range(len(data.get('authors', []))):
        data['authors'][j]['name'] = data['authors'][j]['name'].split('(')[0].strip()
        records[i]['data'] = json.dumps(data)

# Perform update:
for i in range(len(records)):
    db.update("import_item", data=records[i]['data'], where=f"id={records[i]['id']}")

mekarpeles avatar Sep 25 '25 07:09 mekarpeles

I've approved the batch, though we'll need to perform a second run to add:

  1. the languages (where missing)
  2. the covers with proxy, cc @scottbarnes
  3. the acquisition url (or link as a trusted book provider @cdrini)

mekarpeles avatar Sep 25 '25 07:09 mekarpeles

We need to add https://bookdash.org/wp-content/uploads cover url pattern to https://github.com/internetarchive/openlibrary/blob/07a2246e63fa2a59dce73d92e11cffc81804a5e5/openlibrary/catalog/add_book/init.py#L84-L88

And also to https://git.archive.org/ia/ansible-squid-http-proxy/-/blob/main/files/acl.conf?ref_type=heads#L119 acl allowed_domain dstdomain bookdash.org

mekarpeles avatar Oct 27 '25 20:10 mekarpeles

Hi @mekarpeles! I went through the trusted book provider issues and the import pipeline docs, and I want to run a plan by you before writing any code.

Instead of starting a new data source, I'd like to pick up the BookDash import from issue #10856. A contributor already wrote a working scraper and submitted a batch (openlibrary.org/import/batch/1516), but it's stuck on one bug: the scraper pulled author names with their role attached, like "Megan Andrews (Illustrator)" instead of just "Megan Andrews." That risks creating a duplicate author instead of matching the existing one. You mentioned OL would try to fix this on your end, but it looks like nothing's landed yet and the batch is still sitting there.

Compared to ITAN (#12091), which is blocked on an identifier PR in a separate repo, BookDash feels like the more realistic thing I can actually finish.

My plan:

  1. Pull the exact author name format from the scraper's gist so I know precisely what to strip.
  2. Write a fix plus a test for it.
  3. Dry run corrected records through the preview endpoint before touching anything live.
  4. Add a short note to the import docs about this gotcha so future scrapers don't repeat it.

Three things I want your input on before I start:

  1. Should the fix live in the scraper script, or in the shared import pipeline (add_book.py)? A pipeline fix would help every future source, not just this one. I lean toward the pipeline based on your comment, but it changes the scope so wanted to check.
  2. Since batches can't be edited after submission, do you want me to coordinate deleting and resubmitting batch 1516 with corrected data, or handle it a different way?
  3. Does BookDash sound like a reasonable place to start, or would you rather I look at something else?

One more thing: adding-sources.md links to a file, pm/workflows/import_workflow.md, that doesn't exist in the repo. Not sure if it's supposed to point elsewhere or just needs removing, flagging it either way.

rattnak avatar Jul 21 '26 18:07 rattnak

@rattnak thank you! This is all spot on.

  1. I think we ideally want to build out Importer scripts per source (e.g. BookDash) so it makes more sense in its own script than within the import pipeline. The import pipeline should hopefully remain fairly agnostic -- it just cares that data of the right shape / schema is submitted.
  2. Yes please, let's coordinate; I can clear the previous batch to enable you to resubmit. Do you happen to have the batch name / id handy?
  3. I think bookdash is a wonderful place to start :)

mekarpeles avatar Jul 21 '26 19:07 mekarpeles

  • Awesome, thank you for confirming! That makes sense, keeping the pipeline schema-agnostic and pushing the source-specific logic into its own script is cleaner long term.
  • The batch is openlibrary.org/import/batch/1516.
  • I'll get started on a proper BookDash importer script (stripping the parenthetical roles from author names before submission) and let you know once I have corrected records ready to resubmit. I'll ping you again once the batch is cleared and I'm ready to go.

rattnak avatar Jul 21 '26 20:07 rattnak