with open("app.py", "w") as f: f.write(""" import os import sys import torch import torch.nn as nn import torch.nn.functional as F import gradio as gr import pickle import pandas as pd import warnings warnings.filterwarnings('ignore') print("Python version:", sys.version) print("Torch version:", torch.__version__) print("Current directory:", os.getcwd()) print("Directory contents:", 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) # Özellik listeleri 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'] # Varsayılan değerler 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 } try: print("Loading model...") # Model tanımı 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=torch.device('cpu'))) model.eval() print("Model loaded successfully") print("Loading scaler...") # Scaler yükleme with open("trans_scaler.pkl", "rb") as f: scaler = pickle.load(f) print("Scaler loaded successfully") except Exception as e: print(f"Error during initialization: {str(e)}") sys.exit(1) def predict(*inputs): try: # 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) # Scale data scaled_data = scaler.transform(data) # Predict with torch.no_grad(): tensor_data = torch.FloatTensor(scaled_data) outputs = model(tensor_data) probs = F.softmax(outputs, dim=1) response_prob = float(probs[0][0]) non_response_prob = float(probs[0][1]) return f"Response: {response_prob:.1%}\nNon-Response: {non_response_prob:.1%}" except Exception as e: print(f"Error in prediction: {str(e)}") return f"Error: {str(e)}" # Create interface with gr.Blocks() as demo: gr.Markdown("# PVC Response Predictor") gr.Markdown("Enter patient features to predict response probability") with gr.Row(): with gr.Column(): inputs = [] # Categorical inputs for feat in categorical_features: inputs.append(gr.Dropdown( choices=["Yes", "No"], value="No", label=feat )) # Numeric inputs for feat in numeric_features: inputs.append(gr.Number( value=numeric_defaults[feat], label=feat )) with gr.Column(): output = gr.Textbox(label="Prediction Results") submit_btn = gr.Button("Predict") submit_btn.click( fn=predict, inputs=inputs, outputs=output ) if __name__ == "__main__": print("Starting server...") demo.launch( server_name="0.0.0.0", show_error=True, share=False, debug=True )""")