File size: 1,088 Bytes
5401983
 
 
 
 
 
 
 
 
3588e88
5401983
 
3588e88
5401983
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5821c5b
5401983
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#%%
import gradio as gr
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
import pandas as pd

# load resources
df = pd.read_csv('final_2.csv')
model = SentenceTransformer('all-MiniLM-L6-v2')


index = faiss.read_index('index_file.pkl')

# map each document ID to its index in the original dataframe
id_mapping = np.array(range(0, len(df)))

def search(query: str, k=3):
    query_vector = model.encode([query], convert_to_tensor=True)
    query_vector = query_vector / query_vector.norm()  # normalize for cosine similarity
    query_vector_np = query_vector.cpu().numpy()
    _, I = index.search(query_vector_np, k)
    return df.iloc[id_mapping[I[0]].tolist()]

 # return the results as a dictionary
def query(query:str):
    results = search(query)
    
    return results[['Title', 'Authors', 'BuyLink']].to_dict('records')

demo = gr.Interface(fn=query, inputs="text", outputs=gr.outputs.JSON(),
                     title='Suggest a Book',
                     description='No Titles! No Authors! Pour your heart out ♥')

demo.launch()


# %%