Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186118818919019119221941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782793428128228328428556728728828929029129229329429529629789101112132991415301302303304305306161718192021222324252627282930930# -*- coding: utf-8 -*-"""construction_Estimate.ipynb
Automatically generated by Colab.
Original file is located at https://colab.research.google.com/drive/1Co5tgLTTsncgTG84jhqjl_rRpObQX3yW"""
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, MinMaxScalerfrom sklearn.metrics import r2_scorefrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densefrom tensorflow.keras.callbacks import Callbackfrom joblib import dump, loadimport joblib # Needed for saving the OneHotEncoder laterfrom tensorflow.keras.models import save_model
# --- CORE FEATURES to be used in model training ---CORE_FEATURES = [ 'District', 'Settlement_Type', 'Area_sft', 'Land_Type', 'Building_Type', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft']CATEGORICAL_FEATURES = ['District', 'Settlement_Type', 'Land_Type', 'Building_Type']NUMERICAL_FEATURES = ['Area_sft', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft']
# --- 1. Custom R2 Callback (Still needed to see accuracy during training) ---class R2ScoreCallback(Callback): def __init__(self, validation_data): super().__init__() self.X_val, self.y_val = validation_data
def on_epoch_end(self, epoch, logs=None): y_pred = self.model.predict(self.X_val, verbose=0) r2 = r2_score(self.y_val, y_pred) logs['val_r2'] = r2 print(f" - val_r2: {r2:.4f}", end='')
from datasets import load_datasettry: dataset = load_dataset("AzharAbbas/construction_dataset", split='train')
# 2. Convert the Hugging Face Dataset object to a Pandas DataFrame df = dataset.to_pandas()
print("✅ Dataset loaded successfully from Hugging Face Hub.") print("Shape:", df.shape) print(df.head())
except Exception as e: print(f"❌ Failed to load dataset from Hugging Face Hub. Error: {e}") print("Please verify the dataset name and configuration on the Hugging Face website.")
y = df['Total_Estimate_PKR']y_scaler = MinMaxScaler()y_scaled = y_scaler.fit_transform(y.values.reshape(-1, 1))dump(y_scaler, 'y_scaler_manual.pkl')print("Target scaler saved as y_scaler_manual.pkl")
# Split data FIRSTX = df[CORE_FEATURES]X_train, X_test, y_train_scaled, y_test_scaled = train_test_split( X, y_scaled, test_size=0.2, random_state=42)
# Initialize Scalers/Encodersscaler = StandardScaler()encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False) # sparse_output=False makes the output an array
X_train_num = X_train[NUMERICAL_FEATURES]scaler.fit(X_train_num)X_train_num_scaled = scaler.transform(X_train_num)dump(scaler, 'scaler_manual.pkl') # Save the scaler
# 5b. Categorical Encoding (moved here to ensure encoder is fitted before test data is transformed)X_train_cat = X_train[CATEGORICAL_FEATURES]encoder.fit(X_train_cat)X_train_cat_encoded = encoder.transform(X_train_cat)joblib.dump(encoder, 'encoder_manual.pkl') # Save the encoder
# 5c. Combine everything for training (moved here)X_train_processed = np.hstack([X_train_num_scaled, X_train_cat_encoded])
X_test_num = X_test[NUMERICAL_FEATURES]X_test_num_scaled = scaler.transform(X_test_num)
X_test_cat = X_test[CATEGORICAL_FEATURES]X_test_cat_encoded = encoder.transform(X_test_cat)
# 6c. Combine everything for testingX_test_processed = np.hstack([X_test_num_scaled, X_test_cat_encoded])
print("Data preparation complete. Input shape:", X_train_processed.shape[1])
# --- 7. Build ANN Model ---input_shape = X_train_processed.shape[1]model = Sequential([ Dense(128, activation='relu', input_shape=(input_shape,)), Dense(64, activation='relu'), Dense(32, activation='relu'), Dense(1)])
model.compile(optimizer='adam', loss='mse')
# --- 8. Train Model ---val_split_index = int(0.9 * len(X_train_processed))X_train_for_fit = X_train_processed[:val_split_index]y_train_for_fit = y_train_scaled[:val_split_index]X_val_for_callback = X_train_processed[val_split_index:]y_val_for_callback = y_train_scaled[val_split_index:]
r2_callback = R2ScoreCallback(validation_data=(X_val_for_callback, y_val_for_callback))
print("\nTraining ANN model with manual preprocessing...")history = model.fit( # Capture the history object here X_train_for_fit, y_train_for_fit, epochs=50, batch_size=32, validation_data=(X_val_for_callback, y_val_for_callback), callbacks=[r2_callback], verbose=1)
# --- 9. Final Evaluation and Save Model ---loss = model.evaluate(X_test_processed, y_test_scaled, verbose=0)y_pred_scaled = model.predict(X_test_processed, verbose=0)r2 = r2_score(y_test_scaled, y_pred_scaled)
print(f"\n--- MANUAL Model Final Evaluation ---")print(f"Test Loss (Scaled MSE): {loss:.6f}")print(f"Test R-squared (Accuracy): {r2:.4f}")
save_model(model, 'ann_model_manual.h5')print("Trained MANUAL ANN model saved as ann_model_manual.h5")
import matplotlib.pyplot as plt# Predict on test data (y_pred is already scaled from the previous step)y_pred_scaled = model.predict(X_test_processed)
# Load the y_scalery_scaler = load('y_scaler_manual.pkl')
# Inverse transform y_test_scaled and y_pred_scaled to get original valuesy_test_original = y_scaler.inverse_transform(y_test_scaled)y_pred_original = y_scaler.inverse_transform(y_pred_scaled)
plt.figure(figsize=(8,6))plt.scatter(y_test_original, y_pred_original, alpha=0.5)plt.xlabel("Actual Cost (PKR)")plt.ylabel("Predicted Cost (PKR)")plt.title("Actual vs Predicted Construction Cost")plt.grid(True)plt.show()
plt.figure(figsize=(8,6))
# Scatter points using the original (unscaled) valuesplt.scatter(y_test_original, y_pred_original, alpha=0.4, label="Predictions")
# Perfect fit linex_line = np.linspace(min(y_test_original.flatten()), max(y_test_original.flatten()), 100)plt.plot(x_line, x_line, 'r', label="Perfect Prediction Line")
plt.xlabel("Actual Cost (PKR)")plt.ylabel("Predicted Cost (PKR)")plt.title("ANN Performance: Actual vs Predicted")plt.legend()plt.grid(True)plt.show()
plt.figure(figsize=(8,6))plt.plot(history.history["loss"], label="Training Loss")plt.plot(history.history["val_loss"], label="Validation Loss")plt.xlabel("Epochs")plt.ylabel("Loss (MSE)")plt.title("ANN Training & Validation Loss Curve")plt.legend()plt.grid(True)plt.show()
import gradio as grimport pandas as pdimport numpy as npfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.losses import MeanSquaredErrorfrom joblib import loadimport joblibimport os
# --- FEATURE DEFINITIONS (Must match the training script) ---CATEGORICAL_FEATURES = ['District', 'Settlement_Type', 'Land_Type', 'Building_Type']NUMERICAL_FEATURES = ['Area_sft', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft']# -----------------------------------------------------------------
# --- 1. Load Model and Preprocessor Artifacts ---# We check if all required files exist before attempting to loadrequired_files = ['y_scaler_manual.pkl', 'scaler_manual.pkl', 'encoder_manual.pkl', 'ann_model_manual.h5']missing_files = [f for f in required_files if not os.path.exists(f)]
if missing_files: print(f"FATAL ERROR: The following model files are missing: {', '.join(missing_files)}.") print("Please ensure you ran 'train_ann_manual.py' successfully first.") # In a real app, you would exit or raise an error here. # For this demonstration, we'll try to load, expecting failure if files are missing.
try: # Load the manual artifacts y_scaler = load('y_scaler_manual.pkl') scaler = load('scaler_manual.pkl') # Standard Scaler for numerical features encoder = joblib.load('encoder_manual.pkl') # OneHotEncoder for categorical features
# Load the model custom_objects = {'mse': MeanSquaredError()} model = load_model('ann_model_manual.h5', custom_objects=custom_objects)
print("All manual model artifacts loaded successfully.")except Exception as e: print(f"An error occurred during model loading: {e}") exit()
# --- 2. Define Prediction Function ---def predict_estimate( District, Settlement_Type, Area_sft, Land_Type, Building_Type, Floor_Count, Design_Complexity, BBS_kg_per_sft): """ Takes 8 simple user inputs, manually preprocesses them (scales/encodes), and predicts the total estimate cost using the ANN model. """
# Create a DataFrame from the 8 simple inputs input_data = pd.DataFrame({ 'District': [District], 'Settlement_Type': [Settlement_Type], 'Area_sft': [Area_sft], 'Land_Type': [Land_Type], 'Building_Type': [Building_Type], 'Floor_Count': [Floor_Count], 'Design_Complexity': [Design_Complexity], 'BBS_kg_per_sft': [BBS_kg_per_sft] })
# --- Manual Preprocessing Steps (Mirroring the training script) ---
# 2a. Separate features X_num = input_data[NUMERICAL_FEATURES] X_cat = input_data[CATEGORICAL_FEATURES]
# 2b. Transform Numerical (Scale) # The scaler object was saved during training and is loaded above X_num_scaled = scaler.transform(X_num)
# 2c. Transform Categorical (Encode) # The encoder object was saved during training and is loaded above X_cat_encoded = encoder.transform(X_cat)
# 2d. Combine and prepare for prediction (Numerical first, then Categorical) input_processed = np.hstack([X_num_scaled, X_cat_encoded])
# --- Prediction ---
# Step 1: Make the prediction (output is scaled, 0 to 1) prediction_scaled = model.predict(input_processed, verbose=0)[0][0]
# Step 2: Convert the scaled prediction back to the real PKR amount (Inverse Transform) prediction_pkr = y_scaler.inverse_transform([[prediction_scaled]])[0][0]
# Handle potential negative prediction due to inverse transform if prediction is outside training bounds if prediction_pkr < 0: prediction_pkr = 0
return f"Estimated Total Cost: PKR {prediction_pkr:,.2f}"import numpy as np
# --- 3. Setup Gradio Interface Components ---DISTRICTS = ['Ghanche', 'Ghizer', 'Nagar', 'Astore', 'Diamer', 'Skardu', 'Shigar', 'Hunza', 'Gilgit', 'Roundu']SETTLEMENT_TYPES = ['Rural', 'Sub-Rural', 'Urban']LAND_TYPES = ['Commercial', 'Uncultivated', 'Cultivated']BUILDING_TYPES = ['Commercial', 'Road', 'Residential']# Load Modelmodel = joblib.load("model.pkl")
# These 8 fields are what the user seesinputs = [ gr.Dropdown(DISTRICTS, label="1. District (Location)", value='Gilgit'), gr.Dropdown(SETTLEMENT_TYPES, label="2. Settlement Type (Urban/Rural)", value='Urban'), gr.Number(label="3. Area (sq ft)", value=2500, minimum=100, step=1), gr.Dropdown(LAND_TYPES, label="4. Land Type", value='Commercial'), gr.Dropdown(BUILDING_TYPES, label="5. Building Type", value='Residential'), gr.Number(label="6. Floor Count", value=3, minimum=1, step=1), gr.Number(label="7. Design Complexity (1=Simple, 5=Complex)", value=3, minimum=1, maximum=5, step=1), gr.Number(label="8. Steel/Rebar per sq ft (BBS kg/sft)", value=0, minimum=0, step=0.1)]# Prediction Functiondef predict(length, width, height, steel_rate, cement_rate, sand_rate): features = np.array([[length, width, height, steel_rate, cement_rate, sand_rate]]) estimate = model.predict(features)[0] return f"{estimate:,.2f} PKR"
# --- 4. Launch Gradio Interface ---# Gradio UIiface = gr.Interface( fn=predict_estimate, inputs=inputs, outputs=gr.Text(label="Predicted Total Estimate"), title="Simplified Construction Cost Predictor (Manual ANN)", description="This predictive tool uses an Artificial Neural Network trained only on 8 core structural and location features. Note: All underlying cost factors are fixed based on typical values from the training data.", allow_flagging="never" fn=predict, inputs=[ gr.Number(label="Length (ft)"), gr.Number(label="Width (ft)"), gr.Number(label="Height (ft)"), gr.Number(label="Steel Rate /kg"), gr.Number(label="Cement Rate /bag"), gr.Number(label="Sand Rate /cft"), ], outputs=gr.Textbox(label="Estimated Construction Cost (PKR)"), title="🏗️ Construction Estimate Calculator", description="Enter building dimensions & material rates to get the cost estimate using an AI ANN model.",)
iface.launch(inbrowser=True)iface.launch()app.py+22-301