| import streamlit as st |
| import requests |
| import pandas as pd |
| import time |
| import urllib.parse |
|
|
| |
| BASE_API_URL = "https://openlibrary.org/search.json" |
|
|
| |
| SUBJECTS = [ |
| "Classic Literature", "Modern Literature", "Postmodern Literature", "Romanticism", |
| "Realism", "Naturalism", "Existentialism", "Absurdism", "Gothic Fiction", "Science Fiction", |
| "Fantasy Literature", "Historical Fiction", "Mystery and Detective Fiction", "Horror Literature", |
| "Adventure Novels", "Bildungsroman", "Epistolary Novels", "Satire", "Tragedy", "Comedy" |
| ] |
|
|
| def fetch_books(subjects, time_facet): |
| |
| query_subject = " ".join(subjects) |
| |
| |
| query_subject_encoded = urllib.parse.quote_plus(query_subject) |
| time_facet_encoded = urllib.parse.quote_plus(time_facet) |
| |
| |
| query_url = f"{BASE_API_URL}?q={query_subject_encoded}&mode=everything&time_facet={time_facet_encoded}" |
| st.write(f"π Query URL: {query_url}") |
| |
| response = requests.get(query_url) |
| books = [] |
| |
| if response.status_code == 200: |
| data = response.json() |
| for book in data.get("docs", []): |
| books.append({ |
| "title": book.get("title", "N/A"), |
| "author": ", ".join(book.get("author_name", ["N/A"])), |
| "first_publish_year": book.get("first_publish_year", "N/A") |
| }) |
| else: |
| st.error("Error fetching data from Open Library.") |
| |
| time.sleep(1) |
| return books |
|
|
| |
| st.title("π Open Library Book Finder") |
| st.write("Search for books by subject and a custom time facet.") |
|
|
| |
| selected_subjects = st.multiselect("Select subject(s)", SUBJECTS, default=["Classic Literature"]) |
|
|
| |
| time_facet = st.text_input("Enter a time facet (e.g., 20th century)") |
|
|
| if st.button("Find Books"): |
| if not time_facet: |
| st.error("Please enter a time facet!") |
| else: |
| st.write("π Searching books...") |
| books = fetch_books(selected_subjects, time_facet) |
| if books: |
| df = pd.DataFrame(books) |
| st.write(df) |
| else: |
| st.write("β No books found for the selected criteria.") |
|
|