AnnNaser commited on
Commit
7a02fd9
·
verified ·
1 Parent(s): f1bf0c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -218
app.py CHANGED
@@ -1,227 +1,62 @@
1
- import streamlit as st
2
  import requests
3
  import pandas as pd
4
  from bs4 import BeautifulSoup
5
 
6
- # --- Functions ---
7
-
8
- def fetch_books(subjects, start_year, end_year, page=1):
9
- """
10
- Use the Open Library search API to get books matching the given subjects
11
- and publication year range.
12
- """
13
- base_url = "https://openlibrary.org/search.json"
14
- # Build query from subjects (joined with OR)
15
- query = " OR ".join([f"subject:{subject}" for subject in subjects])
16
- params = {
17
- "q": query,
18
- "first_publish_year": f"{start_year}",
19
- "last_publish_year": f"{end_year}",
20
- "page": page
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  }
22
- try:
23
- response = requests.get(base_url, params=params)
24
- response.raise_for_status()
25
- data = response.json()
26
- books = data.get("docs", [])
27
- return books
28
- except Exception as e:
29
- st.error(f"Error fetching books: {e}")
30
- return []
31
-
32
-
33
- def scrape_book_details(book_key):
34
- """
35
- Given a book key (e.g. "/books/OL25845742M/A_house_of_pomegranates"),
36
- scrape its Open Library page to extract details.
37
- """
38
- url = "https://openlibrary.org" + book_key
39
- try:
40
- r = requests.get(url)
41
- if r.status_code != 200:
42
- return dict(
43
- title="Not available",
44
- first_published="Not available",
45
- authors="Not available",
46
- description="Not available",
47
- author_image="Not available",
48
- book_cover="Not available"
49
- )
50
- soup = BeautifulSoup(r.text, "html.parser")
51
-
52
- # Title (from <h1 class="work-title" itemprop="name">)
53
- title_tag = soup.find("h1", class_="work-title")
54
- title = title_tag.get_text(strip=True) if title_tag else "Not available"
55
-
56
- # First Published Year (from <span class="first-published-date">)
57
- fp_span = soup.find("span", class_="first-published-date")
58
- first_published = fp_span.get_text(strip=True).strip("()") if fp_span else "Not available"
59
-
60
- # Author(s) (from <h2 class="edition-byline"> with <a> links)
61
- byline = soup.find("h2", class_="edition-byline")
62
- if byline:
63
- authors_links = byline.find_all("a")
64
- authors = ", ".join(a.get_text(strip=True) for a in authors_links) if authors_links else "Not available"
65
- else:
66
- authors = "Not available"
67
-
68
- # Description (from <div class="book-description"> → <div class="read-more__content">)
69
- desc_div = soup.find("div", class_="book-description")
70
- if desc_div:
71
- content_div = desc_div.find("div", class_="read-more__content")
72
- description = content_div.get_text(separator="\n", strip=True) if content_div else "Not available"
73
- else:
74
- description = "Not available"
75
-
76
- # Book Cover (from <div class="cover"> → <img src=...>)
77
- cover_div = soup.find("div", class_="cover")
78
- if cover_div:
79
- img = cover_div.find("img")
80
- if img and img.get("src"):
81
- book_cover = img["src"]
82
- if book_cover.startswith("//"):
83
- book_cover = "https:" + book_cover
84
- else:
85
- book_cover = "Not available"
86
- else:
87
- book_cover = "Not available"
88
-
89
- # Author Image: try scraping the first author's page.
90
- if byline and byline.find_all("a"):
91
- first_author_link = byline.find_all("a")[0].get("href")
92
- if first_author_link:
93
- author_url = "https://openlibrary.org" + first_author_link
94
- r_auth = requests.get(author_url)
95
- if r_auth.status_code == 200:
96
- soup_auth = BeautifulSoup(r_auth.text, "html.parser")
97
- # Look for an <img> whose alt text contains "author"
98
- author_img = soup_auth.find("img", alt=lambda x: x and "author" in x.lower())
99
- if author_img and author_img.get("src"):
100
- author_image = author_img["src"]
101
- if author_image.startswith("//"):
102
- author_image = "https:" + author_image
103
- else:
104
- author_image = "Not available"
105
- else:
106
- author_image = "Not available"
107
- else:
108
- author_image = "Not available"
109
- else:
110
- author_image = "Not available"
111
-
112
- return dict(
113
- title=title,
114
- first_published=first_published,
115
- authors=authors,
116
- description=description,
117
- author_image=author_image,
118
- book_cover=book_cover
119
- )
120
- except Exception as e:
121
- return dict(
122
- title="Not available",
123
- first_published="Not available",
124
- authors="Not available",
125
- description="Not available",
126
- author_image="Not available",
127
- book_cover="Not available"
128
- )
129
 
