isshagle's picture
Create app.py
1dae8e9
raw
history blame
No virus
2.84 kB
import pandas as pd
import gradio as gr
import matplotlib.pyplot as plt
import io
import base64
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
# Load your dataset
data = pd.read_csv('Blinkit Cart Prediction.csv')
# Create a TF-IDF vectorizer
tfidf_vectorizer = TfidfVectorizer(max_features=1000) # Adjust max_features as needed
tfidf_matrix = tfidf_vectorizer.fit_transform(data['Description'])
# Function to recommend products
def recommend_products(user_choice, num_recommendations=10):
# Transform the user choice using the same TF-IDF vectorizer
user_choice_vector = tfidf_vectorizer.transform([user_choice])
# Compute the cosine similarity between the user choice and all products
cosine_similarities = linear_kernel(user_choice_vector, tfidf_matrix)
# Get the indices of the most similar products
similar_indices = cosine_similarities.argsort()[0][-num_recommendations - 1:-1][::-1]
# Get the recommended product IDs and names
recommended_products = data.iloc[similar_indices][['ProductID', 'ProductName']]
return recommended_products
# Define the input and output components
input_component = gr.inputs.Textbox(label="Enter Your Choice")
output_component = gr.outputs.HTML(label="Recommended Products")
# Create the Gradio interface
def recommend_interface(user_choice):
recommended_products = recommend_products(user_choice)
# Create a bar graph of recommended products
plt.figure(figsize=(10, 6))
plt.bar(recommended_products['ProductName'], range(len(recommended_products)), color='skyblue')
plt.xticks(rotation=45, ha="right")
plt.xlabel("Recommended Products")
plt.ylabel("Ranking")
plt.title("Top Recommended Products")
# Encode the image as base64
buffer = io.BytesIO()
plt.savefig(buffer, format="png")
graph_base64 = base64.b64encode(buffer.getvalue()).decode()
plt.close()
# Create an HTML string with an embedded image
graph_html = f'<img src="data:image/png;base64,{graph_base64}" />'
# Create an HTML string for the table of recommended products
table_html = recommended_products.to_html(index=False)
# Concatenate the HTML strings for both components
result_html = f"<h2>Recommended Products:</h2>{table_html}<br>{graph_html}"
return result_html
# Launch the Gradio app
interface = gr.Interface(
fn=recommend_interface, inputs=input_component, outputs=output_component,
live = True,
description = " Press flag if any erroneous output comes ",
theme=gr.themes.Soft(),
title = "Blinkit Cart Prediction",
examples = [['necklace'],
['DSLR camera '],['tea '], ['Smart TV '] , ['protein bars'] , ['sunglasses '] ],
)
interface.launch(inline=False)