anas-ahmed/Library
2
1import streamlit as st2import pymongo3from datetime import date, timedelta4import sys5import base646from io import BytesIO7from PIL import Image8 9st.set_page_config(10 page_title="Library Management System",11 layout="wide",12 initial_sidebar_state="expanded",13 page_icon="๐"14)15 16st.markdown("""17 <style>18 .stButton button {19 width: 100%;20 }21 .metrics-container {22 display: flex;23 justify-content: space-around;24 margin: 20px 0;25 }26 .book-status-available {27 color: green;28 font-weight: bold;29 }30 .book-status-issued {31 color: red;32 font-weight: bold;33 }34 </style>""", 35 unsafe_allow_html=True)36 37 38def connect_to_database():39 connection_string = st.secrets["MONGO_URI"]40 # connection_string = "mongodb+srv://<username>:<password>@digitallibrary.a6oks.mongodb.net/?retryWrites=true&w=majority&appName=DigitalLibrary"41 try:42 client = pymongo.MongoClient(connection_string)43 db = client["LibraryDB"]44 return client, db45 except pymongo.errors.ConnectionError:46 st.error("Error: Could not connect to database")47 sys.exit(1)48 49def home_page(db):50 st.title("๐ Library Management System")51 52 col1, col2, col3= st.columns(3,)53 54 total_books = db.books.count_documents({})55 available_books = db.books.count_documents({"availability": "Available"})56 issued_books = db.issuedBooks.count_documents({})57 58 with col1:59 st.metric("Total Books", total_books)60 with col2:61 st.metric("Available Books", available_books)62 with col3:63 st.metric("Issued Books", issued_books)64 65 st.markdown("---")66 col1, col2 = st.columns(2)67 68 with col1:69 st.markdown("### ๐ Recently Added Books")70 recent_books = list(db.books.find().sort("_id", -1).limit(5))71 if recent_books:72 for book in recent_books:73 with st.expander(f"{book['bookName']}"):74 st.write(f"๐๏ธ Author: {book['authorName']}")75 st.write(f"๐ ISBN: {book['isbn']}")76 st.write(f"๐ Genre: {book['genre']}")77 st.write(f"๐
Published: {book['publication_year']}")78 status_color = "green" if book['availability'] == "Available" else "red"79 st.markdown(f"Status: <span style='color:{status_color}'>{book['availability']}</span>", 80 unsafe_allow_html=True)81 else:82 st.info("No books added recently")83 84 with col2:85 st.markdown("### ๐ Recently Issued Books")86 recent_issues = list(db.issuedBooks.find().sort("_id", -1).limit(5))87 if recent_issues:88 for book in recent_issues:89 with st.expander(f"{book['bookName']}"):90 st.write(f"๐ค Borrowed by: {book['name']}")91 st.write(f"๐ Contact: {book['phone']}")92 st.write(f"๐
Due Date: {book['dateDue']}")93 else:94 st.info("No recent book issues")95 96def add_book(db):97 st.header("Add New Book")98 with st.form("add_book_form"):99 bookName = st.text_input("Book Name")100 authorName = st.text_input("Author Name")101 isbn = st.text_input("ISBN")102 genre = st.selectbox("Genre", [103 "Fiction", "Non-Fiction", "Science Fiction", "Mystery", 104 "Romance", "Fantasy", "Biography", "History", "Science", 105 "Technology", "Other"106 ])107 publication_year = st.number_input("Publication Year", 108 min_value=1800, 109 max_value=date.today().year,110 value=date.today().year)111 cover_image = st.file_uploader("Upload Book Cover", type=['jpg', 'jpeg', 'png'])112 113 submitted = st.form_submit_button("Add Book")114 115 if submitted:116 if not bookName or not authorName or not isbn:117 st.error("Please fill all fields")118 elif not isbn.isdigit():119 st.error("Error: ISBN must be numeric")120 elif db.books.find_one({"isbn": isbn}):121 st.error("Error: Book with this ISBN already exists")122 else:123 image_data = None124 if cover_image is not None:125 img = Image.open(cover_image)126 max_width = 800127 if img.size[0] > max_width:128 ratio = max_width / img.size[0]129 new_size = (max_width, int(img.size[1] * ratio))130 img = img.resize(new_size)131 buffered = BytesIO()132 img.save(buffered, format="JPEG")133 image_data = base64.b64encode(buffered.getvalue()).decode()134 135 book_doc = {136 "bookName": bookName,137 "authorName": authorName,138 "isbn": isbn,139 "genre": genre, # Add genre140 "publication_year": publication_year, # Add publication year141 "availability": "Available",142 "cover_image": image_data,143 "dateAdded": date.today().isoformat()144 }145 146 db.books.insert_one(book_doc)147 st.success("Book added successfully!")148 149 150def view_books(db):151 st.header("Books in Library")152 153 col1, col2, col3 = st.columns([2, 1, 1])154 with col1:155 search = st.text_input("๐ Search by book name or author")156 with col2:157 status_filter = st.selectbox("Filter by status", ["All", "Available", "Issued"])158 with col3:159 genre_filter = st.selectbox("Filter by genre", ["All", "Fiction", "Non-Fiction", 160 "Science Fiction", "Mystery", "Romance", "Fantasy", "Biography", 161 "History", "Science", "Technology", "Other"])162 163 query = {}164 if search:165 query["$or"] = [166 {"bookName": {"$regex": search, "$options": "i"}},167 {"authorName": {"$regex": search, "$options": "i"}}168 ]169 if status_filter != "All":170 query["availability"] = status_filter171 if genre_filter != "All":172 query["genre"] = genre_filter173 174 books = list(db.books.find(query))175 if not books:176 st.info("No books found matching your criteria")177 else:178 cols = st.columns(3)179 for idx, book in enumerate(books):180 with cols[idx % 3]:181 with st.expander(f"{book['bookName']}",expanded=True):182 if book.get('cover_image'):183 st.image(184 f"data:image/jpeg;base64,{book['cover_image']}", 185 caption=book['bookName'],186 use_container_width=True187 )188 else:189 st.info("๐ธ - Image not found!")190 191 st.write(f"Author: {book['authorName']}")192 st.write(f"ISBN: {book['isbn']}")193 st.write(f"Genre: {book['genre']}")194 st.write(f"Publication Year: {book['publication_year']}")195 status_color = "green" if book['availability'] == "Available" else "red"196 st.markdown(197 f"Status: <span style='color:{status_color}'>{book['availability']}</span>", 198 unsafe_allow_html=True199 )200 201 202def issue_book(db):203 st.header("Issue Book")204 205 available_books = list(db.books.find({"availability": "Available"}))206 207 if not available_books:208 st.warning("No books are currently available for issuing.")209 return210 211 book_options = [f"{book['bookName']} - {book['authorName']} (ISBN: {book['isbn']})" for book in available_books]212 213 book_options.insert(0, "Select a book")214 selected_book = st.selectbox("Select Book to Issue", book_options)215 216 if selected_book != "Select a book":217 # Extract ISBN from the selected option218 isbn = selected_book.split("ISBN: ")[-1][:-1] # Remove the closing parenthesis219 220 book = db.books.find_one({"isbn": isbn})221 222 col1, col2 = st.columns(2)223 with col1:224 if book.get('cover_image'):225 st.image(226 f"data:image/jpeg;base64,{book['cover_image']}", 227 caption=book['bookName'],228 )229 with col2:230 st.write(f"**Author:** {book['authorName']}")231 st.write(f"**ISBN:** {book['isbn']}")232 st.write(f"**Genre:** {book['genre']}")233 st.write(f"**Publication Year:** {book['publication_year']}")234 235 with st.form("issue_book_form"):236 st.markdown("### Borrower Details")237 name = st.text_input("Borrower's Name")238 email = st.text_input("Borrower's Email")239 phone = st.text_input("Borrower's Phone")240 for_days = st.slider("Number of days to issue", 1, 30, 7)241 242 submitted = st.form_submit_button("Issue Book")243 244 if submitted:245 if not all([name, email, phone]):246 st.error("Please fill all borrower details")247 else:248 book = db.books.find_one({"isbn": isbn})249 if not book:250 st.error("Book not found")251 elif book.get("availability") != "Available":252 st.error("Book is no longer available")253 else:254 dateIssued = date.today()255 dateDue = dateIssued + timedelta(days=for_days)256 257 db.issuedBooks.insert_one({258 "bookName": book["bookName"],259 "authorName": book["authorName"],260 "isbn": isbn,261 "genre": book.get("genre", "Not specified"), # Add genre262 "publication_year": book.get("publication_year", "Not specified"), # Add publication year263 "name": name,264 "email": email,265 "phone": phone,266 "dateIssued": dateIssued.strftime("%d/%m/%Y"),267 "dateDue": dateDue.strftime("%d/%m/%Y")268 })269 270 db.books.update_one(271 {"isbn": isbn},272 {"$set": {"availability": "Issued"}}273 )274 275 st.success("Book issued successfully!")276 277 st.markdown("### Issue Details")278 st.write(f"Book: {book['bookName']}")279 st.write(f"Issued to: {name}")280 st.write(f"Issue Date: {dateIssued.strftime('%d/%m/%Y')}")281 st.write(f"Due Date: {dateDue.strftime('%d/%m/%Y')}")282 283 284def return_book(db):285 st.header("Return Book")286 isbn = st.text_input("Enter ISBN of book to return")287 if isbn:288 issued_book = db.issuedBooks.find_one({"isbn": isbn})289 if issued_book:290 st.write("Book Details:")291 st.write(f"Book Name: {issued_book['bookName']}")292 st.write(f"Borrowed by: {issued_book['name']}")293 st.write(f"Due Date: {issued_book['dateDue']}")294 295 if st.button("Confirm Return"):296 db.issuedBooks.delete_one({"isbn": isbn})297 db.books.update_one(298 {"isbn": isbn},299 {"$set": {"availability": "Available"}}300 )301 st.success("Book returned successfully!")302 else:303 st.error("This book is not issued")304 305def view_issued_books(db):306 st.header("Issued Books")307 if db.issuedBooks.count_documents({}) == 0:308 st.info("No books are currently issued")309 else:310 search = st.text_input("๐ Search by borrower name or book name")311 query = {}312 if search:313 query["$or"] = [314 {"name": {"$regex": search, "$options": "i"}},315 {"bookName": {"$regex": search, "$options": "i"}}316 ]317 318 for book in db.issuedBooks.find(query):319 with st.expander(f"{book['bookName']} - {book['isbn']}"):320 st.write(f"Author: {book['authorName']}")321 st.write(f"ISBN: {book['isbn']}")322 st.write(f"Genre: {book.get('genre', 'Not specified')}")323 st.write(f"Publication Year: {book.get('publication_year', 'Not specified')}")324 st.write(f"Borrowed by: {book['name']}")325 st.write(f"Contact: {book['phone']}")326 st.write(f"Issue Date: {book['dateIssued']}")327 st.write(f"Due Date: {book['dateDue']}")328 329def delete_book(db):330 st.header("Delete Book")331 isbn = st.text_input("Enter ISBN of book to delete")332 if isbn:333 book = db.books.find_one({"isbn": isbn})334 if book:335 st.write("Book Details:")336 st.write(f"Book Name: {book['bookName']}")337 st.write(f"Author: {book['authorName']}")338 339 if book.get("availability") == "Issued":340 st.error("Cannot delete: Book is currently issued")341 elif st.button("Confirm Delete",disabled=True):342 db.books.delete_one({"isbn": isbn})343 st.success("Book deleted successfully!")344 else:345 st.error("Book not found")346 347def main():348 _ , db = connect_to_database()349 350 st.sidebar.title("Navigation")351 352 if 'page' not in st.session_state:353 st.session_state.page = 'home'354 355 if st.sidebar.button("Home"):356 st.session_state.page = 'home'357 if st.sidebar.button("โ Add Book"):358 st.session_state.page = 'add_book'359 if st.sidebar.button("๐ View Books"):360 st.session_state.page = 'view_books'361 if st.sidebar.button("๐ Issue Book"):362 st.session_state.page = 'issue_book'363 if st.sidebar.button("โฉ๏ธ Return Book"):364 st.session_state.page = 'return_book'365 if st.sidebar.button("๐ View Issued Books"):366 st.session_state.page = 'view_issued'367 if st.sidebar.button("๐๏ธ Delete Book"):368 st.session_state.page = 'delete_book'369 370 if st.session_state.page == 'home':371 home_page(db)372 elif st.session_state.page == 'add_book':373 add_book(db)374 elif st.session_state.page == 'view_books':375 view_books(db)376 elif st.session_state.page == 'issue_book':377 issue_book(db)378 elif st.session_state.page == 'return_book':379 return_book(db)380 elif st.session_state.page == 'view_issued':381 view_issued_books(db)382 elif st.session_state.page == 'delete_book':383 delete_book(db)384 385 st.sidebar.markdown("---")386 st.sidebar.info("Developed with โค๏ธ by Anas Ahmed")387 388if __name__ == "__main__":389 main()390 