Himadri1102 commited on
Commit
dd28508
·
verified ·
1 Parent(s): a2d165a

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +55 -82
app.py CHANGED
@@ -1,93 +1,66 @@
1
  # Import necessary libraries
2
  import numpy as np
3
- import joblib # For loading the serialized model
4
- import pandas as pd # For data manipulation
5
- from flask import Flask, request, jsonify # For creating the Flask API
 
6
 
7
  # Initialize the Flask application
8
- rental_price_predictor_api = Flask("Airbnb Rental Price Predictor")
9
 
10
  # Load the trained machine learning model
11
- model = joblib.load("rental_price_prediction_model_v1_0.joblib")
 
12
 
13
- # Define a route for the home page (GET request)
14
- @rental_price_predictor_api.get('/')
15
- def home():
16
- """
17
- This function handles GET requests to the root URL ('/') of the API.
18
- It returns a simple welcome message.
19
- """
20
- return "Welcome to the Airbnb Rental Price Prediction API!"
21
-
22
- # Define an endpoint for single property prediction (POST request)
23
- @rental_price_predictor_api.post('/v1/rental')
24
- def predict_rental_price():
25
- """
26
- This function handles POST requests to the '/v1/rental' endpoint.
27
- It expects a JSON payload containing property details and returns
28
- the predicted rental price as a JSON response.
29
- """
30
- # Get the JSON data from the request body
31
- property_data = request.get_json()
32
-
33
- # Extract relevant features from the JSON data
34
- sample = {
35
- 'room_type': property_data['room_type'],
36
- 'accommodates': property_data['accommodates'],
37
- 'bathrooms': property_data['bathrooms'],
38
- 'cancellation_policy': property_data['cancellation_policy'],
39
- 'cleaning_fee': property_data['cleaning_fee'],
40
- 'instant_bookable': property_data['instant_bookable'],
41
- 'review_scores_rating': property_data['review_scores_rating'],
42
- 'bedrooms': property_data['bedrooms'],
43
- 'beds': property_data['beds']
44
- }
45
-
46
- # Convert the extracted data into a Pandas DataFrame
47
- input_data = pd.DataFrame([sample])
48
-
49
- # Make prediction (get log_price)
50
- predicted_log_price = model.predict(input_data)[0]
51
-
52
- # Calculate actual price
53
- predicted_price = np.exp(predicted_log_price)
54
-
55
- # Convert predicted_price to Python float
56
- predicted_price = round(float(predicted_price), 2)
57
- # The conversion above is needed as we convert the model prediction (log price) to actual price using np.exp, which returns predictions as NumPy float32 values.
58
- # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error
59
 
60
- # Return the actual price
61
- return jsonify({'Predicted Price (in dollars)': predicted_price})
62
-
63
-
64
- # Define an endpoint for batch prediction (POST request)
65
- @rental_price_predictor_api.post('/v1/rentalbatch')
66
- def predict_rental_price_batch():
67
- """
68
- This function handles POST requests to the '/v1/rentalbatch' endpoint.
69
- It expects a CSV file containing property details for multiple properties
70
- and returns the predicted rental prices as a dictionary in the JSON response.
71
- """
72
- # Get the uploaded CSV file from the request
73
- file = request.files['file']
74
-
75
- # Read the CSV file into a Pandas DataFrame
76
- input_data = pd.read_csv(file)
77
-
78
- # Make predictions for all properties in the DataFrame (get log_prices)
79
- predicted_log_prices = model.predict(input_data).tolist()
80
-
81
- # Calculate actual prices
82
- predicted_prices = [round(float(np.exp(log_price)), 2) for log_price in predicted_log_prices]
83
-
84
- # Create a dictionary of predictions with property IDs as keys
85
- property_ids = input_data['id'].tolist() # Assuming 'id' is the property ID column
86
- output_dict = dict(zip(property_ids, predicted_prices)) # Use actual prices
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- # Return the predictions dictionary as a JSON response
89
- return output_dict
90
 
91
- # Run the Flask application in debug mode if this script is executed directly
92
  if __name__ == '__main__':
93
- rental_price_predictor_api.run(debug=True)
 
1
  # Import necessary libraries
2
  import numpy as np
3
+ import joblib
4
+ import pandas as pd
5
+ import os
6
+ from flask import Flask, request, jsonify
7
 
8
  # Initialize the Flask application
9
+ sales_predictor_api = Flask("SuperKart Sales Predictor API")
10
 
11
  # Load the trained machine learning model
12
+ # CRITICAL FIX: The file name is CORRECTED here to match the file you uploaded!
13
+ MODEL_PATH = os.path.join(os.getcwd(), "best_xgb_pipeline.joblib")
14
 
15
+ try:
16
+ model = joblib.load(MODEL_PATH)
17
+ print(f"Model loaded successfully from: {MODEL_PATH}")
18
+ except Exception as e:
19
+ print(f"FATAL ERROR: Could not load model: {e}")
20
+ model = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ @sales_predictor_api.get('/')
23
+ def home():
24
+ """Returns a simple welcome message for the SuperKart API."""
25
+ return "Welcome to the SuperKart Sales Prediction API!"
26
+
27
+ @sales_predictor_api.post('/v1/sales')
28
+ def predict_single_sale():
29
+ """Handles POST requests for a single sales forecast."""
30
+ if model is None:
31
+ return jsonify({'error': 'Internal server error: Model failed to load at startup.'}), 500
32
+
33
+ try:
34
+ property_data = request.get_json()
35
+ input_data = pd.DataFrame([property_data])
36
+
37
+ # Predicts actual sales total directly
38
+ predicted_sales = model.predict(input_data)[0]
39
+ predicted_sales = round(float(predicted_sales), 2)
40
+
41
+ return jsonify({'Predicted Total Sales': predicted_sales})
42
+ except Exception as e:
43
+ return jsonify({'error': str(e), 'message': f'Prediction failed: {str(e)}'}), 400
44
+
45
+ @sales_predictor_api.post('/v1/salesbatch')
46
+ def predict_sales_batch():
47
+ """Handles POST requests for batch sales forecasts via CSV upload."""
48
+ if model is None:
49
+ return jsonify({'error': 'Internal server error: Model failed to load at startup.'}), 500
50
+
51
+ try:
52
+ file = request.files['file']
53
+ input_data = pd.read_csv(file)
54
+ predicted_sales = model.predict(input_data).tolist()
55
+ final_predictions = [round(float(sale), 2) for sale in predicted_sales]
56
+
57
+ property_ids = input_data['id'].tolist()
58
+ output_dict = dict(zip(property_ids, final_predictions))
59
+
60
+ return jsonify(output_dict)
61
+ except Exception as e:
62
+ return jsonify({'error': str(e), 'message': f'Batch prediction failed: {str(e)}'}), 400
63
 
 
 
64
 
 
65
  if __name__ == '__main__':
66
+ sales_predictor_api.run(debug=True, host='0.0.0.0', port=7860)