hande-x commited on
Commit
180fd0b
·
verified ·
1 Parent(s): 3430cc6

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +90 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,92 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import joblib
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ MODEL_PATH = 'src/r_tips.joblib'
7
+ SCALER_PATH = 'src/scaler_tips.joblib'
8
+
9
+ FEATURES = [
10
+ 'total_bill', 'size', 'bill_per_person',
11
+ 'sex_Male', 'smoker_Yes',
12
+ 'day_Sat', 'day_Sun', 'day_Thur',
13
+ 'time_Lunch'
14
+ ]
15
+
16
+ NUMERICAL_COLS = ['total_bill', 'size', 'bill_per_person']
17
+
18
+ @st.cache_resource
19
+ def load_assets():
20
+ try:
21
+ model = joblib.load(MODEL_PATH)
22
+ scaler = joblib.load(SCALER_PATH)
23
+ return model, scaler
24
+ except Exception as e:
25
+ st.error(f"Error loading assets. Ensure '{MODEL_PATH}' and '{SCALER_PATH}' are uploaded. Error: {e}")
26
+ return None, None
27
+
28
+ def preprocess_and_predict(model, scaler, input_data):
29
+
30
+ df_input = pd.DataFrame([input_data])
31
+
32
+ df_processed = pd.get_dummies(df_input, columns=["sex", "smoker", "day", "time"], drop_first=True)
33
+
34
+ for col in FEATURES:
35
+ if col not in df_processed.columns:
36
+ df_processed[col] = 0
37
+
38
+ final_features = df_processed[FEATURES]
39
+
40
+ numerical_part = final_features[NUMERICAL_COLS]
41
+
42
+ scaled_numerical = scaler.transform(numerical_part)
43
+
44
+ final_input_array = final_features.values.copy()
45
+ final_input_array[:, 0:len(NUMERICAL_COLS)] = scaled_numerical
46
+
47
+ prediction = model.predict(final_input_array)
48
+
49
+ return float(prediction[0])
50
+
51
+ # --- Streamlit Interface ---
52
+ st.set_page_config(page_title="Waiter Tip Predictor", layout="centered")
53
+ st.title("💰 Waiter Tip Prediction")
54
+ st.markdown("Enter bill details and dining context to predict the tip amount ($).")
55
+
56
+ model, scaler = load_assets()
57
+
58
+ if model is not None and scaler is not None:
59
+ st.sidebar.header("Dining Details")
60
+
61
+ total_bill = st.sidebar.number_input("Total Bill ($):", min_value=1.0, value=25.0, step=0.5)
62
+ size = st.sidebar.number_input("Party Size:", min_value=1, max_value=10, value=3)
63
+
64
+ bill_per_person = total_bill / size if size > 0 else 0
65
+
66
+ sex = st.sidebar.selectbox("Server/Diner Sex:", options=["Female", "Male"])
67
+ smoker = st.sidebar.selectbox("Smoker at Table?", options=["No", "Yes"])
68
+ day = st.sidebar.selectbox("Day of the Week:", options=["Thur", "Fri", "Sat", "Sun"])
69
+ time = st.sidebar.selectbox("Time of Day:", options=["Lunch", "Dinner"])
70
+
71
+ input_data = {
72
+ 'total_bill': total_bill,
73
+ 'size': size,
74
+ 'bill_per_person': bill_per_person,
75
+ 'sex': sex,
76
+ 'smoker': smoker,
77
+ 'day': day,
78
+ 'time': time
79
+ }
80
+
81
+ st.subheader("Input Summary:")
82
+ st.dataframe(pd.DataFrame([input_data]), hide_index=True)
83
 
84
+ if st.button("Predict Tip Amount"):
85
+ with st.spinner('Calculating prediction...'):
86
+ predicted_tip = preprocess_and_predict(model, scaler, input_data)
87
+
88
+ st.success("Prediction Successful!")
89
+ st.markdown("### Predicted Tip:")
90
+ st.markdown(f"**${predicted_tip:,.2f}**")
91
+
92
+ st.info(f"The predicted tip is approximately {predicted_tip/total_bill:.1%} of the total bill.")