import pandas as pd import gradio as gr from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel from groq import Groq # Sample data for products data = { 'product_id': [1, 2, 3, 4, 5], 'name': ['Laptop', 'Smartphone', 'Headphones', 'Smartwatch', 'Tablet'], 'description': [ 'A high-performance laptop with 16GB RAM and 512GB SSD.', 'A latest-gen smartphone with excellent camera quality.', 'Noise-cancelling over-ear headphones.', 'A smartwatch with various health tracking features.', 'A tablet with a 10-inch display and long battery life.' ] } # Initialize Groq client api_key = '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' client = Groq(api_key=api_key) # Create DataFrame products_df = pd.DataFrame(data) # Vectorizing the product descriptions tfidf = TfidfVectorizer(stop_words='english') tfidf_matrix = tfidf.fit_transform(products_df['description']) # Compute the cosine similarity matrix cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) # Function to get product recommendations def get_recommendations(product_name, cosine_sim=cosine_sim): idx = products_df[products_df['name'] == product_name].index[0] sim_scores = list(enumerate(cosine_sim[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:4] # Get top 3 recommendations product_indices = [i[0] for i in sim_scores] return products_df.iloc[product_indices] # Function to fetch descriptions from Groq based on product names def fetch_descriptions(product_names): descriptions = [] try: for product_name in product_names: chat_completion = client.chat.completions.create( messages=[ { "role": "user", "content": f"Generate description for {product_name}", } ], model="llama3-8b-8192", ) description = chat_completion.choices[0].message.content.strip() descriptions.append((product_name, description)) except Exception as e: descriptions.append((product_name, f"Description fetch failed: {str(e)}")) return descriptions # Function to format description in organized manner def format_description(product_name, description): formatted_description = ( f"**{product_name}:**\n\n" f"{description}\n\n" ) return formatted_description # Function to recommend products and fetch descriptions def recommend_products(product_name): recommended_products_df = get_recommendations(product_name) recommended_product_names = recommended_products_df['name'].tolist() recommended_product_descriptions = fetch_descriptions(recommended_product_names) # Combine product names and descriptions for output recommendations_with_descriptions = [ format_description(name, desc) for name, desc in recommended_product_descriptions ] return '\n'.join(recommendations_with_descriptions) # Define Gradio interface iface = gr.Interface( fn=recommend_products, inputs=gr.Dropdown(choices=products_df['name'].tolist(), label="Select a product"), outputs=gr.Textbox(label="Recommended Products with Descriptions", type="text"), title="AI-driven E-commerce Recommendation Engine", description="Select a product to get recommendations along with their descriptions." ) # Launch the Gradio interface iface.launch()