hii. I tried it and it worked, thank you so much. but I have another problem; it doesn’t update the value of the slider even when I move it from 0. I move it to 5 for example, it stores it as 0 in the session state.
//code\
Create a SessionState object
class SessionState:
def init(self, **kwargs):
self.dict.update(kwargs)
Initialize session state
def init_session_state():
if “session_state” not in st.session_state:
st.session_state[“session_state”] = SessionState(
favorites=,
ratings={},
username=None,
login_successful=False
)
return st.session_state[“session_state”]
Retrieve or create session state
session_state = init_session_state()
Function to add a book to favorites
def add_to_favorites(book):
if book not in session_state.favorites:
session_state.favorites.append(book)
st.session_state[“session_state”] = session_state # Update session state
st.success(f"Book ‘{book}’ added to favorites.“)
else:
st.warning(f"Book ‘{book}’ is already in favorites.”)
# Store favorites in session state
st.session_state["favorites"] = session_state.favorites
Function to recommend books based on a selected book
def recommend_book(book_name):
books_list =
book_id = np.where(book_pivot.index == book_name)[0][0]
distance, suggestion = model.kneighbors(book_pivot.iloc[book_id, :].values.reshape(1, -1), n_neighbors=6)
poster_url = fetch_poster(suggestion)
isbn_list = final_rating.iloc[suggestion[0]]['ISBN'].values.tolist()
for i in range(len(suggestion)):
books = book_pivot.index[suggestion[i]]
for j in books:
books_list.append(j)
return books_list, poster_url, isbn_list
Function to store a book rating in the database
def store_rating(isbn, rating, book_index):
try:
# Connect to the database
conn = psycopg.connect(
host=host,
port=port,
dbname=dbname,
user=user,
password=password
)
# Create a cursor
cur = conn.cursor()
# Get the username from the session state
username = session_state.username
# Check if the user already exists in the userlist table
cur.execute("SELECT username FROM bbdatabase.userlist WHERE username = %s", (username,))
existing_user = cur.fetchone()
if existing_user:
# Check if the rating already exists for the user and book
cur.execute("SELECT * FROM bbdatabase.ratings WHERE userid = %s AND isbn = %s", (username, isbn))
existing_rating = cur.fetchone()
if existing_rating:
# Update the existing rating
cur.execute("UPDATE bbdatabase.ratings SET rating = %s WHERE userid = %s AND isbn = %s",
(rating, username, isbn))
st.success("Rating updated successfully.")
else:
# Insert a new rating
cur.execute("INSERT INTO bbdatabase.ratings(rating, userid, isbn) VALUES (%s, %s, %s)",
(rating, username, isbn))
st.success("Rating stored successfully.")
else:
st.error("User does not exist.")
# Commit the changes
conn.commit()
# Update session state
print("ISBN:", isbn)
print("Rating:", rating)
print("Book Index:", book_index)
session_state.ratings[book_index] = rating
# Update session state
# session_state.ratings[book_index] = rating
#st.session_state["session_state"] = session_state # Update session state
#st.session_state["ratings"] = session_state.ratings # Update ratings in session state
#session_state.ratings[book_index.item()] = rating
session_state.ratings[int(isbn)] = rating
st.session_state["session_state"] = session_state # Update session state
st.session_state["ratings"] = session_state.ratings # Update ratings in session state
except (psycopg.Error, psycopg.DatabaseError) as e:
st.error(f"Error storing rating: {e}")
finally:
# Close the cursor and connection
cur.close()
conn.close()
Function to get the rating for a book
def get_rating(isbn):
return session_state.ratings.get(str(isbn), 0)
Update session state to store ratings
if “ratings” not in st.session_state:
st.session_state[“ratings”] = {}