Spaces:
Sleeping
Sleeping
Download app_backend.py from agawale/SalesPredictionBackend: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/spaces/agawale/SalesPredictionBackend/resolve/main/app_backend.py
- Command line
-
hf download hf://spaces/agawale/SalesPredictionBackend/app_backend.py
-
curl -L -o app_backend.py https://huggingface.co/spaces/agawale/SalesPredictionBackend/resolve/main/app_backend.py
2.31 kB
| # Import necessary libraries | |
| import numpy as np | |
| import joblib | |
| import pandas as pd | |
| from flask import Flask, request, jsonify | |
| # Initialize Flask app | |
| sales_predictor_api = Flask("SuperKart Sales Predictor") | |
| # Load trained model | |
| model = joblib.load("product_store_sales_prediction_model_v1_0.joblib") | |
| # Home route | |
| def home(): | |
| """ | |
| Handles GET requests to root URL. | |
| """ | |
| return "Welcome to the SuperKart Sales Prediction API!" | |
| # Single prediction endpoint | |
| def predict_sales(): | |
| """ | |
| Handles POST requests to predict sales for a single product/store. | |
| """ | |
| # Get JSON payload | |
| sales_data = request.get_json() | |
| # Extract required features | |
| sample = { | |
| "Product_Weight": sales_data["Product_Weight"], | |
| "Product_MRP": sales_data["Product_MRP"], | |
| "Store_Id": sales_data["Store_Id"], | |
| "Store_Size": sales_data["Store_Size"], | |
| "Store_Location_City_Type": sales_data["Store_Location_City_Type"], | |
| "Store_Type": sales_data["Store_Type"], | |
| "Product_Id_char": sales_data["Product_Id_char"], | |
| "Product_Type": sales_data["Product_Type"], | |
| "Store_Age": sales_data["Store_Age"] | |
| } | |
| # Convert to DataFrame | |
| input_data = pd.DataFrame([sample]) | |
| # Predict sales | |
| predicted_sales = model.predict(input_data)[0] | |
| # Convert to float for JSON response | |
| predicted_sales = round(float(predicted_sales), 2) | |
| # Return prediction | |
| return jsonify({"Predicted Store Sales": predicted_sales}) | |
| # Batch prediction endpoint | |
| def predict_sales_batch(): | |
| """ | |
| Handles batch predictions using uploaded CSV file. | |
| """ | |
| # Get uploaded CSV | |
| file = request.files['file'] | |
| # Read CSV | |
| input_data = pd.read_csv(file) | |
| # Make predictions | |
| predicted_sales = model.predict(input_data).tolist() | |
| # Convert predictions to float | |
| predicted_sales = [round(float(s), 2) for s in predicted_sales] | |
| # Optional: assume first column is ID | |
| ids = input_data.iloc[:, 0].tolist() | |
| # Create output dictionary | |
| output_dict = dict(zip(ids, predicted_sales)) | |
| return output_dict | |
| # Run the Flask app | |
| if __name__ == '__main__': | |
| sales_predictor_api.run(debug=True) | |