Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import osimport jsonimport joblibimport pandas as pdimport gradio as grBASE_DIR = os.path.dirname(os.path.abspath(__file__))MODELS_DIR = os.path.join(BASE_DIR, "models")MODEL_CANDIDATES = [os.path.join(MODELS_DIR, "best_model.pkl"),os.path.join(MODELS_DIR, "best_model (1).pkl"),]FEATURE_FILE = os.path.join(MODELS_DIR, "feature_names.txt")INFO_FILE = os.path.join(MODELS_DIR, "model_info.json")def find_existing_file(paths):for path in paths:if os.path.exists(path):return pathreturn Nonedef load_artifacts():model_path = find_existing_file(MODEL_CANDIDATES)if model_path is None:raise FileNotFoundError(f"Model file not found. Looked for: {', '.join(MODEL_CANDIDATES)}")if not os.path.exists(FEATURE_FILE):raise FileNotFoundError(f"Feature file not found: {FEATURE_FILE}")model = joblib.load(model_path)with open(FEATURE_FILE, "r", encoding="utf-8") as f:feature_names = [line.strip() for line in f if line.strip()]model_info = {}if os.path.exists(INFO_FILE):with open(INFO_FILE, "r", encoding="utf-8") as f:model_info = json.load(f)return model, feature_names, model_info, model_pathtry:model, feature_names, model_info, model_path = load_artifacts()except Exception as e:raise RuntimeError(f"Failed to load artifacts: {e}")def predict_engine_condition(*values):input_df = pd.DataFrame([dict(zip(feature_names, values))])try:prediction = model.predict(input_df)[0]result_text = f"Predicted Engine Condition: {prediction}"if hasattr(model, "predict_proba"):proba = model.predict_proba(input_df)proba_df = pd.DataFrame(proba,columns=[f"Class {i}" for i in range(proba.shape[1])])return result_text, proba_dfreturn result_text, pd.DataFrame()except Exception as e:return f"Prediction failed: {e}", pd.DataFrame()with gr.Blocks() as demo:gr.Markdown("# Engine Condition Prediction App")gr.Markdown("Enter sensor values to predict the engine condition.")with gr.Row():with gr.Column(scale=1):gr.Markdown("### Model Details")gr.Markdown(f"**Loaded model:** `{os.path.basename(model_path)}`")gr.Markdown(f"**Best model name:** {model_info.get('best_model_name', 'Unknown')}")gr.Markdown(f"**Test F1:** {model_info.get('test_f1', 'N/A')}")gr.Markdown(f"**Number of features:** {len(feature_names)}")with gr.Column(scale=2):gr.Markdown("### Input Features")inputs = []for feature in feature_names:inputs.append(gr.Number(label=feature,value=0.0,precision=4))predict_btn = gr.Button("Predict Engine Condition", variant="primary")gr.Markdown("### Prediction Output")result_box = gr.Textbox(label="Prediction", interactive=False)proba_box = gr.Dataframe(label="Prediction Probabilities")predict_btn.click(fn=predict_engine_condition,inputs=inputs,outputs=[result_box, proba_box])if __name__ == "__main__":demo.launch(theme=gr.themes.Soft())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import jsonimport joblibimport pandas as pdimport gradio as grfrom huggingface_hub import hf_hub_downloadMODEL_REPO = "Swetha1929/predictive-maintenance-engine-model"# Download files from the HF model repositorymodel_path = hf_hub_download(repo_id=MODEL_REPO,filename="best_model.pkl")feature_path = hf_hub_download(repo_id=MODEL_REPO,filename="feature_names.txt")info_path = hf_hub_download(repo_id=MODEL_REPO,filename="model_info.json")# Load modelmodel = joblib.load(model_path)# Load featureswith open(feature_path, "r") as f:feature_names = [line.strip() for line in f]# Load metadatawith open(info_path) as f:model_info = json.load(f)def predict(*values):df = pd.DataFrame([dict(zip(feature_names, values))])pred = model.predict(df)[0]return str(pred)with gr.Blocks() as demo:gr.Markdown("# Engine Condition Prediction")inputs = []for feature in feature_names:inputs.append(gr.Number(label=feature))output = gr.Textbox(label="Prediction")btn = gr.Button("Predict")btn.click(predict,inputs=inputs,outputs=output)demo.launch()
app.py+38-86