zahidpichen commited on
Commit
8193c46
·
verified ·
1 Parent(s): a8be96d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -90
app.py CHANGED
@@ -2,36 +2,24 @@ import streamlit as st
2
  import numpy as np
3
  import pandas as pd
4
  import os
5
- import tempfile
6
  import joblib
7
  import pickle
8
-
9
- # Try to import keras only if available (for .h5 models)
10
  try:
11
  from tensorflow.keras.models import load_model as keras_load_model
12
  KERAS_AVAILABLE = True
13
  except Exception:
14
  KERAS_AVAILABLE = False
15
 
16
- st.set_page_config(page_title="House Price Predictor", layout="centered")
17
-
18
  st.title("🏠 Simple House Price Predictor")
19
- st.write("Load a saved regression model (joblib/pickle or Keras .h5) and predict house price from features.")
20
-
21
- # Sidebar: model selection / upload
22
- st.sidebar.header("Model")
23
- DEFAULT_MODEL_NAMES = ["model.joblib", "model.pkl", "model.h5"]
24
 
25
- selected_local = None
26
- for name in DEFAULT_MODEL_NAMES:
27
- if os.path.exists(name):
28
- selected_local = name
29
- break
30
 
31
- uploaded_model = st.sidebar.file_uploader("Upload your saved model file (joblib/pkl/h5)", type=["joblib","pkl","h5"])
32
- use_local = st.sidebar.checkbox("Use model file from repository (if present)", value=(selected_local is not None))
33
-
34
- @st.cache_resource
35
  def load_model_from_path(path):
36
  """Load model from a local path (joblib/pickle/keras .h5)."""
37
  ext = os.path.splitext(path)[1].lower()
@@ -43,69 +31,33 @@ def load_model_from_path(path):
43
  return pickle.load(f)
44
  if ext == ".h5":
45
  if not KERAS_AVAILABLE:
46
- raise RuntimeError("Keras/TensorFlow not available in this environment to load .h5 model.")
47
  return keras_load_model(path)
48
  raise ValueError("Unsupported model extension: " + ext)
49
 
50
- def load_model_from_uploaded(uploaded_file):
51
- """Save uploaded file to a temp file and load similarly to local path."""
52
- if uploaded_file is None:
53
- return None
54
- suffix = os.path.splitext(uploaded_file.name)[1].lower()
55
- # write to temp file
56
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
57
- tmp.write(uploaded_file.getbuffer())
58
- tmp.flush()
59
- tmp.close()
60
- model = load_model_from_path(tmp.name)
61
- try:
62
- os.unlink(tmp.name)
63
- except Exception:
64
- pass
65
- return model
66
 
67
- # Attempt to load model based on user choices
68
  model = None
69
- if use_local and selected_local:
70
  try:
71
- model = load_model_from_path(selected_local)
72
- st.sidebar.success(f"Loaded local model: {selected_local}")
73
  except Exception as e:
74
- st.sidebar.error(f"Failed to load local model: {e}")
75
-
76
- if model is None and uploaded_model is not None:
77
- try:
78
- model = load_model_from_uploaded(uploaded_model)
79
- st.sidebar.success(f"Loaded uploaded model: {uploaded_model.name}")
80
- except Exception as e:
81
- st.sidebar.error(f"Failed to load uploaded model: {e}")
82
-
83
- if model is None:
84
- st.sidebar.info("No model loaded yet. Place model.joblib/model.pkl/model.h5 in repo or upload one.")
85
- st.markdown(
86
- """
87
- **How to get a model:**\n
88
- - If using scikit-learn: `joblib.dump(your_model, 'model.joblib')` or `pickle.dump(your_model, open('model.pkl','wb'))`\n
89
- - If using Keras: `model.save('model.h5')` (requires TensorFlow in the environment).
90
- """
91
- )
92
 
93
  st.markdown("---")
94
  st.header("Input features")
95
 
96
- # NOTE: keep a small sensible feature set. Adjust to match the features your model expects.
97
- # Common simple house price features:
98
- # - OverallQual (1-10)
99
- # - GrLivArea (square feet)
100
- # - GarageCars (count)
101
- # - TotalBsmtSF (sq ft)
102
- # - FullBath (count)
103
- # - YearBuilt (year)
104
- #
105
- # Make sure your trained model was trained on exactly these features in this order.
106
-
107
  col1, col2 = st.columns(2)
108
-
109
  with col1:
110
  overall_qual = st.slider("Overall Quality (1 - 10)", 1, 10, 6)
111
  gr_liv_area = st.number_input("Ground living area (sq ft)", min_value=100, max_value=10000, value=1500, step=50)
@@ -123,19 +75,15 @@ predict_button = st.button("Predict House Price")
123
 
124
  def model_predict(model_obj, features_array):
125
  """Unify prediction call for sklearn-like and keras models."""
126
- # reshape
127
  X = np.array(features_array).reshape(1, -1)
128
- # For Keras models: they may output a 2D array
129
  try:
130
- # scikit-learn like .predict
131
  if hasattr(model_obj, "predict") and not (KERAS_AVAILABLE and hasattr(model_obj, "save")):
132
  preds = model_obj.predict(X)
133
- # sklearn regressors usually return array of shape (1,)
134
  if isinstance(preds, (list, np.ndarray)):
