NV9523 commited on
Commit
9714b3f
·
verified ·
1 Parent(s): 7d4f61b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -160
app.py CHANGED
@@ -1,162 +1,145 @@
1
- import faicons as fa
2
- import plotly.express as px
3
-
4
- # Load data and compute static values
5
- from shared import app_dir, tips
6
- from shinywidgets import render_plotly
7
-
8
- from shiny import reactive, render
9
- from shiny.express import input, ui
10
-
11
- bill_rng = (min(tips.total_bill), max(tips.total_bill))
12
-
13
- # Add page title and sidebar
14
- ui.page_opts(title="Restaurant tipping", fillable=True)
15
-
16
- with ui.sidebar(open="desktop"):
17
- ui.input_slider(
18
- "total_bill",
19
- "Bill amount",
20
- min=bill_rng[0],
21
- max=bill_rng[1],
22
- value=bill_rng,
23
- pre="$",
24
- )
25
- ui.input_checkbox_group(
26
- "time",
27
- "Food service",
28
- ["Lunch", "Dinner"],
29
- selected=["Lunch", "Dinner"],
30
- inline=True,
31
- )
32
- ui.input_action_button("reset", "Reset filter")
33
-
34
- # Add main content
35
- ICONS = {
36
- "user": fa.icon_svg("user", "regular"),
37
- "wallet": fa.icon_svg("wallet"),
38
- "currency-dollar": fa.icon_svg("dollar-sign"),
39
- "ellipsis": fa.icon_svg("ellipsis"),
 
 
 
 
40
  }
41
 
42
- with ui.layout_columns(fill=False):
43
- with ui.value_box(showcase=ICONS["user"]):
44
- "Total tippers"
45
-
46
- @render.express
47
- def total_tippers():
48
- tips_data().shape[0]
49
-
50
- with ui.value_box(showcase=ICONS["wallet"]):
51
- "Average tip"
52
-
53
- @render.express
54
- def average_tip():
55
- d = tips_data()
56
- if d.shape[0] > 0:
57
- perc = d.tip / d.total_bill
58
- f"{perc.mean():.1%}"
59
-
60
- with ui.value_box(showcase=ICONS["currency-dollar"]):
61
- "Average bill"
62
-
63
- @render.express
64
- def average_bill():
65
- d = tips_data()
66
- if d.shape[0] > 0:
67
- bill = d.total_bill.mean()
68
- f"${bill:.2f}"
69
-
70
-
71
- with ui.layout_columns(col_widths=[6, 6, 12]):
72
- with ui.card(full_screen=True):
73
- ui.card_header("Tips data")
74
-
75
- @render.data_frame
76
- def table():
77
- return render.DataGrid(tips_data())
78
-
79
- with ui.card(full_screen=True):
80
- with ui.card_header(class_="d-flex justify-content-between align-items-center"):
81
- "Total bill vs tip"
82
- with ui.popover(title="Add a color variable", placement="top"):
83
- ICONS["ellipsis"]
84
- ui.input_radio_buttons(
85
- "scatter_color",
86
- None,
87
- ["none", "sex", "smoker", "day", "time"],
88
- inline=True,
89
- )
90
-
91
- @render_plotly
92
- def scatterplot():
93
- color = input.scatter_color()
94
- return px.scatter(
95
- tips_data(),
96
- x="total_bill",
97
- y="tip",
98
- color=None if color == "none" else color,
99
- trendline="lowess",
100
- )
101
-
102
- with ui.card(full_screen=True):
103
- with ui.card_header(class_="d-flex justify-content-between align-items-center"):
104
- "Tip percentages"
105
- with ui.popover(title="Add a color variable"):
106
- ICONS["ellipsis"]
107
- ui.input_radio_buttons(
108
- "tip_perc_y",
109
- "Split by:",
110
- ["sex", "smoker", "day", "time"],
111
- selected="day",
112
- inline=True,
113
- )
114
-
115
- @render_plotly
116
- def tip_perc():
117
- from ridgeplot import ridgeplot
118
-
119
- dat = tips_data()
120
- dat["percent"] = dat.tip / dat.total_bill
121
- yvar = input.tip_perc_y()
122
- uvals = dat[yvar].unique()
123
-
124
- samples = [[dat.percent[dat[yvar] == val]] for val in uvals]
125
-
126
- plt = ridgeplot(
127
- samples=samples,
128
- labels=uvals,
129
- bandwidth=0.01,
130
- colorscale="viridis",
131
- colormode="row-index",
132
- )
133
-
134
- plt.update_layout(
135
- legend=dict(
136
- orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.5
137
- )
138
- )
139
-
140
- return plt
141
-
142
-
143
- ui.include_css(app_dir / "styles.css")
144
-
145
- # --------------------------------------------------------
146
- # Reactive calculations and effects
147
- # --------------------------------------------------------
148
-
149
-
150
- @reactive.calc
151
- def tips_data():
152
- bill = input.total_bill()
153
- idx1 = tips.total_bill.between(bill[0], bill[1])
154
- idx2 = tips.time.isin(input.time())
155
- return tips[idx1 & idx2]
156
-
157
-
158
- @reactive.effect
159
- @reactive.event(input.reset)
160
- def _():
161
- ui.update_slider("total_bill", value=bill_rng)
162
- ui.update_checkbox_group("time", selected=["Lunch", "Dinner"])
 
