File size: 4,808 Bytes
f899ab7
 
75cf953
ef39e84
f899ab7
 
8bdd542
f899ab7
 
 
ef39e84
 
f899ab7
ef39e84
 
f34b5b5
ef39e84
75cf953
f899ab7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75cf953
f899ab7
75cf953
f899ab7
 
ef39e84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f899ab7
888d601
f34b5b5
888d601
 
75cf953
f34b5b5
888d601
 
75cf953
f34b5b5
888d601
ef39e84
 
888d601
75cf953
ef39e84
888d601
75cf953
ef39e84
 
8bdd542
ef39e84
 
 
 
 
888d601
f34b5b5
8bdd542
f34b5b5
 
ef39e84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f899ab7
e830de4
ef39e84
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
    )""")