import streamlit as st import requests import pandas as pd import time import urllib.parse # Base API URL for Open Library BASE_API_URL = "https://openlibrary.org/search.json" # List of subjects for selection 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): # Join the selected subjects into one search query query_subject = " ".join(subjects) # URL-encode the query components query_subject_encoded = urllib.parse.quote_plus(query_subject) time_facet_encoded = urllib.parse.quote_plus(time_facet) # Build the full URL with the mode and time_facet parameters query_url = f"{BASE_API_URL}?q={query_subject_encoded}&mode=everything&time_facet={time_facet_encoded}" st.write(f"🔗 Query URL: {query_url}") # Optional: Display the URL for debugging purposes 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) # A short delay to be respectful to the API server return books # Streamlit UI st.title("📚 Open Library Book Finder") st.write("Search for books by subject and a custom time facet.") # Let the user select one or more subjects selected_subjects = st.multiselect("Select subject(s)", SUBJECTS, default=["Classic Literature"]) # Let the user enter a custom time facet 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.")