Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -143,9 +143,9 @@ df = df.drop(columns=DROP).dropna()
|
|
| 143 |
X, y = df.drop(columns="Görüs Tipi"), df["Görüs Tipi"]
|
| 144 |
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
|
| 145 |
|
| 146 |
-
|
| 147 |
-
Xtr_s =
|
| 148 |
-
Xte_s =
|
| 149 |
|
| 150 |
encoder = LabelEncoder()
|
| 151 |
ytr_e = encoder.fit_transform(y_tr)
|
|
@@ -159,25 +159,30 @@ grid = GridSearchCV(
|
|
| 159 |
grid.fit(Xtr_s, ytr_e)
|
| 160 |
best_params = grid.best_params_
|
| 161 |
|
|
|
|
| 162 |
full_plain = ConcreteXGBClassifier(n_bits=8, **best_params, random_state=42)
|
| 163 |
full_plain.fit(Xtr_s, ytr_e)
|
| 164 |
|
| 165 |
imp_df = pd.DataFrame({"col": X.columns, "imp": full_plain.feature_importances_})
|
|
|
|
| 166 |
imp_df["cum"] = imp_df["imp"].cumsum()
|
| 167 |
COLS = imp_df.loc[imp_df["cum"] <= 0.95, "col"].tolist()
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
scaler_sel = MinMaxScaler().fit(X_tr[COLS])
|
| 174 |
-
Xtr_sel = scaler_sel.transform(X_tr[COLS])
|
| 175 |
-
Xte_sel = scaler_sel.transform(X_te[COLS])
|
| 176 |
|
| 177 |
final_model = ConcreteXGBClassifier(n_bits=8, **best_params, random_state=42)
|
| 178 |
final_model.fit(Xtr_sel, ytr_e)
|
| 179 |
final_model.compile(Xtr_sel)
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
# ------------------------ Tahmin Fonksiyonu ------------------------
|
| 182 |
def predict_opinion(excel_file: gr.File):
|
| 183 |
if excel_file is None:
|
|
@@ -205,43 +210,81 @@ def predict_opinion(excel_file: gr.File):
|
|
| 205 |
"Tahmin Görüş Tipi": labels})
|
| 206 |
|
| 207 |
|
| 208 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
|
| 210 |
-
gr.Markdown("# Denetçi Görüşü Tahmin Uygulaması")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
-
#
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
)
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
|
| 236 |
-
def predict_opinion_with_visibility(excel_file: gr.File):
|
| 237 |
-
df_result = predict_opinion(excel_file) # senin mevcut fonksiyonun
|
| 238 |
-
return gr.update(value=df_result, visible=True)
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
inputs=file_in,
|
| 243 |
-
|
|
|
|
| 244 |
)
|
| 245 |
|
| 246 |
if __name__ == "__main__":
|
| 247 |
-
demo.launch()
|
|
|
|
| 143 |
X, y = df.drop(columns="Görüs Tipi"), df["Görüs Tipi"]
|
| 144 |
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
|
| 145 |
|
| 146 |
+
scaler_full = MinMaxScaler().fit(X_tr)
|
| 147 |
+
Xtr_s = scaler_full.transform(X_tr)
|
| 148 |
+
Xte_s = scaler_full.transform(X_te)
|
| 149 |
|
| 150 |
encoder = LabelEncoder()
|
| 151 |
ytr_e = encoder.fit_transform(y_tr)
|
|
|
|
| 159 |
grid.fit(Xtr_s, ytr_e)
|
| 160 |
best_params = grid.best_params_
|
| 161 |
|
| 162 |
+
# İlk eğitim → feature importance için
|
| 163 |
full_plain = ConcreteXGBClassifier(n_bits=8, **best_params, random_state=42)
|
| 164 |
full_plain.fit(Xtr_s, ytr_e)
|
| 165 |
|
| 166 |
imp_df = pd.DataFrame({"col": X.columns, "imp": full_plain.feature_importances_})
|
| 167 |
+
imp_df = imp_df.sort_values("imp", ascending=False).reset_index(drop=True)
|
| 168 |
imp_df["cum"] = imp_df["imp"].cumsum()
|
| 169 |
COLS = imp_df.loc[imp_df["cum"] <= 0.95, "col"].tolist()
|
| 170 |
|
| 171 |
+
# Seçilen feature'lara göre final model
|
| 172 |
+
scaler = MinMaxScaler().fit(X_tr[COLS])
|
| 173 |
+
Xtr_sel = scaler.transform(X_tr[COLS])
|
| 174 |
+
Xte_sel = scaler.transform(X_te[COLS])
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
final_model = ConcreteXGBClassifier(n_bits=8, **best_params, random_state=42)
|
| 177 |
final_model.fit(Xtr_sel, ytr_e)
|
| 178 |
final_model.compile(Xtr_sel)
|
| 179 |
|
| 180 |
+
print("\n🔍 Seçilen Özellikler (%95 etkili):")
|
| 181 |
+
for i, col in enumerate(COLS, 1):
|
| 182 |
+
print(f"{i:>2}. {col}")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
|
| 186 |
# ------------------------ Tahmin Fonksiyonu ------------------------
|
| 187 |
def predict_opinion(excel_file: gr.File):
|
| 188 |
if excel_file is None:
|
|
|
|
| 210 |
"Tahmin Görüş Tipi": labels})
|
| 211 |
|
| 212 |
|
| 213 |
+
# Global değişkenler
|
| 214 |
+
enc_input = None
|
| 215 |
+
enc_output = None
|
| 216 |
+
|
| 217 |
+
# -------------------- Gradio UI -------------------- #
|
| 218 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
|
| 219 |
+
gr.Markdown("# 🔐 Denetçi Görüşü Tahmin Uygulaması (FHE)")
|
| 220 |
+
|
| 221 |
+
gr.Markdown("## 1️⃣ Anahtar Üret (Key Generation)")
|
| 222 |
+
key_btn = gr.Button("🔑 Anahtarı Oluştur ve Server'a Gönder")
|
| 223 |
+
eval_key_box = gr.Textbox(label="Evaluation Key (görsel)", lines=1)
|
| 224 |
+
|
| 225 |
+
def generate_keys():
|
| 226 |
+
final_model.fhe_circuit.keygen()
|
| 227 |
+
return final_model.fhe_circuit.get_serialized_evaluation_keys().decode()[:120] + "..."
|
| 228 |
+
|
| 229 |
+
key_btn.click(generate_keys, outputs=eval_key_box)
|
| 230 |
|
| 231 |
+
gr.Markdown("## 2️⃣ Excel Dosyası Yükle")
|
| 232 |
+
file_in = gr.File(file_types=[".xlsx"], label="📁 Excel Dosyası")
|
| 233 |
+
|
| 234 |
+
encrypt_btn = gr.Button("🔐 Girişi Şifrele ve Server'a Gönder")
|
| 235 |
+
encrypted_box = gr.Textbox(label="Şifreli Giriş (ilk 150 karakter)")
|
| 236 |
+
|
| 237 |
+
def encrypt_excel(file):
|
| 238 |
+
global enc_input
|
| 239 |
+
raw_df = (
|
| 240 |
+
pd.read_excel(file.name, header=None)
|
| 241 |
+
.set_index(0).T.reset_index(drop=True)
|
| 242 |
)
|
| 243 |
+
raw_df.columns = raw_df.columns.str.strip()
|
| 244 |
+
raw_df = raw_df.loc[:, ~raw_df.columns.duplicated()]
|
| 245 |
+
raw_df.rename(columns={"Desc": "Periyot"}, inplace=True)
|
| 246 |
+
raw_df["Periyot"] = raw_df["Periyot"].astype(str).str.strip()
|
| 247 |
|
| 248 |
+
enriched = compute_ratios(raw_df)
|
| 249 |
+
X_input = enriched[SELECTED_FEATS].dropna()
|
| 250 |
+
if X_input.empty:
|
| 251 |
+
raise gr.Error("Veri eksik veya oranlar hesaplanamadı.")
|
| 252 |
+
scaled = scaler.transform(X_input)
|
| 253 |
+
enc_input = final_model.fhe_circuit.encrypt(scaled)
|
| 254 |
+
return str(enc_input)[:150] + "..."
|
| 255 |
|
| 256 |
+
encrypt_btn.click(encrypt_excel, inputs=file_in, outputs=encrypted_box)
|
| 257 |
+
|
| 258 |
+
gr.Markdown("## 3️⃣ Tahmini Şifreli Olarak Gerçekleştir (FHE)")
|
| 259 |
+
run_btn = gr.Button("🚀 FHE Tahmini Çalıştır")
|
| 260 |
+
time_box = gr.Textbox(label="Tahmin Süresi (sn)")
|
| 261 |
+
|
| 262 |
+
def run_fhe():
|
| 263 |
+
import time
|
| 264 |
+
global enc_output
|
| 265 |
+
start = time.time()
|
| 266 |
+
enc_output = final_model.fhe_circuit.run(enc_input)
|
| 267 |
+
return f"{time.time() - start:.2f}"
|
| 268 |
|
| 269 |
+
run_btn.click(run_fhe, outputs=time_box)
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
+
gr.Markdown("## 4️⃣ Tahmin Sonucunu Deşifre Et")
|
| 272 |
+
decrypt_btn = gr.Button("🔓 Tahmin Sonucunu Göster")
|
| 273 |
+
result_box = gr.Textbox(label="📌 Tahmin: Görüş Tipi")
|
| 274 |
+
|
| 275 |
+
def decrypt_result():
|
| 276 |
+
y_pred = final_model.fhe_circuit.decrypt(enc_output)
|
| 277 |
+
return encoder.inverse_transform([y_pred])[0]
|
| 278 |
+
|
| 279 |
+
decrypt_btn.click(decrypt_result, outputs=result_box)
|
| 280 |
+
|
| 281 |
+
gr.Markdown("## 📎 Örnek Dosyaları Deneyin")
|
| 282 |
+
gr.Examples(
|
| 283 |
+
examples=EXAMPLE_XLSX,
|
| 284 |
inputs=file_in,
|
| 285 |
+
label="💾 Örnek Excel Seç",
|
| 286 |
+
cache_examples=False,
|
| 287 |
)
|
| 288 |
|
| 289 |
if __name__ == "__main__":
|
| 290 |
+
demo.launch()
|