What I’m trying to do: I am developing a machine learning model for school which recommends 5 books based on a book title that the user inputs. The model is ready in my Jupyter Notebook. Now I am trying to make the Webapp for it
What I’ve tried and what’s not working: I connected anvil with my notebook. I set up the code in Anvil, but I feel like I am missing a small detail. This is how the webapp works:
The user writes the book name, presses ENTER and the 5 recommended books should appear where “result_books” is, but it doesn’t. Instead, the results appear on my Jupyter notebook.
This is my notebook code: @anvil.server.callable
def reco(book_name):
book_id=np.where(book_pivot.index==book_name)[0][0]
distances,suggestions=model.kneighbors(book_pivot.iloc[book_id,:].values.reshape(1,-1))
for i in range(len(suggestions)):
if i==0:
print("the suggestions for ",book_name,"are : ")
if not i:
print(book_pivot.index[suggestions[i]])
This is my code in Anvil:
def name_box_pressed_enter(self, **event_args):
“”“This method is called when the user presses Enter in this text box”""
self.result_books.text = anvil.server.call(‘reco’, self.name_box.text)
I’m fairly new to this, and I think I’m missing a very small detail. Any help would be greatly appreciated.
Welcome! Formatting your python code like the post here describes would make it easier to follow.
I think you just need to have the ‘reco’ function ‘return’ the suggestions being printed out. That is, at the end of your function code, convert your suggestions list into a string and return that.
It looks like there is no return in your python function, so nothing is being returned to the Anvil app. You could try this:
@anvil.server.callable
def reco(book_name):
book_id=np.where(book_pivot.index==book_name)[0][0]
distances, suggestions = model.kneighbors(book_pivot.iloc[book_id,:].values.reshape(1,-1))
for i in range(len(suggestions)):
if i==0:
return f"The suggestions for {book_name} are: ")
if not i:
return book_pivot.index[suggestions[i]]
Thank you for your reply, but unfortunately that didn’t work either. I fiddled with the python code for a few hours and this is what gave me the result I wanted. Decided to share it incase someone else encounters a similar issue. All I did was convert the return function into a numpy array: