File size: 1,794 Bytes
6a8f68c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import gradio as gr
import random
import pandas as pd
from surprise import Dataset, Reader
from surprise import KNNBasic

def opendata(a, nrows):
    df = pd.read_csv(a, nrows=nrows, sep=';', encoding='ISO-8859-1')
    return df

def split(df):
    n=len(df)
    N=list(range(n))
    random.seed(2023)
    random.shuffle(N)
    train=df.iloc[N[0:(n*4)//5]]
    test=df.iloc[N[(n*4)//5:]]
    return train, test

def red(df):
    reader = Reader(rating_scale=(1,10)) # rating scale range
    trainset = Dataset.load_from_df(df[['User-ID','ISBN','Book-Rating']],reader).build_full_trainset()
    items = trainset.build_anti_testset()
    return trainset, items


def mod(df, user, items):
    algo = KNNBasic()
    algo.fit(df)
    user_items = list(filter(lambda x: x[0] == user, items))
    recommendations = algo.test(user_items)
    recommendations.sort(key=operator.itemgetter(3), reverse=True)
    return recommendations

def gl(num):
    data = opendata('Book reviews\BX-Book-Ratings.csv', nrows=20_000)
    books = opendata('Book reviews\BX_Books.csv', nrows=None)
    mapping_dict = books.set_index("ISBN")["Book-Title"].to_dict()
    train, test = split(data)
    users=test['User-ID'].tolist()
    trainset, items  = red(train)
    user = users[int(num)]
    recommendations = mod(trainset, user, items)
    op = []
    for r in recommendations[0:5]:
        try:  
            op.append(f"{mapping_dict[r[1]]} with Estimated Rating {round(r[3],3)}")
        except:
            continue
    return ('\n\n'.join(map(str, op)))

text = gr.components.Number(label="pick a number between 1 and 1000")
label = gr.components.Text(label="Picked User Top 5 Recommendations:")
example = [2, 3]

intf = gr.Interface(fn=gl, inputs=text, outputs=label, examples=example)
intf.launch(inline=False)