Download huggingface_app/app.py from douccana/FeedGenerator: direct link, hf CLI and curl.
- Browser
- Download file 7.89 kB
-
https://huggingface.co/douccana/FeedGenerator/resolve/main/huggingface_app/app.py
- Command line
-
hf download hf://douccana/FeedGenerator/huggingface_app/app.py
-
curl -L -o app.py https://huggingface.co/douccana/FeedGenerator/resolve/main/huggingface_app/app.py
7.89 kB
| import os | |
| import json | |
| import pickle | |
| import sys | |
| from pathlib import Path | |
| from typing import List, Dict, Any, Optional | |
| import requests | |
| from supabase import create_client, Client | |
| # Add the current directory to Python path | |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) | |
| # Import our recommendation functions | |
| from recommend import get_ai_recommendations, load_model | |
| from ai_reel_recommend import get_ai_reel_recommendations | |
| # Initialize Supabase client | |
| def get_supabase_client(): | |
| """Get Supabase client using environment variables.""" | |
| try: | |
| supabase_url = os.getenv('NEXT_PUBLIC_SUPABASE_URL') | |
| supabase_key = os.getenv('SUPABASE_SERVICE_KEY') | |
| if not supabase_url or not supabase_key: | |
| print("Supabase environment variables not found") | |
| return None | |
| supabase: Client = create_client(supabase_url, supabase_key) | |
| return supabase | |
| except Exception as e: | |
| print(f"Error creating Supabase client: {e}") | |
| return None | |
| # Load model once at startup | |
| model = None | |
| try: | |
| model_path = Path(__file__).parent / "trained_model.pkl" | |
| model = load_model(str(model_path)) | |
| print(f"Model loaded successfully: {type(model)}") | |
| except Exception as e: | |
| print(f"Could not load model: {e}") | |
| print("Using mock recommendation system") | |
| def predict_product_recommendations(user_id: str, top_n: int = 10, exclude_product_ids: Optional[List[int]] = None) -> Dict[str, Any]: | |
| """Generate product recommendations for a user.""" | |
| try: | |
| if model is None: | |
| return { | |
| "error": "Model not available", | |
| "recommendations": [], | |
| "count": 0 | |
| } | |
| recommendations = get_ai_recommendations(model, user_id, top_n, exclude_product_ids) | |
| return { | |
| "user_id": user_id, | |
| "recommendations": recommendations, | |
| "count": len(recommendations), | |
| "model_info": { | |
| "type": "SVD", | |
| "training_data": "user-item interactions with weighted actions" | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "error": f"Error generating recommendations: {str(e)}", | |
| "recommendations": [], | |
| "count": 0 | |
| } | |
| def predict_reel_recommendations(user_id: str, top_n: int = 10, exclude_reel_ids: Optional[List[int]] = None) -> Dict[str, Any]: | |
| """Generate reel recommendations for a user.""" | |
| try: | |
| if model is None: | |
| return { | |
| "error": "Model not available", | |
| "recommendations": [], | |
| "count": 0 | |
| } | |
| recommendations = get_ai_reel_recommendations(model, user_id, top_n, exclude_reel_ids) | |
| return { | |
| "user_id": user_id, | |
| "recommendations": recommendations, | |
| "count": len(recommendations), | |
| "model_info": { | |
| "type": "SVD", | |
| "training_data": "user-reel interactions with weighted actions" | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "error": f"Error generating recommendations: {str(e)}", | |
| "recommendations": [], | |
| "count": 0 | |
| } | |
| # Gradio interface | |
| import gradio as gr | |
| def create_interface(): | |
| """Create the Gradio interface for the recommendation system.""" | |
| def product_recommendations(user_id: str, top_n: int, exclude_ids: str): | |
| """Generate product recommendations.""" | |
| try: | |
| exclude_product_ids = None | |
| if exclude_ids.strip(): | |
| exclude_product_ids = [int(x.strip()) for x in exclude_ids.split(',') if x.strip().isdigit()] | |
| result = predict_product_recommendations(user_id, top_n, exclude_product_ids) | |
| return json.dumps(result, indent=2) | |
| except Exception as e: | |
| return json.dumps({"error": str(e)}, indent=2) | |
| def reel_recommendations(user_id: str, top_n: int, exclude_ids: str): | |
| """Generate reel recommendations.""" | |
| try: | |
| exclude_reel_ids = None | |
| if exclude_ids.strip(): | |
| exclude_reel_ids = [int(x.strip()) for x in exclude_ids.split(',') if x.strip().isdigit()] | |
| result = predict_reel_recommendations(user_id, top_n, exclude_reel_ids) | |
| return json.dumps(result, indent=2) | |
| except Exception as e: | |
| return json.dumps({"error": str(e)}, indent=2) | |
| # Create the interface | |
| with gr.Blocks(title="FeedGenerator - AI Recommendation System") as demo: | |
| gr.Markdown("# 🎯 FeedGenerator - AI Recommendation System") | |
| gr.Markdown("Generate personalized product and reel recommendations using SVD machine learning model.") | |
| with gr.Tab("Product Recommendations"): | |
| gr.Markdown("### Generate Product Recommendations") | |
| with gr.Row(): | |
| with gr.Column(): | |
| product_user_id = gr.Textbox(label="User ID", placeholder="Enter user ID") | |
| product_top_n = gr.Slider(minimum=1, maximum=50, value=10, step=1, label="Number of recommendations") | |
| product_exclude = gr.Textbox(label="Exclude Product IDs", placeholder="Comma-separated IDs (e.g., 1,2,3)") | |
| product_btn = gr.Button("Generate Product Recommendations", variant="primary") | |
| with gr.Column(): | |
| product_output = gr.JSON(label="Results") | |
| product_btn.click( | |
| fn=product_recommendations, | |
| inputs=[product_user_id, product_top_n, product_exclude], | |
| outputs=product_output | |
| ) | |
| with gr.Tab("Reel Recommendations"): | |
| gr.Markdown("### Generate Reel Recommendations") | |
| with gr.Row(): | |
| with gr.Column(): | |
| reel_user_id = gr.Textbox(label="User ID", placeholder="Enter user ID") | |
| reel_top_n = gr.Slider(minimum=1, maximum=50, value=10, step=1, label="Number of recommendations") | |
| reel_exclude = gr.Textbox(label="Exclude Reel IDs", placeholder="Comma-separated IDs (e.g., 1,2,3)") | |
| reel_btn = gr.Button("Generate Reel Recommendations", variant="primary") | |
| with gr.Column(): | |
| reel_output = gr.JSON(label="Results") | |
| reel_btn.click( | |
| fn=reel_recommendations, | |
| inputs=[reel_user_id, reel_top_n, reel_exclude], | |
| outputs=reel_output | |
| ) | |
| with gr.Tab("API Documentation"): | |
| gr.Markdown(""" | |
| ## API Endpoints | |
| ### Product Recommendations | |
| **POST** `/api/product-recommendations` | |
| ```json | |
| { | |
| "user_id": "123", | |
| "top_n": 10, | |
| "exclude_product_ids": [1, 2, 3] | |
| } | |
| ``` | |
| ### Reel Recommendations | |
| **POST** `/api/reel-recommendations` | |
| ```json | |
| { | |
| "user_id": "123", | |
| "top_n": 10, | |
| "exclude_reel_ids": [1, 2, 3] | |
| } | |
| ``` | |
| ## Environment Variables Required | |
| - `NEXT_PUBLIC_SUPABASE_URL`: Your Supabase URL | |
| - `SUPABASE_SERVICE_KEY`: Your Supabase service key | |
| """) | |
| return demo | |
| # Create and launch the interface | |
| if __name__ == "__main__": | |
| demo = create_interface() | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |