Spaces:
Runtime error
Runtime error
Download app.py from 12ongo/backendproject: direct link, hf CLI and curl.
- Browser
- Download file 2.66 kB
-
https://huggingface.co/spaces/12ongo/backendproject/resolve/main/app.py
- Command line
-
hf download hf://spaces/12ongo/backendproject/app.py
-
curl -L -o app.py https://huggingface.co/spaces/12ongo/backendproject/resolve/main/app.py
2.66 kB
| import os | |
| import joblib | |
| import pandas as pd | |
| from flask import Flask, request, jsonify | |
| sales_predictor_api = Flask("Sales Predictor") | |
| # Load the trained model pipeline | |
| MODEL_PATH = os.path.join("deployment_files", "sales_predictor.joblib") | |
| model = joblib.load(MODEL_PATH) | |
| def home(): | |
| return "Welcome to the Sales Prediction API!" | |
| def validate_and_make_dataframe(sales_data: dict) -> pd.DataFrame: | |
| """ | |
| Validate required fields and convert a single JSON payload to a DataFrame. | |
| """ | |
| required_fields = [ | |
| "Product_Weight", | |
| "Product_Sugar_Content", | |
| "Product_Allocated_Area", | |
| "Product_Type", | |
| "Product_MRP", | |
| "Store_Establishment_Year_Before_2005", | |
| "Store_Size", | |
| "Store_Location_City_Type", | |
| "Store_Type", | |
| ] | |
| missing = [f for f in required_fields if f not in sales_data] | |
| if missing: | |
| raise KeyError(f"Missing required fields: {', '.join(missing)}") | |
| sample = { | |
| "Product_Weight": sales_data["Product_Weight"], | |
| "Product_Sugar_Content": sales_data["Product_Sugar_Content"], | |
| "Product_Allocated_Area": sales_data["Product_Allocated_Area"], | |
| "Product_Type": sales_data["Product_Type"], | |
| "Product_MRP": sales_data["Product_MRP"], | |
| "Store_Establishment_Year_Before_2005": sales_data["Store_Establishment_Year_Before_2005"], | |
| "Store_Size": sales_data["Store_Size"], | |
| "Store_Location_City_Type": sales_data["Store_Location_City_Type"], | |
| "Store_Type": sales_data["Store_Type"], | |
| } | |
| return pd.DataFrame([sample]) | |
| def predict_sale(): | |
| try: | |
| sales_data = request.get_json(force=True, silent=False) | |
| input_df = validate_and_make_dataframe(sales_data) | |
| prediction = model.predict(input_df).tolist()[0] | |
| return jsonify({"Predicted_Sales": prediction}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 400 | |
| def predict_sale_batch(): | |
| try: | |
| file = request.files.get("file") | |
| if file is None: | |
| return jsonify({"error": "No file provided with form field 'file'"}), 400 | |
| input_df = pd.read_csv(file) | |
| predictions = model.predict(input_df).tolist() | |
| return jsonify({"Predicted_Sales": predictions}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 400 | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", "7860")) | |
| sales_predictor_api.run(host="0.0.0.0", port=port, debug=False) | |