CoolFace
Apppublic

4d0T/Allocation-Model-Api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
api.py89 linesDownload Raw Back to root
1#!/usr/bin/env python32import os3import sys4from flask import Flask, request, jsonify5from flask_cors import CORS6import logging7from datetime import datetime8import gdown9import tempfile # Import the tempfile module10 11# Add current directory to path12current_dir = os.path.dirname(os.path.abspath(__file__))13if current_dir not in sys.path:14    sys.path.insert(0, current_dir)15 16# Logging17logging.basicConfig(level=logging.INFO)18logger = logging.getLogger(__name__)19 20# Import runner21try:22    from speed_optimized_runner import SpeedOptimizedSupabaseRunner23except ImportError as e:24    logger.error(f"Cannot import runner: {e}")25    sys.exit(1)26 27app = Flask(__name__)28CORS(app)29 30runner = None31 32def init_runner():33    """Initializes the runner by downloading the model and creating the instance."""34    global runner35    if runner is None:36        try:37            # Google Drive link for the model38            drive_url = 'https://drive.google.com/file/d/1ySUxfrQivGwoGffirbIaUGgNm-QaMgfg/view?usp=sharing'39            40            # --- FIX: Download to a writable temporary directory ---41            temp_dir = tempfile.gettempdir()42            model_path = os.path.join(temp_dir, 'allocation_model.pkl')43            # ---------------------------------------------------------44            45            # Download model from Google Drive46            logger.info(f"Downloading model to: {model_path}")47            # Use fuzzy=True to handle different Google Drive link formats48            gdown.download(drive_url, model_path, quiet=False, fuzzy=True)49            50            # Pass the correct model_path to the runner51            runner = SpeedOptimizedSupabaseRunner(model_path=model_path)52            logger.info("Runner initialized")53        except Exception as e:54            logger.error(f"Runner init error: {e}")55            raise e56 57# Gunicorn will run this code once when each worker process starts.58init_runner()59 60@app.route('/health', methods=['GET'])61def health():62    return jsonify({63        'status': 'healthy',64        'timestamp': datetime.now().isoformat(),65        'model_ready': runner is not None66    })67 68@app.route('/run-allocation', methods=['POST'])69def run_allocation():70    data = request.get_json() or {}71    internship_id = data.get('internship_id')72    if not internship_id:73        return jsonify({'success':False,'error':'Provide internship_id'}),40074    success = runner and runner.run_allocation_for_internship(internship_id)75    return jsonify({'success':bool(success),'internship_id':internship_id})76 77@app.route('/get-results/<internship_id>', methods=['GET'])78def get_results(internship_id):79    results = runner.fetch_table_data('results', {'InternshipID': internship_id})80    return jsonify({'success':True,'results':results,'count':len(results)})81 82@app.route('/list-internships', methods=['GET'])83def list_internships():84    ints = runner.fetch_table_data('internship')85    return jsonify({'success':True,'internships':ints,'count':len(ints)})86 87if __name__=='__main__':88    port = int(os.environ.get('PORT', 5000))89    app.run(host='0.0.0.0', port=port)