ESMATUGBA commited on
Commit
dec4ce8
·
verified ·
1 Parent(s): 9074332

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -56
app.py CHANGED
@@ -5,95 +5,99 @@ from pyspark.ml.classification import LogisticRegressionModel
5
  from pyspark.ml.feature import VectorAssembler
6
 
7
  # --- 1. SAYFA AYARLARI (PAGE CONFIG) ---
8
- st.set_page_config(page_title="Heart Disease Predictor", page_icon="🫀", layout="centered")
9
 
10
- # CSS ile buton ve başlıkları güzelleştirelim
11
  st.markdown("""
12
  <style>
13
- .main { opacity: 0.95; }
14
- .stButton>button { width: 100%; border-radius: 20px; height: 3em; background-color: #ff4b4b; color: white; }
 
15
  </style>
16
  """, unsafe_allow_html=True)
17
 
18
- st.title("🫀 Heart Disease Risk Prediction")
19
- st.subheader("Kalp Hastalığı Risk Tahmini")
20
- st.write("---")
21
-
22
- # --- 2. SPARK VE MODEL YÜKLEME (SPARK & MODEL LOADING) ---
23
  @st.cache_resource
24
- def initialize_app():
25
- # Spark oturumunu başlat
26
  spark = SparkSession.builder \
27
  .appName("HeartDiseaseApp") \
28
  .master("local[*]") \
29
  .config("spark.driver.bindAddress", "127.0.0.1") \
30
  .getOrCreate()
31
 
32
- # Modeli yükle (heart_model klasöründen)
33
  model = LogisticRegressionModel.load("heart_model")
34
  return spark, model
35
 
36
  try:
37
- spark, model = initialize_app()
38
- st.success("✅ System Ready / Sistem Hazır")
39
  except Exception as e:
40
- st.error(f"❌ Initialization Error / Başlatma Hatası: {e}")
41
- st.info("Lütfen heart_model klasörünün doğruluğunu kontrol edin.")
42
  st.stop()
43
 
44
- # --- 3. KULLANICI GİRİŞLERİ (USER INPUTS) ---
 
 
 
 
 
45
  st.sidebar.header("📋 Patient Data / Hasta Verileri")
46
 
47
- def get_inputs():
48
- col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- with col1:
51
- age = st.number_input("Age / Yaş", 1, 120, 50)
52
- sex = st.selectbox("Sex / Cinsiyet", options=[1, 0], format_func=lambda x: "Male/Erkek (1)" if x == 1 else "Female/Kadın (0)")
53
- cp = st.selectbox("Chest Pain / Göğüs Ağrısı (0-3)", [0, 1, 2, 3])
54
- trestbps = st.number_input("Resting BP / Kan Basıncı", 50, 250, 120)
55
- chol = st.number_input("Cholesterol / Kolesterol", 100, 600, 200)
56
- fbs = st.selectbox("Fasting Sugar > 120 / Şeker", [0, 1], format_func=lambda x: "Yes/Evet (1)" if x == 1 else "No/Hayır (0)")
57
-
58
- with col2:
59
- restecg = st.selectbox("Resting ECG / EKG (0-2)", [0, 1, 2])
60
- thalach = st.number_input("Max Heart Rate / Kalp Hızı", 50, 250, 150)
61
- exang = st.selectbox("Exercise Angina / Anjin", [0, 1], format_func=lambda x: "Yes/Evet (1)" if x == 1 else "No/Hayır (0)")
62
- oldpeak = st.number_input("Oldpeak", 0.0, 10.0, 1.0)
63
- slope = st.selectbox("Slope (0-2)", [0, 1, 2])
64
- ca = st.selectbox("Major Vessels / Damar Sayısı", [0, 1, 2, 3, 4])
65
- thal = st.selectbox("Thal (0-3)", [0, 1, 2, 3])
66
-
67
- input_data = {
68
  'age': age, 'sex': sex, 'cp': cp, 'trestbps': trestbps, 'chol': chol,
69
  'fbs': fbs, 'restecg': restecg, 'thalach': thalach, 'exang': exang,
70
  'oldpeak': oldpeak, 'slope': slope, 'ca': ca, 'thal': thal
71
  }
