Spaces:
Runtime error
Runtime error
| with open("app.py", "w") as f: | |
| f.write(""" | |
| import os | |
| import torch | |
| import torch.nn as nn | |
| import gradio as gr | |
| import pickle | |
| import pandas as pd | |
| print("Starting application...") | |
| print("Current directory:", os.getcwd()) | |
| print("Files in directory:", os.listdir()) | |
| class TabTransformer(nn.Module): | |
| def __init__(self, input_dim, num_classes=2, d_model=64, nhead=4, num_layers=3, dropout=0.1): | |
| super().__init__() | |
| self.embedding = nn.Linear(input_dim, d_model) | |
| encoder_layer = nn.TransformerEncoderLayer( | |
| d_model=d_model, nhead=nhead, dim_feedforward=d_model * 4, dropout=dropout, activation='gelu' | |
| ) | |
| self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) | |
| self.fc = nn.Sequential( | |
| nn.Linear(d_model, d_model // 2), | |
| nn.ReLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model // 2, num_classes) | |
| ) | |
| def forward(self, x): | |
| x = self.embedding(x) | |
| x = x.unsqueeze(0) | |
| x = self.transformer_encoder(x) | |
| x = x.squeeze(0) | |
| return self.fc(x) | |
| def predict(*inputs): | |
| try: | |
| print("Prediction started...") | |
| # Feature lists | |
| categorical_features = ['Multifocal_PVC', 'Nonsustained_VT', 'gender', 'HTN', 'DM', 'Fullcompansasion'] | |
| numeric_features = ['pvc_percent', 'PVCQRS', 'EF', 'Age', 'PVC_Prematurity_index', 'QRS_ratio', | |
| 'mean_HR', 'symptom_duration', 'QTc_sinus', 'PVCCI_dispersion', | |
| 'CI_variability', 'PVC_Peak_QRS_duration', 'PVCCI', 'PVC_Compansatory_interval'] | |
| # Split inputs | |
| cat_inputs = inputs[:len(categorical_features)] | |
| num_inputs = inputs[len(categorical_features):] | |
| # Convert inputs | |
| cat_data = [1 if val == "Yes" else 0 for val in cat_inputs] | |
| num_data = [float(val) for val in num_inputs] | |
| # Create DataFrame | |
| data = pd.DataFrame([cat_data + num_data], columns=categorical_features + numeric_features) | |
| print("Data prepared:", data.shape) | |
| # Load scaler and transform data | |
| with open("trans_scaler.pkl", 'rb') as f: | |
| scaler = pickle.load(f) | |
| scaled_data = scaler.transform(data) | |
| print("Data scaled") | |
| # Load model and predict | |
| input_dim = len(categorical_features) + len(numeric_features) | |
| model = TabTransformer(input_dim=input_dim) | |
| model.load_state_dict(torch.load("tabtransformer_model.pth", map_location='cpu')) | |
| model.eval() | |
| with torch.no_grad(): | |
| tensor_data = torch.FloatTensor(scaled_data) | |
| output = model(tensor_data) | |
| probabilities = torch.softmax(output, dim=1) | |
| print("Prediction completed") | |
| return { | |
| "Response Probability": float(probabilities[0][0]), | |
| "Non-Response Probability": float(probabilities[0][1]) | |
| } | |
| except Exception as e: | |
| print(f"Error in prediction: {str(e)}") | |
| return {"error": str(e)} | |
| # Default values | |
| numeric_defaults = { | |
| 'pvc_percent': 11.96, 'PVCQRS': 155.1, 'EF': 59.93, 'Age': 52.19, | |
| 'PVC_Prematurity_index': 0.6158, 'QRS_ratio': 1.933, 'mean_HR': 71.28, | |
| 'symptom_duration': 14.91, 'QTc_sinus': 425.0, 'PVCCI_dispersion': 57.1, | |
| 'CI_variability': 22.98, 'PVC_Peak_QRS_duration': 76.13, 'PVCCI': 513.4, | |
| 'PVC_Compansatory_interval': 1044 | |
| } | |
| # Create interface | |
| demo = gr.Interface( | |
| fn=predict, | |
| inputs=[ | |
| gr.Dropdown(choices=["Yes", "No"], label="Multifocal_PVC"), | |
| gr.Dropdown(choices=["Yes", "No"], label="Nonsustained_VT"), | |
| gr.Dropdown(choices=["Yes", "No"], label="gender"), | |
| gr.Dropdown(choices=["Yes", "No"], label="HTN"), | |
| gr.Dropdown(choices=["Yes", "No"], label="DM"), | |
| gr.Dropdown(choices=["Yes", "No"], label="Fullcompansasion"), | |
| gr.Number(value=numeric_defaults['pvc_percent'], label="pvc_percent"), | |
| gr.Number(value=numeric_defaults['PVCQRS'], label="PVCQRS"), | |
| gr.Number(value=numeric_defaults['EF'], label="EF"), | |
| gr.Number(value=numeric_defaults['Age'], label="Age"), | |
| gr.Number(value=numeric_defaults['PVC_Prematurity_index'], label="PVC_Prematurity_index"), | |
| gr.Number(value=numeric_defaults['QRS_ratio'], label="QRS_ratio"), | |
| gr.Number(value=numeric_defaults['mean_HR'], label="mean_HR"), | |
| gr.Number(value=numeric_defaults['symptom_duration'], label="symptom_duration"), | |
| gr.Number(value=numeric_defaults['QTc_sinus'], label="QTc_sinus"), | |
| gr.Number(value=numeric_defaults['PVCCI_dispersion'], label="PVCCI_dispersion"), | |
| gr.Number(value=numeric_defaults['CI_variability'], label="CI_variability"), | |
| gr.Number(value=numeric_defaults['PVC_Peak_QRS_duration'], label="PVC_Peak_QRS_duration"), | |
| gr.Number(value=numeric_defaults['PVCCI'], label="PVCCI"), | |
| gr.Number(value=numeric_defaults['PVC_Compansatory_interval'], label="PVC_Compansatory_interval") | |
| ], | |
| outputs=gr.Label(label="Prediction"), | |
| title="PVC Response Predictor", | |
| description="Enter patient features to predict response probability" | |
| ) | |
| if __name__ == "__main__": | |
| print("Launching application...") | |
| demo.launch()""") |