CoolFace
Apppublic

GouravDeepak/Mark3

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py84 linesDownload Raw Back to root
1# app.py2import os3import numpy as np4import joblib5import tensorflow as tf6from flask import Flask, request, jsonify, render_template7 8app = Flask(__name__)9 10# --- Configuration & Setup ---11BASE_DIR = os.path.dirname(os.path.abspath(__file__))12MODEL_PATH = os.path.join(BASE_DIR, 'baccarat_lstm_rich_model.h5') 13SCALER_PATH = os.path.join(BASE_DIR, 'rich_model_scaler.pkl') # Path to the saved scaler14SEQUENCE_LENGTH = 1015 16label_map = {"Player": 0, "Banker": 1, "Tie": 2}17inv_label_map = {v: k for k, v in label_map.items()}18 19# --- Load Model and Scaler ---20model = None21scaler = None22try:23    model = tf.keras.models.load_model(MODEL_PATH)24    scaler = joblib.load(SCALER_PATH)25    print("✅ Rich LSTM model and data scaler loaded successfully.")26    # Warm up the model27    dummy_input = np.zeros((1, SEQUENCE_LENGTH, 4)) # Samples, Timesteps, Features28    model.predict(dummy_input)29    print("✅ Model warmed up.")30except Exception as e:31    print(f"❌ CRITICAL ERROR: Could not load model or scaler. Error: {e}")32 33# --- Flask Routes ---34@app.route('/')35def index():36    return render_template('index.html')37 38@app.route('/predict_rich_sequence', methods=['POST'])39def predict_rich_sequence():40    if not model or not scaler:41        return jsonify({'error': 'AI model or data scaler is not loaded.'}), 50342 43    try:44        # The frontend will now send a list of 10 hand objects45        sequence_data = request.json.get('sequence', [])46 47        if len(sequence_data) != SEQUENCE_LENGTH:48            return jsonify({'error': f'Exactly {SEQUENCE_LENGTH} hands are required.'}), 40049 50        # 1. Prepare the feature list from the input data51        feature_list = []52        for hand in sequence_data:53            winner_int = label_map[hand['winner']]54            features = [55                int(hand['player_total']),56                int(hand['banker_total']),57                int(bool(hand['natural_win'])),58                winner_int59            ]60            feature_list.append(features)61 62        # 2. Scale the features using the loaded scaler63        scaled_features = scaler.transform(feature_list)64        65        # 3. Reshape for the LSTM model66        X_pred = np.array([scaled_features]) # Wrap in a list to create a "batch" of 167 68        # 4. Make prediction69        probabilities = model.predict(X_pred)[0]70        predicted_int = np.argmax(probabilities)71        prediction_label = inv_label_map[predicted_int]72        confidence = probabilities[predicted_int] * 10073 74        return jsonify({75            'prediction': prediction_label,76            'confidence': f"{confidence:.2f}%",77            'based_on': 'AI model (Rich LSTM)'78        })79 80    except Exception as e:81        return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 50082 83if __name__ == '__main__':84    app.run(debug=True)