72
- return spark.createDataFrame([input_data])
 
 
 
 
 
73
 
74
- input_df = get_inputs()
 
 
75
 
76
- # --- 4. TAHMİN (PREDICTION) ---
77
- st.write("---")
78
- if st.button("PREDICT / TAHMİN ET"):
79
- with st.spinner('Analyzing... / Analiz ediliyor...'):
80
- # Özellikleri vektöre dönüştür
81
  feature_cols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal']
82
  assembler = VectorAssembler(inputCols=feature_cols, outputCol="features")
83
- final_data = assembler.transform(input_df)
84
 
85
- # Tahmin yap
86
- prediction_results = model.transform(final_data)
87
- result = prediction_results.select("prediction").collect()[0][0]
88
- probability = prediction_results.select("probability").collect()[0][0]
89
 
90
- st.subheader("Results / Sonuçlar")
91
  if result == 1.0:
92
- st.error(f"⚠️ HIGH RISK / YÜKSEK RİSK")
93
- st.write(f"Confidence / Güven Oranı: %{round(probability[1]*100, 2)}")
 
94
  else:
95
- st.success(f"💚 LOW RISK / DÜŞÜK RİSK")
96
- st.write(f"Confidence / Güven Oranı: %{round(probability[0]*100, 2)}")
 
97
 
98
- st.write("---")
99
- st.caption("Disclaimer: Not for medical use. / Tıbbi amaçlı kullanılamaz.")
 
5
  from pyspark.ml.feature import VectorAssembler
6
 
7
  # --- 1. SAYFA AYARLARI (PAGE CONFIG) ---
8
+ st.set_page_config(page_title="Heart Disease Predictor", page_icon="🫀", layout="wide")
9
 
10
+ # Görsel stil ekleyelim (CSS)
11
  st.markdown("""
12
  <style>
13
+ .main { background-color: #f5f7f9; }
14
+ .stButton>button { width: 100%; border-radius: 10px; height: 3em; background-color: #e63946; color: white; font-weight: bold; }
15
+ .stSuccess { background-color: #d8f3dc; }
16
  </style>
17
  """, unsafe_allow_html=True)
18
 
19
+ # --- 2. SPARK VE MODEL BAŞLATMA ---
 
 
 
 
20
  @st.cache_resource
21
+ def initialize_spark_and_model():
22
+ # Spark Session
23
  spark = SparkSession.builder \
24
  .appName("HeartDiseaseApp") \
25
  .master("local[*]") \
26
  .config("spark.driver.bindAddress", "127.0.0.1") \
27
  .getOrCreate()
28
 
29
+ # Model Loading
30
  model = LogisticRegressionModel.load("heart_model")
31
  return spark, model
32
 
33
  try:
34
+ spark, model = initialize_spark_and_model()
 
35
  except Exception as e:
36
+ st.error(f"Error / Hata: {e}")
 
37
  st.stop()
38
 
39
+ # --- 3. ÜST BAŞLIK VE AÇIKLAMA ---
40
+ st.title("🫀 Heart Disease Risk Prediction")
41
+ st.subheader("Kalp Hastalığı Risk Tahmini")
42
+ st.info("Fill in the patient data on the left and click 'Predict'. / Soldaki hasta verilerini doldurun ve 'Tahmin Et' butonuna basın.")
43
+
44
+ # --- 4. GİRİŞ ALANLARI (SIDEBAR) ---
45
  st.sidebar.header("📋 Patient Data / Hasta Verileri")
46
 
