Spaces:
Runtime error
Runtime error
| 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 | |
| # Debug için print fonksiyonları | |
| print("Python version:", sys.version) | |
| print("Current working directory:", os.getcwd()) | |
| print("Directory contents:", os.listdir()) | |
| # TabTransformer Model Tanımı | |
| 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) | |
| # Özellikler | |
| 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'] | |
| numeric_means = { | |
| '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 | |
| } | |
| # Global değişkenler | |
| model = None | |
| scaler = None | |
| def load_model_and_scaler(): | |
| global model, scaler | |
| try: | |
| print("Model ve scaler yükleniyor...") | |
| # Model dosyası kontrolü | |
| model_path = "tabtransformer_model.pth" | |
| if not os.path.exists(model_path): | |
| raise FileNotFoundError(f"Model dosyası bulunamadı: {model_path}") | |
| # Scaler dosyası kontrolü | |
| scaler_path = "trans_scaler.pkl" | |
| if not os.path.exists(scaler_path): | |
| raise FileNotFoundError(f"Scaler dosyası bulunamadı: {scaler_path}") | |
| # Model yükleme | |
| input_dim = len(categorical_features) + len(numeric_features) | |
| model = TabTransformer(input_dim=input_dim) | |
| model.load_state_dict(torch.load(model_path, map_location='cpu')) | |
| model.eval() | |
| # Scaler yükleme | |
| with open(scaler_path, 'rb') as f: | |
| scaler = pickle.load(f) | |
| print("Model ve scaler başarıyla yüklendi!") | |
| return True | |
| except Exception as e: | |
| print(f"Model yükleme hatası: {str(e)}") | |
| return False | |
| def predict(*inputs): | |
| if model is None or scaler is None: | |
| return {"Error": "Model henüz yüklenmedi"} | |
| try: | |
| # Girdileri ayır | |
| cat_inputs = inputs[:len(categorical_features)] | |
| num_inputs = inputs[len(categorical_features):] | |
| # Kategorik verileri dönüştür | |
| cat_data = [1 if val == "Yes" else 0 for val in cat_inputs] | |
| # Sayısal verileri dönüştür | |
| num_data = [float(val) for val in num_inputs] | |
| # DataFrame oluştur | |
| data = pd.DataFrame([cat_data + num_data], columns=categorical_features + numeric_features) | |
| # Veriyi ölçeklendir | |
| scaled_data = scaler.transform(data) | |
| # Tahmin | |
| with torch.no_grad(): | |
| tensor_data = torch.FloatTensor(scaled_data) | |
| logits = model(tensor_data) | |
| probabilities = F.softmax(logits, dim=1).numpy() | |
| return { | |
| "Probability of Response": float(probabilities[0][0]), | |
| "Probability of Non-Response": float(probabilities[0][1]) | |
| } | |
| except Exception as e: | |
| print(f"Tahmin hatası: {str(e)}") | |
| return {"Error": str(e)} | |
| # Gradio arayüzü | |
| def create_interface(): | |
| inputs = [gr.Dropdown(choices=['Yes', 'No'], label=feat) for feat in categorical_features] | |
| inputs.extend([gr.Number(label=feat, value=numeric_means[feat]) for feat in numeric_features]) | |
| outputs = gr.Label(label="Prediction") | |
| return gr.Interface( | |
| fn=predict, | |
| inputs=inputs, | |
| outputs=outputs, | |
| title="TabTransformer Prediction", | |
| description="Enter the features to predict the response probability" | |
| ) | |
| if __name__ == "__main__": | |
| print("Uygulama başlatılıyor...") | |
| # Model ve scaler'ı yükle | |
| if not load_model_and_scaler(): | |
| print("Model yüklenemedi. Uygulama sonlandırılıyor.") | |
| sys.exit(1) | |
| # Arayüzü oluştur ve başlat | |
| try: | |
| demo = create_interface() | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |
| except Exception as e: | |
| print(f"Arayüz başlatma hatası: {str(e)}") | |
| sys.exit(1)""") |