amitcoolll commited on
Commit
54d4ada
·
verified ·
1 Parent(s): 3e8702f

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. Dockerfile +16 -0
  2. app.py +101 -0
  3. conversion_prediction_model_v1_0.joblib +3 -0
  4. requirements.txt +11 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ # Set the working directory inside the container
4
+ WORKDIR /app
5
+
6
+ # Copy all files from the current directory to the container's working directory
7
+ COPY . .
8
+
9
+ # Install dependencies from the requirements file without using cache to reduce image size
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ # Define the command to start the application using Gunicorn with 4 worker processes
13
+ # - `-w 4`: Uses 4 worker processes for handling requests
14
+ # - `-b 0.0.0.0:7860`: Binds the server to port 7860 on all network interfaces
15
+ # - `app:app`: Runs the Flask app (assuming `app.py` contains the Flask instance named `app`)
16
+ CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:rental_price_predictor_api"]
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import os
3
+ import numpy as np
4
+ import joblib # For loading the serialized model
5
+ import pandas as pd # For data manipulation
6
+ from flask import Flask, request, jsonify # For creating the Flask API
7
+
8
+ # Initialize the Flask application
9
+ rental_price_predictor_api = Flask("Extraa Learn conversion Predictor")
10
+
11
+ # Load the trained machine learning model
12
+ # Use relative path to load the model inside backend_files
13
+ model_path = os.path.join(os.path.dirname(__file__), "conversion_prediction_model_v1_0.joblib")
14
+ model = joblib.load(model_path)
15
+
16
+ print("Model loaded successfully.")
17
+ # model = joblib.load(model_path)
18
+
19
+ # Define a route for the home page (GET request)
20
+ @rental_price_predictor_api.get('/')
21
+ def home():
22
+ """
23
+ This function handles GET requests to the root URL ('/') of the API.
24
+ It returns a simple welcome message.
25
+ """
26
+ return "Welcome to the Airbnb Rental Price Prediction API!"
27
+
28
+ # Define an endpoint for single property prediction (POST request)
29
+ @rental_price_predictor_api.post('/v1/conversion')
30
+ def predict_rental_price():
31
+ """
32
+ This function handles POST requests to the '/v1/conversion' endpoint.
33
+ It expects a JSON payload containing property details and returns
34
+ the predicted rental price as a JSON response.
35
+ """
36
+ # Get the JSON data from the request body
37
+ property_data = request.get_json()
38
+
39
+ # Extract relevant features from the JSON data
40
+ sample = {
41
+ 'age': property_data['age'],
42
+ 'website_visits': property_data['website_visits'],
43
+ 'time_spent_on_website': property_data['time_spent_on_website'],
44
+ 'page_views_per_visit': property_data['page_views_per_visit'],
45
+ 'current_occupation': property_data['current_occupation'],
46
+ 'first_interaction': property_data['first_interaction'],
47
+ 'profile_completed': property_data['profile_completed'],
48
+ 'last_activity': property_data['last_activity'],
49
+ 'print_media_type1': property_data['print_media_type1'],
50
+ 'print_media_type2': property_data['print_media_type2'],
51
+ 'digital_media': property_data['digital_media'],
52
+ 'educational_channels': property_data['educational_channels'],
53
+ 'referral': property_data['referral']
54
+ }
55
+
56
+ # Convert the extracted data into a Pandas DataFrame
57
+ input_data = pd.DataFrame([sample])
58
+
59
+ # Make prediction (get status_log)
60
+ status_log = model.predict(input_data)[0]
61
+
62
+ # Calculate actual price
63
+ status = np.exp(status_log)
64
+ # # Convert status to Python float
65
+ # status = round(float(status), 2)
66
+ # 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.
67
+ # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error
68
+
69
+ # Return the actual price
70
+ return jsonify({'Predicted status ': status})
71
+
72
+ # Define an endpoint for batch prediction (POST request)
73
+ @rental_price_predictor_api.post('/v1/conversionbatch')
74
+ def predict_rental_price_batch():
75
+ """
76
+ This function handles POST requests to the '/v1/conversionbatch' endpoint.
77
+ It expects a CSV file containing property details for multiple properties
78
+ and returns the predicted rental prices as a dictionary in the JSON response.
79
+ """
80
+ # Get the uploaded CSV file from the request
81
+ file = request.files['file']
82
+
83
+ # Read the CSV file into a Pandas DataFrame
84
+ input_data = pd.read_csv(file)
85
+
86
+ # Make predictions for all properties in the DataFrame (get log_prices)
87
+ status_log = model.predict(input_data).tolist()
88
+
89
+ # Calculate actual prices
90
+ status = [round(float(np.exp(log_price)), 2) for log_price in status_log]
91
+
92
+ # Create a dictionary of predictions with property IDs as keys
93
+ property_ids = input_data['ID'].tolist() # Assuming 'id' is the property ID column
94
+ output_dict = dict(zip(property_ids, status)) # Use actual prices
95
+
96
+ # Return the predictions dictionary as a JSON response
97
+ return output_dict
98
+
99
+ # Run the Flask application in debug mode if this script is executed directly
100
+ if __name__ == '__main__':
101
+ rental_price_predictor_api.run(debug=True)
conversion_prediction_model_v1_0.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc1bd21ff520078ab9764e8f46cbfda074e8d9d674b77609274f237ae2ae2487
3
+ size 91927
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pandas==2.2.2
2
+ numpy==2.0.2
3
+ scikit-learn==1.6.1
4
+ xgboost==2.1.4
5
+ joblib==1.4.2
6
+ Werkzeug==2.2.2
7
+ flask==2.2.2
8
+ gunicorn==20.1.0
9
+ requests==2.28.1
10
+ uvicorn[standard]
11
+ streamlit==1.43.2