47
+ def get_user_inputs():
48
+ # Sayısal girişler ve seçimler
49
+ age = st.sidebar.slider("Age / Yaş", 1, 100, 50)
50
+ sex = st.sidebar.radio("Sex / Cinsiyet", [1, 0], format_func=lambda x: "Male/Erkek" if x == 1 else "Female/Kadın")
51
+ cp = st.sidebar.selectbox("Chest Pain Type / Göğüs Ağrısı Tipi (0-3)", [0, 1, 2, 3])
52
+ trestbps = st.sidebar.number_input("Resting BP / Kan Basıncı (mm Hg)", 50, 250, 120)
53
+ chol = st.sidebar.number_input("Cholesterol / Kolesterol (mg/dl)", 100, 600, 200)
54
+ fbs = st.sidebar.radio("Fasting Blood Sugar > 120 / Şeker Yüksek mi?", [0, 1], format_func=lambda x: "Yes/Evet" if x == 1 else "No/Hayır")
55
+ restecg = st.sidebar.selectbox("Resting ECG / EKG Sonucu (0-2)", [0, 1, 2])
56
+ thalach = st.sidebar.slider("Max Heart Rate / Maks. Kalp Hızı", 50, 220, 150)
57
+ exang = st.sidebar.radio("Exercise Induced Angina / Egzersiz Ağrısı?", [0, 1], format_func=lambda x: "Yes/Evet" if x == 1 else "No/Hayır")
58
+ oldpeak = st.sidebar.number_input("Oldpeak (ST Depression)", 0.0, 10.0, 1.0, step=0.1)
59
+ slope = st.sidebar.selectbox("Slope of ST Segment (0-2)", [0, 1, 2])
60
+ ca = st.sidebar.selectbox("Major Vessels / Damar Sayısı (0-4)", [0, 1, 2, 3, 4])
61
+ thal = st.sidebar.selectbox("Thalassemia / Thal (0-3)", [0, 1, 2, 3])
62
 
63
+ data = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  'age': age, 'sex': sex, 'cp': cp, 'trestbps': trestbps, 'chol': chol,
65
  'fbs': fbs, 'restecg': restecg, 'thalach': thalach, 'exang': exang,
66
  'oldpeak': oldpeak, 'slope': slope, 'ca': ca, 'thal': thal
67
  }
68
+ return spark.createDataFrame([data])
69
+
70
+ input_df = get_user_inputs()
71
+
72
+ # --- 5. TAHMİN VE SONUÇ EKRANI ---
73
+ col1, col2 = st.columns([1, 1])
74
 
75
+ with col1:
76
+ st.markdown("### User Profile / Kullanıcı Profili")
77
+ st.write(input_df.toPandas().T.rename(columns={0: 'Values'}))
78
 
79
+ with col2:
80
+ st.markdown("### Prediction / Tahmin")
81
+ if st.button("RUN ANALYSIS / ANALİZİ ÇALIŞTIR"):
82
+ # Veriyi hazırla
 
83
  feature_cols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal']
84
  assembler = VectorAssembler(inputCols=feature_cols, outputCol="features")
85
+ processed_data = assembler.transform(input_df)
86
 
87
+ # Model tahmini
88
+ prediction_output = model.transform(processed_data)
89
+ result = prediction_output.select("prediction").collect()[0][0]
90
+ prob = prediction_output.select("probability").collect()[0][0]
91
 
92
+ # Sonuç Görselleştirme
93
  if result == 1.0:
94
+ st.error(f"### ⚠️ HIGH RISK / YÜKSEK RİSK")
95
+ st.metric("Risk Probability / Risk Olasılığı", f"%{round(prob[1]*100, 2)}")
96
+ st.write("Please consult a doctor. / Lütfen bir doktora danışın.")
97
  else:
98
+ st.success(f"### LOW RISK / DÜŞÜK RİSK")
99
+ st.metric("Healthy Probability / Sağlıklı Olasılığı", f"%{round(prob[0]*100, 2)}")
100
+ st.write("Results look stable. / Sonuçlar stabil görünüyor.")
101
 
102
+ st.divider()
103
+ st.caption("Disclaimer: This AI model is for educational purposes. / Bu yapay zeka modeli eğitim amaçlıdır.")