File size: 3,979 Bytes
bf41edb 9b5e746 b23a502 9b5e746 bf41edb 9b5e746 bf41edb 9b5e746 bf41edb 9b5e746 bf41edb 9b5e746 b23a502 9b5e746 b23a502 9b5e746 b23a502 9b5e746 b23a502 9b5e746 b23a502 9b5e746 b23a502 | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | """
import gradio as gr
def greet(name):
return "Hello " + name + "!!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()"""
import gradio as gr
import pandas as pd
import torch
from sentence_transformers import SentenceTransformer, util
import google.generativeai as genai
import pathlib
import textwrap
from IPython.display import display
from IPython.display import Markdown
import time
# 1. Initialization - Load Data and Set Up model
url = 'https://raw.githubusercontent.com/TRASJEPS/Vinicunca_AI_Project1/refs/heads/main/_Data-20241116T221029Z-001/Data/Cleaned%20Data/Combined%20Cleaned%20Data.csv'
df = pd.read_csv(url)
# Combine relevant columns
df["combined"] = (
"Product Name: " + df.Product_Name.str.strip()+"; Brand: " + df.Brand.str.strip()
+ "; Category: " + df.Product_Category.str.strip()
+ "; Details: " + df.Product_Details.str.strip()
+ "; Ingredients: " + df.Ingredients.str.strip()
+ "; Price: " + df["Cleaned Price"].str.strip()
# +"; desc: "+ df.text.str.strip()
)
# Ensure the 'combined' column has no NaN or invalid values
df['combined'] = df['combined'].fillna('')
# Check that all values are strings
df['combined'] = df['combined'].astype(str)
# Convert the combined column to lowercase for consistency
df_combined = df.copy()
df_combined['combined'] = df_combined['combined'].str.lower()
# Load embedding model and move to GPU if available
model = SentenceTransformer('all-MiniLM-L6-v2')
if torch.cuda.is_available():
modle = model.to('cuda')
# Create embeddings for all products once at the start
df['embeddings'] = df['combined'].apply(lambda x: model.encode(x))
df["embedding"] = df.combined.apply(lambda x: model.encode(x))
# 2. Define the Search Function for Gradio
def gradio_search(query):
# Set the number of results to display
n = 3
# Embed the user query
query_embedding = model.encode(query)
# Calculate similarity
df["similarity"] = df.embedding.apply(lambda x: util.cos_sim(x, query_embedding).item())
# Sort by similarity and return the top 'n' results
results = df.sort_values("similarity", ascending=False).head(n)
resultlist = []
# Collect results in a simple format
for r in results.index:
resultlist.append({
"Product Name": results.Product_Name[r],
"Score": results.similarity[r],
"Category": results.Product_Category[r],
"Price": results["Cleaned Price"][r],
"Details": results.Product_Details[r],
"Ingredients": results.Ingredients[r]
})
return resultlist
# 3. Maintain History for Multi-Turn Conversations
def chatbot_response(history, query):
history.append(("User", query)) # Log user input
results = gradio_search(query)
if len(results) == 0:
reply = "I couldn't find any matching products. Could you provide more details or rephrase your request?"
else:
reply = "\n".join([f"Product: {r['Product Name']}\nCategory: {r['Category']}\nPrice: {r['Price']}\nDetails: {r['Details']}\n" for r in results])
history.append(("Vinuca", reply)) # Log bot response
return history, reply
# 4. Set up the Gradio Interface
with gr.Blocks(title="Vinuca AI") as iface:
gr.Markdown("# Vinuca AI, Your Personal Haircare Assistant")
chatbot = gr.Chatbot()
user_input = gr.Textbox(placeholder="Ask me about haircare products...")
clear = gr.Button("Clear")
history = []
def interact(query):
global history
history, reply = chatbot_response(history, query)
return history
user_input.submit(interact, user_input, chatbot)
clear.click(lambda: [], None, chatbot)
"""iface = gr.Interface(
fn=gradio_search,
inputs="text",
outputs="json",
title="Ulta Hair Recommendation Search",
description="Enter your preferences to find matching products!"
)"""
# 4. Run the App
if __name__ == "__main__":
iface.launch()
|