Team Ai
Apppublic

codexpawan/GNN

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py106 linesDownload Raw Back to root
1# app.py2from flask import Flask, request, jsonify3from predictor import EmbeddingPredictor4import torch5import numpy as np6from pathlib import Path7import os8 9app = Flask(__name__)10 11# Configuration (replacing Django settings.py)12class Config:13    BASE_DIR = Path(__file__).parent14    MODEL_DIR = BASE_DIR / 'model' / 'gnn'  # Changed from 'models' to 'model' to match your structure15    PORT = int(os.environ.get('PORT', 7860))  # Add port from environment16 17# Initialize predictor18try:19    predictor = EmbeddingPredictor(base_path=Config.MODEL_DIR)20except Exception as e:21    print(f"Failed to initialize predictor: {e}")22    raise23 24@app.route('/api/recommend', methods=['POST'])25def get_recommendations():26    """27    Endpoint to get movie recommendations for a user embedding28    29    Request body:30    {31        "user_embedding": [float, float, ...],  # User embedding vector32        "num_recommendations": int              # Optional, defaults to 533    }34    35    Response:36    {37        "success": bool,38        "recommendations": [39            {40                "movie_id": int,41                "predicted_rating": float,42                "movie_details": dict43            },44            ...45        ],46        "error": str (if applicable)47    }48    """49    try:50        # Get JSON data from request51        data = request.get_json()52        if not data or 'user_embedding' not in data:53            return jsonify({54                'success': False,55                'error': 'Missing user_embedding in request body'56            }), 40057 58        user_embedding = data['user_embedding']59        num_recommendations = data.get('num_recommendations', 5)60 61        # Validate input62        if not isinstance(user_embedding, list):63            return jsonify({64                'success': False,65                'error': 'user_embedding must be a list'66            }), 40067            68        if not isinstance(num_recommendations, int) or num_recommendations <= 0:69            return jsonify({70                'success': False,71                'error': 'num_recommendations must be a positive integer'72            }), 40073 74        # Get predictions75        recommendations = predictor.predict_for_embedding(76            user_embedding=user_embedding,77            num_recommendations=num_recommendations78        )79 80        # Format response81        response = []82        for movie_id, rating in recommendations:83            # movie_details = predictor.get_movie_details(movie_id)84            response.append({85                'movie_id': int(movie_id),86                'predicted_rating': float(rating)87            })88 89        return jsonify({90            'success': True,91            'recommendations': response92        }), 20093 94    except Exception as e:95        return jsonify({96            'success': False,97            'error': str(e)98        }), 50099 100@app.route('/health', methods=['GET'])101def health_check():102    """Health check endpoint"""103    return jsonify({104        'success': True,105        'message': 'Server is running'106    }), 200