130
- # --- Main Streamlit App ---
131
-
132
- def main():
133
- st.title("Book Finder and Scraper")
134
- st.write("Search for books by subject(s) and publication year range, then scrape details from Open Library.")
 
 
 
135
 
136
- # Sidebar: Input selections
137
- st.sidebar.title("Search Filters")
138
- subjects = st.sidebar.multiselect(
139
- "Select Subjects (choose one or more):",
140
- options=[
141
- "Philosophy", "Modern Literature", "Classic Literature", "Drama", "Psychological Fiction",
142
- "Historical Fiction", "Poetry", "Dystopian Fiction", "Romanticism", "Existentialism", "Tragedy",
143
- "Comedy", "Philosophical Fiction", "Social Realism", "Feminist Literature", "Surrealism",
144
- "Renaissance Literature", "Victorian Literature", "Gothic Fiction", "Transcendentalism",
145
- "Magical Realism", "Absurdism", "Allegory", "Mythology", "Metaphysical Poetry", "Postmodern Literature",
146
- "Epic Poetry", "Literary Criticism", "Realism", "Postmodernism", "Contemporary Drama", "Political Drama"
147
- ]
148
- )
149
- year_range = st.sidebar.slider(
150
- "Select Publication Year Range:",
151
- min_value=1700,
152
- max_value=2025,
153
- value=(2000, 2020),
154
- step=1
155
- )
156
- start_year, end_year = year_range
157
-
158
- # When Search is clicked:
159
- if st.sidebar.button("Search"):
160
- if not subjects:
161
- st.sidebar.error("Please select at least one subject.")
162
- return
163
- if start_year > end_year:
164
- st.sidebar.error("Start year must be less than or equal to end year.")
165
- return
166
-
167
- st.write(f"Fetching books on {', '.join(subjects)} published between {start_year} and {end_year}...")
168
- # Get books using the API (first page)
169
- books = fetch_books(subjects, start_year, end_year, page=1)
170
- if not books:
171
- st.write("No books found.")
172
- return
173
-
174
- # Convert list of books into a DataFrame
175
- df = pd.DataFrame(books)
176
- # Show a quick table of a few fields for context (if available)
177
- if not df.empty:
178
- st.write("API Results (first 10 rows):")
179
- display_cols = []
180
- for col in ['title', 'first_publish_year', 'author_name', 'key']:
181
- if col in df.columns:
182
- display_cols.append(col)
183
- st.dataframe(df[display_cols].head(10))
184
- else:
185
- st.write("No API results to display.")
186
- return
187
-
188
- # --- Pagination: Display 10 books per page ---
189
- per_page = 10
190
- total = len(df)
191
- if "page_index" not in st.session_state:
192
- st.session_state.page_index = 0
193
- page_index = st.session_state.page_index
194
-
195
- # Get current page of books
196
- current_df = df.iloc[page_index * per_page:(page_index + 1) * per_page]
197
- st.write(f"Showing results {page_index * per_page + 1} to {min((page_index + 1) * per_page, total)} out of {total}")
198
-
199
- # Iterate over current books, scrape details, and display them
200
- for i, row in current_df.iterrows():
201
- # The API returns a "key" field that gives the relative URL of the book page.
202
- book_key = row.get("key")
203
- if not book_key:
204
- continue
205
- details = scrape_book_details(book_key)
206
- st.markdown(f"### {details['title']}")
207
- st.write(f"**First Published:** {details['first_published']}")
208
- st.write(f"**Author(s):** {details['authors']}")
209
- if details["author_image"] != "Not available":
210
- st.image(details["author_image"], width=100)
211
- else:
212
- st.write("**Author Image:** Not available")
213
- if details["book_cover"] != "Not available":
214
- st.image(details["book_cover"], width=150)
215
- else:
216
- st.write("**Book Cover:** Not available")
217
- st.write(f"**Description:** {details['description']}")
218
- st.write("---")
219
 
220
- # Show "Show More" button if more results exist
221
- if (page_index + 1) * per_page < total:
222
- if st.button("Show More"):
223
- st.session_state.page_index += 1
224
- st.experimental_rerun()
225
 
226
- if __name__ == "__main__":
227
- main()
 
 
 
1
  import requests
2
  import pandas as pd
3
  from bs4 import BeautifulSoup
4
 
5
+ # Function to fetch book details from OpenLibrary
6
+ def fetch_book_details(book_url):
7
+ response = requests.get(f"https://openlibrary.org{book_url}")
8
+ soup = BeautifulSoup(response.text, 'html.parser')
9
+
10
+ # Get Title
11
+ title = soup.find('h1', {'class': 'work-title'}).text.strip() if soup.find('h1', {'class': 'work-title'}) else 'N/A'
12
+
13
+ # Get First Published Year
14
+ first_published = soup.find('span', {'class': 'first-published-date'}).text.strip() if soup.find('span', {'class': 'first-published-date'}) else 'N/A'
15
+
16
+ # Get Author(s)
17
+ authors = [a.text.strip() for a in soup.find_all('a', {'itemprop': 'author'})] if soup.find_all('a', {'itemprop': 'author'}) else ['N/A']
18
+
19
+ # Get Description
20
+ description = soup.find('div', {'class': 'book-description'}).text.strip() if soup.find('div', {'class': 'book-description'}) else 'N/A'
21
+
22
+ # Get Author Image (if available)
23
+ author_image = soup.find('img', {'class': 'author-avatar'})['src'] if soup.find('img', {'class': 'author-avatar'}) else 'N/A'
24
+
25
+ # Get Book Cover Image (if available)
26
+ book_cover = soup.find('img', {'class': 'cover'})['src'] if soup.find('img', {'class': 'cover'}) else 'N/A'
27
+
28
+ return {
29
+ 'Title': title,
30
+ 'First Published Year': first_published,
31
+ 'Authors': ", ".join(authors),
32
+ 'Description': description,
33
+ 'Author Image': author_image,
34
+ 'Book Cover': book_cover
35
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # Function to fetch books based on subjects and time frame
38
+ def fetch_books(subjects, time_frame):
39
+ # Example of how to fetch book URLs (This should be replaced with actual OpenLibrary search logic)
40
+ book_urls = [
41
+ '/works/OL14877868W/A_House_of_Pomegranates',
42
+ '/works/OL25684502W/Don_Quixote'
43
+ # Add more book URLs here
44
+ ]
45
 
46
+ books_data = []
47
+
48
+ for book_url in book_urls:
49
+ book_details = fetch_book_details(book_url)
50
+ books_data.append(book_details)
51
+
52
+ # Convert to DataFrame
53
+ books_df = pd.DataFrame(books_data)
54
+ return books_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ # Example: Get books for selected subjects and time frame
57
+ subjects = ['fiction', 'classic literature'] # Example subjects
58
+ time_frame = '1800-1900' # Example time frame
 
 
59
 
60
+ # Fetch books and show results
61
+ books_df = fetch_books(subjects, time_frame)
62
+ print(books_df) # This will display the dataframe without showing raw API results