1
+ from flask import Flask, request, jsonify, render_template
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+ from sklearn.base import BaseEstimator, TransformerMixin
6
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
7
+
8
+ # Custom LabelEncoder Transformer
9
+ class LabelEncoderTransformer(BaseEstimator, TransformerMixin):
10
+ def __init__(self):
11
+ self.encoders = {}
12
+
13
+ def fit(self, X, y=None):
14
+ for col in X.columns:
15
+ le = LabelEncoder()
16
+ le.fit(X[col])
17
+ self.encoders[col] = le
18
+ return self
19
+
20
+ def transform(self, X):
21
+ X_transformed = X.copy()
22
+ for col in X.columns:
23
+ X_transformed[col] = self.encoders[col].transform(X[col])
24
+ return X_transformed
25
+
26
+ def inverse_transform(self, X):
27
+ X_inverse = X.copy()
28
+ for col in X.columns:
29
+ X_inverse[col] = self.encoders[col].inverse_transform(X[col])
30
+ return X_inverse
31
+
32
+ app = Flask(__name__)
33
+
34
+ # Load dataset
35
+ df = pd.read_excel("Laptops_dataset.xlsx")
36
+
37
+ # Extract unique values
38
+ unique_values = {
39
+ 'Ram': sorted(df['Ram'].unique().tolist()),
40
+ 'Memory': sorted(df['Memory'].unique().tolist()),
41
+ 'Size': sorted(df['Size'].unique().tolist()),
42
+ 'GPU_type': sorted(df['GPU_type'].unique().tolist()),
43
+ 'CPU_type': sorted(df['CPU_type'].unique().tolist())
44
  }
45
 
46
+ # Load model and preprocessor
47
+ model = joblib.load("best_model.pkl")
48
+ preprocessor = joblib.load("preprocessor.pkl")
49
+
50
+ @app.route('/')
51
+ def index():
52
+ return render_template('new_web.html')
53
+
54
+ @app.route('/form')
55
+ def form():
56
+ # Extract unique values from dataset
57
+ ram_values = sorted(df['Ram'].unique().tolist())
58
+ memory_values = sorted(df['Memory'].unique().tolist())
59
+ size_values = sorted(df['Size'].unique().tolist())
60
+ gpu_values = sorted(df['GPU_type'].unique().tolist())
61
+ cpu_values = sorted(df['CPU_type'].unique().tolist())
62
+
63
+ return render_template('form_web.html',
64
+ ram_values=ram_values,
65
+ memory_values=memory_values,
66
+ size_values=size_values,
67
+ gpu_values=gpu_values,
68
+ cpu_values=cpu_values)
69
+
70
+ @app.route("/submit_form", methods=['POST'])
71
+ def prediction():
72
+ if request.method == "POST":
73
+ try:
74
+ # Get form data
75
+ input_data = {
76
+ 'Ram': int(request.form['ram']),
77
+ 'Memory': int(request.form['memory']),
78
+ 'Size': float(request.form['size']),
79
+ 'GPU_type': request.form['gpu_type'],
80
+ 'CPU_type': request.form['cpu_type']
81
+ }
82
+
83
+ # Create DataFrame and process
84
+ input_df = pd.DataFrame([input_data])
85
+ processed_features = preprocessor.transform(input_df)
86
+ prediction = model.predict(processed_features)[0]
87
+
88
+ # Find similar laptops in price range
89
+ price_range = (prediction - 2000000, prediction + 2000000)
90
+ similar_laptops = df[
91
+ (df['Price'] >= price_range[0]) &
92
+ (df['Price'] <= price_range[1])
93
+ ][['Name', 'Link', 'Price']].to_dict('records')
94
+
95
+ # Get values for the sidebar form
96
+ ram_values = sorted(df['Ram'].unique().tolist())
97
+ memory_values = sorted(df['Memory'].unique().tolist())
98
+ size_values = sorted(df['Size'].unique().tolist())
99
+ gpu_values = sorted(df['GPU_type'].unique().tolist())
100
+ cpu_values = sorted(df['CPU_type'].unique().tolist())
101
+
102
+ return render_template('output_web.html',
103
+ ram=input_data['Ram'],
104
+ memory=input_data['Memory'],
105
+ size=input_data['Size'],
106
+ gpu_type=input_data['GPU_type'],
107
+ cpu_type=input_data['CPU_type'],
108
+ output=f"{prediction:,.0f}",
109
+ similar_laptops=similar_laptops,
110
+ ram_values=ram_values,
111
+ memory_values=memory_values,
112
+ size_values=size_values,
113
+ gpu_values=gpu_values,
114
+ cpu_values=cpu_values)
115
+
116
+ except Exception as e:
117
+ print(f"Error in prediction: {e}")
118
+ return render_template('error.html', error=str(e))
119
+
120
+ @app.route("/api/predict", methods=["POST"])
121
+ def api_predict():
122
+ try:
123
+ data = request.get_json()
124
+ input_data = {
125
+ 'Ram': int(data['ram']),
126
+ 'Memory': int(data['memory']),
127
+ 'Size': float(data['size']),
128
+ 'GPU_type': data['gpu_type'],
129
+ 'CPU_type': data['cpu_type']
130
+ }
131
+
132
+ # Create DataFrame with proper column order
133
+ columns = ['Ram', 'Memory', 'Size', 'GPU_type', 'CPU_type']
134
+ input_df = pd.DataFrame([input_data])[columns]
135
+
136
+ processed_features = preprocessor.transform(input_df)
137
+ prediction = model.predict(processed_features)[0]
138
+
139
+ return jsonify({"price": float(prediction)})
140
+
141
+ except Exception as e:
142
+ return jsonify({"error": str(e)}), 400
143
+
144
+ if __name__ == "__main__":
145
+ app.run(debug=True)