Dattaluri commited on
Commit
9c74e64
·
verified ·
1 Parent(s): ab3a758

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -75
app.py CHANGED
@@ -1,86 +1,67 @@
1
- import streamlit as st
2
- import prediction_pipeline as pp
3
- import pandas as pd
4
- import os
5
 
6
- # -----------------------------
7
- # PAGE CONFIG
8
- # Must be first Streamlit command
9
- st.set_page_config(
10
- page_title="Tourism Package Prediction",
11
- page_icon="✈️"
12
- )
13
 
14
- st.title("✈️ Tourism Package Prediction")
15
- st.write("Predict whether a customer will purchase a tourism package.")
16
 
17
- # -----------------------------
18
- # LOAD MODEL
19
- @st.cache_resource
20
- def load_model():
21
- pp.load_artifacts()
22
- return pp.MODEL, pp.X_TRAIN_ENCODED_COLUMNS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- model, columns = load_model()
 
25
 
26
- if model is None or columns is None:
27
- st.error("❌ Model failed to load. Check logs for details.")
28
- st.stop()
 
 
 
 
 
 
29
 
30
- # -----------------------------
31
- # UI INPUTS
32
- Age = st.number_input("Age", min_value=0.0, value=35.0)
33
- TypeofContact = st.selectbox("Type of Contact", ["Self Enquiry", "Company Invited"])
34
- CityTier = st.selectbox("City Tier", [1, 2, 3])
35
- DurationOfPitch = st.number_input("Duration Of Pitch", min_value=0.0, value=10.0)
36
- Occupation = st.selectbox("Occupation", ["Salaried", "Free Lancer", "Small Business", "Large Business"])
37
- Gender = st.selectbox("Gender", ["Male", "Female"])
38
- NumberOfPersonVisiting = st.number_input("Number Of Person Visiting", min_value=1, value=2)
39
- NumberOfFollowups = st.number_input("Number Of Followups", min_value=0.0, value=3.0)
40
- ProductPitched = st.selectbox("Product Pitched", ["Basic", "Standard", "Deluxe", "Super Deluxe"])
41
- PreferredPropertyStar = st.number_input("Preferred Property Star", min_value=1.0, max_value=5.0, value=3.0)
42
- MaritalStatus = st.selectbox("Marital Status", ["Married", "Single", "Divorced"])
43
- NumberOfTrips = st.number_input("Number Of Trips", min_value=0.0, value=2.0)
44
- Passport = st.selectbox("Passport", [0, 1])
45
- PitchSatisfactionScore = st.slider("Pitch Satisfaction Score", 1, 5, 4)
46
- OwnCar = st.selectbox("Own Car", [0, 1])
47
- NumberOfChildrenVisiting = st.number_input("Number Of Children Visiting", min_value=0.0, value=1.0)
48
- Designation = st.selectbox("Designation", ["Executive", "Manager", "Senior Manager", "AVP", "VP"])
49
- MonthlyIncome = st.number_input("Monthly Income", min_value=0.0, value=25000.0)
50
 
51
- # -----------------------------
52
- # PREDICT BUTTON
53
- if st.button("Predict"):
54
- input_data = {
55
- "Age": Age,
56
- "TypeofContact": TypeofContact,
57
- "CityTier": CityTier,
58
- "DurationOfPitch": DurationOfPitch,
59
- "Occupation": Occupation,
60
- "Gender": Gender,
61
- "NumberOfPersonVisiting": NumberOfPersonVisiting,
62
- "NumberOfFollowups": NumberOfFollowups,
63
- "ProductPitched": ProductPitched,
64
- "PreferredPropertyStar": PreferredPropertyStar,
65
- "MaritalStatus": MaritalStatus,
66
- "NumberOfTrips": NumberOfTrips,
67
- "Passport": Passport,
68
- "PitchSatisfactionScore": PitchSatisfactionScore,
69
- "OwnCar": OwnCar,
70
- "NumberOfChildrenVisiting": NumberOfChildrenVisiting,
71
- "Designation": Designation,
72
- "MonthlyIncome": MonthlyIncome
73
- }
74
 
75
- try:
76
- df = pp.preprocess_input(input_data)
77
- pred = model.predict(df)[0]
78
- proba = model.predict_proba(df)[0]
79
 
80
- st.success(f"Prediction: {'Purchased' if pred == 1 else 'Not Purchased'}")
81
- st.write(f"Probability Purchased: **{proba[1]:.2%}**")
82
- st.write(f"Probability Not Purchased: **{proba[0]:.2%}**")
83
- except Exception as e:
84
- st.error(f"Prediction failed: {e}")
85
 
 
 
86
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ from fastapi import FastAPI
3
+ from pydantic import BaseModel
4
+ import pandas as pd
5
+ import numpy as np
 
 
 
6
 
7
+ from prediction_pipeline import load_artifacts, preprocess_input, MODEL, X_TRAIN_ENCODED_COLUMNS
 
8
 
9
+ # Define the input data model using Pydantic BaseModel
10
+ class PredictionRequest(BaseModel):
11
+ Age: float
12
+ TypeofContact: str
13
+ CityTier: int
14
+ DurationOfPitch: float
15
+ Occupation: str
16
+ Gender: str
17
+ NumberOfPersonVisiting: int
18
+ NumberOfFollowups: float
19
+ ProductPitched: str
20
+ PreferredPropertyStar: float
21
+ MaritalStatus: str
22
+ NumberOfTrips: float
23
+ Passport: int
24
+ PitchSatisfactionScore: int
25
+ OwnCar: int
26
+ NumberOfChildrenVisiting: float
27
+ Designation: str
28
+ MonthlyIncome: float
29
 
30
+ # Initialize FastAPI app
31
+ app = FastAPI()
32
 
33
+ # Load model and column names when the application starts
34
+ # This ensures artifacts are loaded only once
35
+ @app.on_event("startup")
36
+ async def startup_event():
37
+ print("Loading model and column names on startup...")
38
+ load_artifacts()
39
+ if MODEL is None or X_TRAIN_ENCODED_COLUMNS is None:
40
+ raise RuntimeError("Failed to load model or column names during startup.")
41
+ print("Model and column names loaded successfully.")
42
 
43
+ @app.get("/")
44
+ async def root():
45
+ return {"message": "Welcome to the Tourism Package Prediction API!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ @app.post("/predict")
48
+ async def predict(request: PredictionRequest):
49
+ # Convert incoming request data to a dictionary
50
+ input_data_dict = request.model_dump()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # Preprocess the input data
53
+ preprocessed_df = preprocess_input(input_data_dict)
 
 
54
 
55
+ # Make prediction
56
+ prediction = MODEL.predict(preprocessed_df)[0]
57
+ prediction_proba = MODEL.predict_proba(preprocessed_df)[0].tolist()
 
 
58
 
59
+ # Map prediction to a human-readable label if desired
60
+ prediction_label = "Purchased" if prediction == 1 else "Not Purchased"
61
 
62
+ return {
63
+ "prediction": int(prediction),
64
+ "prediction_label": prediction_label,
65
+ "probability_not_purchased": prediction_proba[0],
66
+ "probability_purchased": prediction_proba[1]
67
+ }