hh / app.py
ssenaay's picture
Update app.py
dfc47a3 verified
Raw
History Blame Contribute Delete
37.6 kB
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingRegressor, GradientBoostingClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error, accuracy_score, classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.impute import SimpleImputer
import json
import bcrypt
import os
from datetime import datetime
import joblib
import warnings
warnings.filterwarnings('ignore')
# Authentication system with bcrypt
class AuthSystem:
def __init__(self, auth_file="user_auth.json"):
self.auth_file = auth_file
self.load_auth_data()
def load_auth_data(self):
"""Load authentication data from JSON file"""
if os.path.exists(self.auth_file):
with open(self.auth_file, 'r') as f:
self.auth_data = json.load(f)
else:
# Initialize with default credentials
self.auth_data = {
"username": "admin",
"password_hash": self.hash_password("admin123"),
"created_at": datetime.now().isoformat()
}
self.save_auth_data()
def save_auth_data(self):
"""Save authentication data to JSON file"""
with open(self.auth_file, 'w') as f:
json.dump(self.auth_data, f, indent=2)
def hash_password(self, password):
"""Hash password using bcrypt"""
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def verify_password(self, password, hashed):
"""Verify password against hash"""
return bcrypt.checkpw(password.encode(), hashed.encode())
def register(self, username, password):
"""Register new user (overwrites existing)"""
if not username or not password:
return False, "Kullanıcı adı ve şifre gereklidir"
if len(password) < 6:
return False, "Şifre en az 6 karakter olmalıdır"
self.auth_data = {
"username": username,
"password_hash": self.hash_password(password),
"created_at": datetime.now().isoformat()
}
self.save_auth_data()
return True, "Kullanıcı başarıyla kaydedildi"
def login(self, username, password):
"""Authenticate user"""
if not username or not password:
return False, "Kullanıcı adı ve şifre gereklidir"
if (self.auth_data.get("username") == username and
self.verify_password(password, self.auth_data.get("password_hash"))):
return True, "Giriş başarılı"
else:
return False, "Geçersiz kullanıcı bilgileri"
# Initialize authentication system
auth_system = AuthSystem()
def authenticate_user(username, password):
"""Authentication function for Gradio"""
success, message = auth_system.login(username, password)
return success, message
def register_user(username, password):
"""Registration function for Gradio"""
success, message = auth_system.register(username, password)
return success, message
def analyze_data(file, progress=gr.Progress()):
"""Enhanced data analysis function with progress tracking"""
if file is None:
fig, ax = plt.subplots(figsize=(1,1))
fig.patch.set_visible(False)
ax.axis('off')
plt.close(fig)
return "Lütfen bir CSV dosyası yükleyin.", fig, fig, None, None, None, [], None, None, None, None, None
try:
progress(0.1, desc="Dosya okunuyor...")
# Check file size (limit to 100MB)
file_size = os.path.getsize(file.name)
if file_size > 100 * 1024 * 1024:
raise Exception("Dosya boyutu 100MB'dan küçük olmalıdır")
# Read CSV with error handling
try:
df = pd.read_csv(file.name, encoding='utf-8')
except UnicodeDecodeError:
df = pd.read_csv(file.name, encoding='latin-1')
progress(0.3, desc="Veri analiz ediliyor...")
# Basic dataset information
num_rows, num_cols = df.shape
column_info = "\n".join([f"- {col} ({df[col].dtype})" for col in df.columns])
# Missing values analysis
missing_values_info = df.isnull().sum()
missing_values_report = "Eksik Değerler:\n" + missing_values_info[missing_values_info > 0].to_string()
if missing_values_info.sum() == 0:
missing_values_report = "Eksik değer bulunamadı."
progress(0.5, desc="Sütunlar analiz ediliyor...")
# Column explanations (automatic analysis)
column_explanations = generate_column_explanations(df)
progress(0.7, desc="Grafikler oluşturuluyor...")
# Correlation matrix
correlation_plot_figure = create_correlation_plot(df)
# Feature importance plot (initially empty)
feature_importance_fig = create_empty_plot()
progress(0.9, desc="İstatistikler hesaplanıyor...")
# Basic statistics
numeric_df = df.select_dtypes(include=[np.number])
basic_stats = ""
if not numeric_df.empty:
basic_stats = "Temel İstatistikler:\n" + numeric_df.describe().to_string()
# Outlier detection
outlier_info = detect_outliers(df)
summary_text = (
f"## ✅ Veri Seti Başarıyla Yüklendi!\n\n"
f"- **Satır Sayısı:** {num_rows:,}\n"
f"- **Sütun Sayısı:** {num_cols}\n"
f"- **Dosya Boyutu:** {file_size / 1024:.2f} KB\n\n"
f"### 📋 Sütun Bilgileri:\n```\n{column_info}\n```\n\n"
f"### ⚠️ Eksik Değer Raporu:\n```\n{missing_values_report}\n```\n\n"
f"### 🔍 Aykırı Değer Tespiti:\n```\n{outlier_info}\n```\n\n"
f"### 📊 Temel İstatistikler (Sayısal Sütunlar):\n```\n{basic_stats}\n```\n\n"
f"### 👀 İlk 5 Satır:\n```\n{df.head().to_string(max_rows=5, max_cols=10)}\n```"
)
progress(1.0, desc="Tamamlandı!")
return (summary_text, correlation_plot_figure, feature_importance_fig, column_explanations,
"", "", [str(col) for col in df.columns], df, None, None, None, None)
except Exception as e:
fig, ax = plt.subplots(figsize=(1,1))
fig.patch.set_visible(False)
ax.axis('off')
plt.close(fig)
return f"❌ Dosya işlenirken hata oluştu: {str(e)}", fig, fig, "", "", "", [], None, None, None, None, None
def detect_outliers(df):
"""Detect outliers using IQR method"""
numeric_df = df.select_dtypes(include=[np.number])
outlier_report = []
for col in numeric_df.columns:
Q1 = numeric_df[col].quantile(0.25)
Q3 = numeric_df[col].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = numeric_df[(numeric_df[col] < lower_bound) | (numeric_df[col] > upper_bound)][col]
if len(outliers) > 0:
outlier_report.append(f"{col}: {len(outliers)} aykırı değer tespit edildi ({len(outliers)/len(df)*100:.2f}%)")
if not outlier_report:
return "Aykırı değer tespit edilmedi."
return "\n".join(outlier_report)
def generate_column_explanations(df):
"""Generate automatic explanations for each column"""
explanations = []
for col in df.columns:
col_data = df[col]
dtype = col_data.dtype
if pd.api.types.is_numeric_dtype(col_data):
# Numeric column analysis
unique_count = col_data.nunique()
null_count = col_data.isnull().sum()
mean_val = col_data.mean()
std_val = col_data.std()
min_val = col_data.min()
max_val = col_data.max()
explanation = f"**{col}** (Sayısal):\n"
explanation += f"- Benzersiz değerler: {unique_count}\n"
explanation += f"- Eksik değerler: {null_count} ({null_count/len(df)*100:.2f}%)\n"
explanation += f"- Ortalama: {mean_val:.2f}\n"
explanation += f"- Standart sapma: {std_val:.2f}\n"
explanation += f"- Min: {min_val:.2f}, Max: {max_val:.2f}\n"
if unique_count < 10:
explanation += f"- Olası kategorik değerler: {sorted(col_data.unique())}\n"
else:
# Categorical column analysis
unique_count = col_data.nunique()
null_count = col_data.isnull().sum()
most_common = col_data.value_counts().head(3)
explanation = f"**{col}** (Kategorik):\n"
explanation += f"- Benzersiz değerler: {unique_count}\n"
explanation += f"- Eksik değerler: {null_count} ({null_count/len(df)*100:.2f}%)\n"
explanation += f"- En yaygın değerler:\n"
for val, count in most_common.items():
explanation += f" * {val}: {count} ({count/len(df)*100:.2f}%)\n"
explanations.append(explanation)
return "\n\n".join(explanations)
def create_correlation_plot(df):
"""Create correlation matrix plot"""
numeric_df = df.select_dtypes(include=[np.number])
if numeric_df.empty or len(numeric_df.columns) < 2:
return create_empty_plot()
fig, ax = plt.subplots(figsize=(12, 10))
corr_matrix = numeric_df.corr()
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt=".2f", ax=ax,
cbar_kws={'label': 'Korelasyon Katsayısı'})
ax.set_title("Sayısal Sütunların Korelasyon Matrisi", fontsize=16, fontweight='bold')
plt.tight_layout()
return fig
def create_empty_plot():
"""Create empty plot"""
fig, ax = plt.subplots(figsize=(1,1))
fig.patch.set_visible(False)
ax.axis('off')
plt.close(fig)
return fig
def run_ml_analysis(df_state, target_column, missing_strategy, scale_features, use_cv, n_cv_folds, progress=gr.Progress()):
"""Run comprehensive machine learning analysis"""
if df_state is None:
return "❌ Lütfen önce bir CSV dosyası yükleyin.", "", None, None, None, None
if not target_column:
return "❌ Lütfen bir hedef değişken seçin.", "", None, None, None, None
if target_column not in df_state.columns:
return f"❌ Hata: '{target_column}' sütunu veri setinde bulunamadı.", "", None, None, None, None
try:
progress(0.1, desc="Veri hazırlanıyor...")
df = df_state.copy()
# Remove rows with missing target values
if df[target_column].isnull().any():
initial_rows = len(df)
df.dropna(subset=[target_column], inplace=True)
rows_after_drop = len(df)
if rows_after_drop == 0:
return ("❌ Hata: Hedef değişkendeki eksik değerler nedeniyle tüm satırlar silindi.",
"", None, None, None, None)
# Prepare data
X = df.drop(columns=[target_column])
y = df[target_column]
progress(0.2, desc="Kategorik değişkenler işleniyor...")
# Handle categorical variables
categorical_columns = X.select_dtypes(include=['object']).columns
label_encoders = {}
for col in categorical_columns:
if X[col].isnull().any():
X[col] = X[col].fillna('Missing')
le = LabelEncoder()
X[col] = le.fit_transform(X[col].astype(str))
label_encoders[col] = le
# Handle missing values in features
numeric_feature_cols = X.select_dtypes(include=[np.number]).columns
if not numeric_feature_cols.empty and X[numeric_feature_cols].isnull().any().any():
if missing_strategy == "Ortalama":
imputer = SimpleImputer(strategy='mean')
elif missing_strategy == "Medyan":
imputer = SimpleImputer(strategy='median')
else: # "Mod"
imputer = SimpleImputer(strategy='most_frequent')
X[numeric_feature_cols] = imputer.fit_transform(X[numeric_feature_cols])
if X.empty or len(y) == 0:
return ("❌ Hata: Ön işleme sonrası veri kalmadı.", "", None, None, None, None)
if len(y) < 2:
return ("❌ Hata: ML analizi için yeterli örnek yok.", "", None, None, None, None)
progress(0.3, desc="Problem tipi belirleniyor...")
# Determine problem type
if y.dtype == 'object' or (pd.api.types.is_numeric_dtype(y) and y.nunique() < 20):
problem_type = 'classification'
le_y = LabelEncoder()
y = le_y.fit_transform(y.astype(str))
else:
problem_type = 'regression'
# Feature scaling
if scale_features:
progress(0.4, desc="Özellikler ölçeklendiriliyor...")
scaler = StandardScaler()
X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)
progress(0.5, desc="Veri bölünüyor...")
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
results_text = ""
feature_importance_data = None
predictions_plot = None
confusion_matrix_plot = None
cv_results_text = ""
if problem_type == 'regression':
progress(0.6, desc="Regresyon modelleri eğitiliyor...")
# Linear Regression
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
lr_pred = lr_model.predict(X_test)
lr_r2 = r2_score(y_test, lr_pred)
lr_mae = mean_absolute_error(y_test, lr_pred)
lr_rmse = np.sqrt(mean_squared_error(y_test, lr_pred))
# Random Forest
rf_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
rf_model.fit(X_train, y_train)
rf_pred = rf_model.predict(X_test)
rf_r2 = r2_score(y_test, rf_pred)
rf_mae = mean_absolute_error(y_test, rf_pred)
rf_rmse = np.sqrt(mean_squared_error(y_test, rf_pred))
# Gradient Boosting
gb_model = GradientBoostingRegressor(n_estimators=100, random_state=42)
gb_model.fit(X_train, y_train)
gb_pred = gb_model.predict(X_test)
gb_r2 = r2_score(y_test, gb_pred)
gb_mae = mean_absolute_error(y_test, gb_pred)
gb_rmse = np.sqrt(mean_squared_error(y_test, gb_pred))
progress(0.8, desc="Sonuçlar hazırlanıyor...")
# Feature importance
feature_importance_data = pd.DataFrame({
'feature': X.columns,
'importance': rf_model.feature_importances_
}).sort_values('importance', ascending=False)
# Cross-validation
if use_cv:
progress(0.85, desc="Cross-validation yapılıyor...")
rf_cv_scores = cross_val_score(rf_model, X, y, cv=n_cv_folds, scoring='r2')
cv_results_text = f"\n\n🔄 Cross-Validation Sonuçları (Random Forest, {n_cv_folds}-Fold):\n"
cv_results_text += f"- Ortalama R² Skoru: {rf_cv_scores.mean():.4f}{rf_cv_scores.std():.4f})\n"
cv_results_text += f"- Min: {rf_cv_scores.min():.4f}, Max: {rf_cv_scores.max():.4f}"
results_text = f"""📊 **Makine Öğrenimi Analiz Sonuçları (Regresyon)**
🔹 **Doğrusal Regresyon:**
- R² Skoru: {lr_r2:.4f}
- MAE: {lr_mae:.4f}
- RMSE: {lr_rmse:.4f}
🔹 **Rastgele Orman:**
- R² Skoru: {rf_r2:.4f}
- MAE: {rf_mae:.4f}
- RMSE: {rf_rmse:.4f}
🔹 **Gradient Boosting:**
- R² Skoru: {gb_r2:.4f}
- MAE: {gb_mae:.4f}
- RMSE: {gb_rmse:.4f}
🏆 **En İyi Model:** {"Gradient Boosting" if gb_r2 == max(lr_r2, rf_r2, gb_r2) else "Rastgele Orman" if rf_r2 == max(lr_r2, rf_r2, gb_r2) else "Doğrusal Regresyon"}
📈 **Özellik Önemi (İlk 10):**
{feature_importance_data.head(10).to_string(index=False)}
{cv_results_text}"""
# Predictions plot
predictions_plot = plot_predictions(y_test, rf_pred, "Rastgele Orman")
# Save best model
best_model = rf_model if rf_r2 >= max(lr_r2, gb_r2) else (gb_model if gb_r2 >= lr_r2 else lr_model)
model_path = "saved_model.pkl"
joblib.dump(best_model, model_path)
else: # Classification
progress(0.6, desc="Sınıflandırma modelleri eğitiliyor...")
# Logistic Regression
lr_model = LogisticRegression(random_state=42, max_iter=1000, n_jobs=-1)
lr_model.fit(X_train, y_train)
lr_pred = lr_model.predict(X_test)
lr_accuracy = accuracy_score(y_test, lr_pred)
# Random Forest
rf_model = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
rf_model.fit(X_train, y_train)
rf_pred = rf_model.predict(X_test)
rf_accuracy = accuracy_score(y_test, rf_pred)
# Gradient Boosting
gb_model = GradientBoostingClassifier(n_estimators=100, random_state=42)
gb_model.fit(X_train, y_train)
gb_pred = gb_model.predict(X_test)
gb_accuracy = accuracy_score(y_test, gb_pred)
progress(0.8, desc="Sonuçlar hazırlanıyor...")
# Feature importance
feature_importance_data = pd.DataFrame({
'feature': X.columns,
'importance': rf_model.feature_importances_
}).sort_values('importance', ascending=False)
# Confusion matrix
confusion_matrix_plot = plot_confusion_matrix(y_test, rf_pred, le_y.classes_)
# Cross-validation
if use_cv:
progress(0.85, desc="Cross-validation yapılıyor...")
rf_cv_scores = cross_val_score(rf_model, X, y, cv=n_cv_folds, scoring='accuracy')
cv_results_text = f"\n\n🔄 Cross-Validation Sonuçları (Random Forest, {n_cv_folds}-Fold):\n"
cv_results_text += f"- Ortalama Doğruluk: {rf_cv_scores.mean():.4f}{rf_cv_scores.std():.4f})\n"
cv_results_text += f"- Min: {rf_cv_scores.min():.4f}, Max: {rf_cv_scores.max():.4f}"
results_text = f"""📊 **Makine Öğrenimi Analiz Sonuçları (Sınıflandırma)**
🔹 **Lojistik Regresyon:**
- Doğruluk: {lr_accuracy:.4f}
🔹 **Rastgele Orman:**
- Doğruluk: {rf_accuracy:.4f}
🔹 **Gradient Boosting:**
- Doğruluk: {gb_accuracy:.4f}
🏆 **En İyi Model:** {"Gradient Boosting" if gb_accuracy == max(lr_accuracy, rf_accuracy, gb_accuracy) else "Rastgele Orman" if rf_accuracy == max(lr_accuracy, rf_accuracy, gb_accuracy) else "Lojistik Regresyon"}
📋 **Sınıflandırma Raporu (Rastgele Orman):**
{classification_report(y_test, rf_pred, target_names=le_y.classes_)}
📈 **Özellik Önemi (İlk 10):**
{feature_importance_data.head(10).to_string(index=False)}
{cv_results_text}"""
# Save best model
best_model = rf_model if rf_accuracy >= max(lr_accuracy, gb_accuracy) else (gb_model if gb_accuracy >= lr_accuracy else lr_model)
model_path = "saved_model.pkl"
joblib.dump(best_model, model_path)
# Model summary
model_summary = f"""🔧 **Model Bilgileri:**
- Problem Tipi: {problem_type.title()}
- Kullanılan Özellikler: {len(X.columns)}
- Eğitim Örnekleri: {len(X_train):,}
- Test Örnekleri: {len(X_test):,}
- Özellik Ölçeklendirme: {'Evet' if scale_features else 'Hayır'}
- Eksik Değer Stratejisi: {missing_strategy}
- Model Kaydedildi: saved_model.pkl"""
# Feature importance plot
feature_importance_fig = plot_feature_importance(feature_importance_data)
progress(1.0, desc="Tamamlandı!")
return (results_text, model_summary, feature_importance_fig,
predictions_plot if problem_type == 'regression' else confusion_matrix_plot,
model_path, feature_importance_data)
except Exception as e:
return f"❌ ML analizi sırasında hata oluştu: {str(e)}", f"❌ Hata: {str(e)}", None, None, None, None
def plot_feature_importance(feature_importance_data):
"""Plot feature importance"""
if feature_importance_data is None or feature_importance_data.empty:
return create_empty_plot()
fig, ax = plt.subplots(figsize=(10, 8))
top_features = feature_importance_data.head(15)
ax.barh(top_features['feature'], top_features['importance'], color='steelblue')
ax.set_xlabel('Önem Skoru', fontsize=12)
ax.set_ylabel('Özellik', fontsize=12)
ax.set_title('En Önemli 15 Özellik', fontsize=14, fontweight='bold')
ax.invert_yaxis()
plt.tight_layout()
return fig
def plot_predictions(y_test, y_pred, model_name):
"""Plot actual vs predicted values"""
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(y_test, y_pred, alpha=0.6, edgecolors='k', s=50)
# Perfect prediction line
min_val = min(y_test.min(), y_pred.min())
max_val = max(y_test.max(), y_pred.max())
ax.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Mükemmel Tahmin')
ax.set_xlabel('Gerçek Değerler', fontsize=12)
ax.set_ylabel('Tahmin Edilen Değerler', fontsize=12)
ax.set_title(f'Gerçek vs Tahmin Edilen Değerler ({model_name})', fontsize=14, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_confusion_matrix(y_test, y_pred, class_names):
"""Plot confusion matrix"""
cm = confusion_matrix(y_test, y_pred)
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names,
yticklabels=class_names, ax=ax, cbar_kws={'label': 'Sayı'})
ax.set_xlabel('Tahmin Edilen Sınıf', fontsize=12)
ax.set_ylabel('Gerçek Sınıf', fontsize=12)
ax.set_title('Confusion Matrix (Rastgele Orman)', fontsize=14, fontweight='bold')
plt.tight_layout()
return fig
def download_model_file(model_path):
"""Return model file for download"""
if model_path and os.path.exists(model_path):
return model_path
return None
def export_results_to_csv(feature_importance_data):
"""Export feature importance to CSV"""
if feature_importance_data is not None:
output_path = "feature_importance.csv"
feature_importance_data.to_csv(output_path, index=False)
return output_path
return None
# Create Gradio interface
def create_interface():
with gr.Blocks(title="🤖 Gelişmiş Veri Analizi Sistemi", theme=gr.themes.Soft()) as demo:
# Authentication state
auth_state = gr.State(value=False)
# State variables
df_state = gr.State(value=None)
saved_model_path_state = gr.State(value=None)
feature_importance_state = gr.State(value=None)
# Login Interface (always visible at start)
with gr.Column(visible=True) as login_page:
gr.Markdown(
"""
# 🔐 Giriş Yap
Sisteme erişmek için lütfen giriş yapın.
"""
)
with gr.Row():
with gr.Column(scale=1):
pass
with gr.Column(scale=1):
login_username = gr.Textbox(
label="Kullanıcı Adı",
placeholder="Kullanıcı adınızı girin",
elem_id="login_username"
)
login_password = gr.Textbox(
label="Şifre",
type="password",
placeholder="Şifrenizi girin",
elem_id="login_password"
)
login_status = gr.Markdown("")
with gr.Row():
login_button = gr.Button("🚀 Giriş Yap", variant="primary", size="lg", scale=2)
register_page_button = gr.Button("📝 Kayıt Ol", variant="secondary", size="lg", scale=1)
gr.Markdown("---")
gr.Markdown("**💡 Varsayılan Giriş:** `admin` / `admin123`")
with gr.Column(scale=1):
pass
# Register Interface (hidden at start)
with gr.Column(visible=False) as register_page:
gr.Markdown(
"""
# ✍️ Yeni Hesap Oluştur
Sisteme kayıt olmak için bilgilerinizi girin.
"""
)
with gr.Row():
with gr.Column(scale=1):
pass
with gr.Column(scale=1):
register_username = gr.Textbox(
label="Kullanıcı Adı",
placeholder="Yeni kullanıcı adı seçin"
)
register_password = gr.Textbox(
label="Şifre",
type="password",
placeholder="Şifre (min 6 karakter)"
)
register_confirm_password = gr.Textbox(
label="Şifre Tekrar",
type="password",
placeholder="Şifreyi tekrar girin"
)
register_status = gr.Markdown("")
with gr.Row():
register_button = gr.Button("✅ Kayıt Ol", variant="primary", size="lg", scale=2)
back_to_login_button = gr.Button("◀️ Geri Dön", variant="secondary", size="lg", scale=1)
with gr.Column(scale=1):
pass
# Main Analysis Interface (hidden at start)
with gr.Column(visible=False) as analysis_page:
gr.Markdown("# 📊 Veri Analizi Sistemi")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📂 Veri Seti Yükleme")
file_input = gr.File(label="CSV Dosyası Yükle (Max 100MB)", file_types=[".csv"])
run_button = gr.Button("🚀 Analizi Başlat", variant="primary", size="lg")
gr.Markdown("---")
gr.Markdown("### 🤖 Makine Öğrenimi Ayarları")
target_column_dropdown = gr.Dropdown(
label="🎯 Hedef Değişkeni Seç",
choices=[],
interactive=True,
info="Tahmin edilecek sütunu seçin"
)
with gr.Accordion("⚙️ Gelişmiş Ayarlar", open=False):
missing_strategy = gr.Radio(
label="Eksik Değer Stratejisi",
choices=["Ortalama", "Medyan", "Mod"],
value="Ortalama",
info="Eksik değerleri nasıl doldurmak istersiniz?"
)
scale_features = gr.Checkbox(
label="Özellik Ölçeklendirme (StandardScaler)",
value=True,
info="Özellikleri normalize et"
)
use_cv = gr.Checkbox(
label="Cross-Validation Kullan",
value=True,
info="Model performansını daha iyi değerlendirmek için"
)
n_cv_folds = gr.Slider(
label="CV Fold Sayısı",
minimum=3,
maximum=10,
value=5,
step=1,
info="Cross-validation için fold sayısı"
)
run_ml_button = gr.Button("🎯 ML Analizi Çalıştır", variant="secondary", size="lg")
gr.Markdown("---")
gr.Markdown("### 💾 İndirme Seçenekleri")
download_model_button = gr.Button("📦 Modeli İndir (.pkl)", size="sm")
model_download_file = gr.File(label="Model Dosyası", visible=False)
download_feature_importance_button = gr.Button("📊 Özellik Önemini İndir (.csv)", size="sm")
feature_importance_download_file = gr.File(label="Özellik Önemi CSV", visible=False)
with gr.Column(scale=2):
gr.Markdown("### 📈 Analiz Sonuçları")
with gr.Tabs():
with gr.TabItem("📋 Veri Seti Genel Bakış"):
output_text = gr.Markdown(label="Analiz Sonuçları")
with gr.TabItem("🔍 Sütun Açıklamaları"):
column_explanations_output = gr.Textbox(
label="Sütun Detaylı Açıklamaları",
lines=20,
interactive=False,
show_copy_button=True
)
with gr.TabItem("🌡️ Korelasyon Matrisi"):
correlation_plot_output = gr.Plot(label="Sayısal Sütunların Korelasyon Matrisi")
with gr.TabItem("🎯 ML Sonuçları"):
ml_results_output = gr.Textbox(
label="Makine Öğrenimi Modeli Sonuçları",
lines=25,
interactive=False,
show_copy_button=True
)
ml_model_summary = gr.Textbox(
label="Model Özeti",
lines=10,
interactive=False,
show_copy_button=True
)
with gr.TabItem("📊 Özellik Önemi"):
feature_importance_plot = gr.Plot(label="En Önemli Özellikler")
with gr.TabItem("📈 Tahmin Grafiği"):
predictions_plot = gr.Plot(label="Gerçek vs Tahmin / Confusion Matrix")
# Page navigation functions
def show_register_page():
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
def show_login_page():
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
def show_analysis_page():
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
# Authentication event handlers
def handle_login(username, password):
success, message = authenticate_user(username, password)
if success:
return (
True,
f"✅ {message}",
gr.update(visible=False), # login_page
gr.update(visible=False), # register_page
gr.update(visible=True) # analysis_page
)
else:
return (
False,
f"❌ {message}",
gr.update(visible=True), # login_page
gr.update(visible=False), # register_page
gr.update(visible=False) # analysis_page
)
def handle_register(username, password, confirm_password):
if password != confirm_password:
return (
False,
"❌ Şifreler eşleşmiyor!",
gr.update(visible=False), # login_page
gr.update(visible=True), # register_page
gr.update(visible=False) # analysis_page
)
success, message = register_user(username, password)
if success:
return (
True,
f"✅ {message} Giriş sayfasına yönlendiriliyorsunuz...",
gr.update(visible=True), # login_page
gr.update(visible=False), # register_page
gr.update(visible=False) # analysis_page
)
else:
return (
False,
f"❌ {message}",
gr.update(visible=False), # login_page
gr.update(visible=True), # register_page
gr.update(visible=False) # analysis_page
)
# Navigation button events
register_page_button.click(
show_register_page,
outputs=[login_page, register_page, analysis_page]
)
back_to_login_button.click(
show_login_page,
outputs=[login_page, register_page, analysis_page]
)
# Authentication events
login_button.click(
handle_login,
inputs=[login_username, login_password],
outputs=[auth_state, login_status, login_page, register_page, analysis_page]
)
register_button.click(
handle_register,
inputs=[register_username, register_password, register_confirm_password],
outputs=[auth_state, register_status, login_page, register_page, analysis_page]
)
# Analysis event handlers
def update_dropdown_choices(df_state):
"""Update dropdown choices when new data is loaded"""
if df_state is not None:
valid_columns = [str(col) for col in df_state.columns if str(col).strip()]
return gr.update(choices=valid_columns, value=None)
return gr.update(choices=[], value=None)
# Data loading
run_button.click(
analyze_data,
inputs=file_input,
outputs=[
output_text,
correlation_plot_output,
feature_importance_plot,
column_explanations_output,
ml_results_output,
ml_model_summary,
target_column_dropdown,
df_state,
saved_model_path_state,
predictions_plot,
model_download_file,
feature_importance_download_file
]
)
# Update dropdown when data changes
df_state.change(
update_dropdown_choices,
inputs=df_state,
outputs=target_column_dropdown
)
# ML Analysis
run_ml_button.click(
run_ml_analysis,
inputs=[
df_state,
target_column_dropdown,
missing_strategy,
scale_features,
use_cv,
n_cv_folds
],
outputs=[
ml_results_output,
ml_model_summary,
feature_importance_plot,
predictions_plot,
saved_model_path_state,
feature_importance_state
]
)
# Download model
download_model_button.click(
download_model_file,
inputs=saved_model_path_state,
outputs=model_download_file
)
# Download feature importance
download_feature_importance_button.click(
export_results_to_csv,
inputs=feature_importance_state,
outputs=feature_importance_download_file
)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch(
share=False,
server_name="0.0.0.0",
show_error=True,
quiet=False
)