Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import pandas as pd | |
| from surprise import SVD, Dataset, Reader | |
| from src.data_preprocessing import load_parquet_data | |
| from src.collaborative_filtering import train_user_based_cf, get_top_n_recommendations | |
| # Load and preprocess sample data | |
| df_raw = pd.read_csv("train_sample.csv") | |
| df_raw['user_id'] = df_raw['user_id'].astype(int) | |
| df_raw['product_id'] = df_raw['product_id'].astype(str) | |
| # Train the collaborative filtering model using SVD | |
| algo, df_clean = train_user_based_cf(df_raw, algorithm=SVD(), show_rmse=True) | |
| # Generate top-N recommendations for all users | |
| top_n = get_top_n_recommendations(algo, df_clean, n=5) | |
| def recommend(user_id_input): | |
| try: | |
| user_id = int(float(user_id_input)) # Converts strings or floats safely | |
| except ValueError: | |
| return "β Invalid user ID format." | |
| if user_id not in top_n: | |
| return "π« User not found or not enough data." | |
| recs = top_n[user_id] | |
| return "\n".join([f"π Product {pred.iid} (predicted rating: {pred.est:.3f})" for pred in recs]) | |
| # Build Gradio UI | |
| with gr.Blocks() as demo: | |
| gr.Markdown("π **E-commerce Recommender (SVD)**") | |
| gr.Markdown("Enter a user ID to get top-5 product recommendations using collaborative filtering (SVD).") | |
| with gr.Row(): | |
| user_id_input = gr.Textbox(label="Enter User ID", placeholder="e.g., 553033744") | |
| output = gr.Textbox(label="Top 5 Recommendations") | |
| with gr.Row(): | |
| clear_btn = gr.Button("Clear") | |
| submit_btn = gr.Button("Submit") | |
| submit_btn.click(fn=recommend, inputs=user_id_input, outputs=output) | |
| clear_btn.click(fn=lambda: ("", ""), inputs=[], outputs=[user_id_input, output]) | |
| if __name__ == "__main__": | |
| demo.launch() | |