135
  return float(np.squeeze(preds))
136
  return float(preds)
137
- except Exception as e:
138
- # fallthrough to try keras
139
  pass
140
 
141
  # Try Keras model
@@ -150,23 +98,11 @@ def model_predict(model_obj, features_array):
150
 
151
  if predict_button:
152
  if model is None:
153
- st.error("No model loaded. Upload a model or enable local model usage in the sidebar.")
154
  else:
155
  try:
156
  pred = model_predict(model, input_vector)
157
- # If your model predicts log(price) or scaled value, adjust accordingly.
158
  st.success(f"Predicted house price: {pred:,.2f} (units same as model target)")
159
- st.info("If the value seems off, check that the model expects these exact features and order.")
160
  except Exception as e:
161
  st.exception(f"Prediction failed: {e}")
162
-
163
- st.markdown("---")
164
- st.markdown("### Tips / Troubleshooting")
165
- st.markdown(
166
- """
167
- - Ensure the model was trained on exactly **these features in the same order**.\n
168
- - If you trained using scaling/encoders (StandardScaler, OneHotEncoder), save and load those transformers and apply them to inputs before predicting.\n
169
- - To include encoders/scalers, save a pipeline object (e.g., sklearn Pipeline) so the app only needs to call `pipeline.predict(X)`.\n
170
- - If your model predicts a transformed target (e.g., log(price)), inverse-transform before displaying.\n
171
- """
172
- )
 
2
  import numpy as np
3
  import pandas as pd
4
  import os
 
5
  import joblib
6
  import pickle
 
 
7
  try:
8
  from tensorflow.keras.models import load_model as keras_load_model
9
  KERAS_AVAILABLE = True
10
  except Exception:
11
  KERAS_AVAILABLE = False
12
 
13
+ st.set_page_config(page_title="House Price Predictor (fixed model)", layout="centered")
 
14
  st.title("🏠 Simple House Price Predictor")
15
+ st.write("This app loads a fixed model file: `house_price_model.h5` and predicts house price from features.")
 
 
 
 
16
 
17
+ # -----------------------
18
+ # HARD-CODED MODEL PATH
19
+ # -----------------------
20
+ MODEL_PATH = "house_price_model.h5" # <-- hard-coded model filename
 
21
 
22
+ # Utility: load model from path (supports .h5, .joblib, .pkl)
 
 
 
23
  def load_model_from_path(path):
24
  """Load model from a local path (joblib/pickle/keras .h5)."""
25
  ext = os.path.splitext(path)[1].lower()
 
31
  return pickle.load(f)
32
  if ext == ".h5":
33
  if not KERAS_AVAILABLE:
34
+ raise RuntimeError("TensorFlow/Keras not available. Add `tensorflow` to requirements.txt.")
35
  return keras_load_model(path)
36
  raise ValueError("Unsupported model extension: " + ext)
37
 
38
+ # Cached loader so HF/Streamlit won't reload unnecessarily
39
+ @st.cache_resource
40
+ def load_fixed_model():
41
+ return load_model_from_path(MODEL_PATH)
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Attempt to load the fixed model
44
  model = None
45
+ if os.path.exists(MODEL_PATH):
46
  try:
47
+ model = load_fixed_model()
48
+ st.sidebar.success(f"Loaded model: {MODEL_PATH}")
49
  except Exception as e:
50
+ st.sidebar.error(f"Failed to load {MODEL_PATH}: {e}")
51
+ model = None
52
+ else:
53
+ st.sidebar.warning(f"Model file not found: {MODEL_PATH}")
54
+ st.sidebar.info("Add `house_price_model.h5` to the repo root (or your HF Space files) and re-run the app.")
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  st.markdown("---")
57
  st.header("Input features")
58
 
59
+ # Feature inputs (keep these in same order your model expects)
 
 
 
 
 
 
 
 
 
 
60
  col1, col2 = st.columns(2)
 
61
  with col1:
62
  overall_qual = st.slider("Overall Quality (1 - 10)", 1, 10, 6)
63
  gr_liv_area = st.number_input("Ground living area (sq ft)", min_value=100, max_value=10000, value=1500, step=50)
 
75
 
76
  def model_predict(model_obj, features_array):
77
  """Unify prediction call for sklearn-like and keras models."""
 
78
  X = np.array(features_array).reshape(1, -1)
79
+ # Try sklearn-like predict first
80
  try:
 
81
  if hasattr(model_obj, "predict") and not (KERAS_AVAILABLE and hasattr(model_obj, "save")):
82
  preds = model_obj.predict(X)
 
83
  if isinstance(preds, (list, np.ndarray)):
84
  return float(np.squeeze(preds))
85
  return float(preds)
86
+ except Exception:
 
87
  pass
88
 
89
  # Try Keras model
 
98
 
99
  if predict_button:
100
  if model is None:
101
+ st.error("Model not loaded. Ensure `house_price_model.h5` exists in repo and that `tensorflow` is installed.")
102
  else:
103
  try:
104
  pred = model_predict(model, input_vector)
 
105
  st.success(f"Predicted house price: {pred:,.2f} (units same as model target)")
106
+ st.info("If value seems off, ensure model expects these features in this order and any scalers/pipelines are included.")
107
  except Exception as e:
108
  st.exception(f"Prediction failed: {e}")