ESMATUGBA commited on
Commit
897354f
·
verified ·
1 Parent(s): f102b68

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +109 -71
src/streamlit_app.py CHANGED
@@ -3,90 +3,128 @@ import pandas as pd
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  import seaborn as sns
6
- import os
7
 
8
- # 1. DOSYA İZLEYİCİSİNİ SUSTURMA (Titremeyi önlemek için en üstte olmalı)
9
- os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none"
10
 
11
- # 2. SAYFA AYARI
12
- st.set_page_config(
13
- page_title="Fast Food Nutrition Guide",
14
- layout="wide",
15
- initial_sidebar_state="expanded"
16
- )
17
-
18
- # 3. VERİ KİLİDİ (Cache - spinner'ı bile kapattık ki hareket olmasın)
19
- @st.cache_data(show_spinner=False)
20
- def get_locked_data():
21
  try:
22
- data = pd.read_csv("Nutrition_Value_Dataset.csv")
23
- return data.replace([np.inf, -np.inf], np.nan).dropna()
24
  except:
25
  return None
26
 
27
- df = get_locked_data()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # --- SIDEBAR (SOL PANEL) ---
30
- with st.sidebar:
31
- st.title("🏥 Health Guide")
32
- st.subheader("⚖️ Daily Needs")
33
- st.write("- **Women:** 2,000 kcal\n- **Men:** 2,500 kcal")
34
- st.warning("⚠️ High sodium warning!")
35
- st.info("💡 Tip: Choose water.")
36
 
37
- # --- ANA SAYFA ---
38
- st.title("🍔 Global Fast Food Nutrition Analysis")
39
 
40
- # SABİT HTML NOT KUTUSU (Titreme yapmaz)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  st.markdown("""
42
- <div style="background-color: #ff4b4b; padding: 15px; border-radius: 8px; color: white; margin-bottom: 20px;">
43
- <h3 style="margin-top:0;">📢 Important Notice / Önemli Not</h3>
44
- <p>Aşağıdaki nedenlerle bu ürünlerin tüketimi <b>sağlık açısından risklidir:</b></p>
45
- <ol>
46
- <li><b>Kalp Sağlığı:</b> Tansiyon ve damar sertliği.</li>
47
- <li><b>Kan Şekeri:</b> Diyabet riski.</li>
48
- <li><b>Besin Değeri:</b> Boş kalori kaynakları.</li>
49
- <li><b>Obezite:</b> Pizza Hut, Burger King, KFC, McDonald’s ve Starbucks ürünleri hızlı kilo aldırır.</li>
50
- </ol>
51
  </div>
52
  """, unsafe_allow_html=True)
53
 
54
- # PROJE ÖZETİ (SABİT)
55
- st.markdown("<h1 style='text-align: center;'>🔍 Besin Değerleri Analiz Raporu</h1>", unsafe_allow_html=True)
56
- st.markdown("<p style='text-align: center; font-size: 20px;'>Bu çalışma, fast food ürünlerini görselleştirerek genel bir sağlık tablosu sunar.</p>", unsafe_allow_html=True)
57
-
58
  st.write("---")
59
 
60
- # 4. GRAFİKLERİ CACHE İLE DONDURMA
61
- @st.cache_resource(show_spinner=False)
62
- def get_static_plots(_data):
63
- # Grafik 1
64
- fig1, ax1 = plt.subplots(figsize=(10, 5))
65
- _data.groupby("Company")["Sugar (g)"].mean().sort_values().plot(kind="bar", color="crimson", ax=ax1)
66
- plt.xticks(rotation=45)
67
- plt.tight_layout()
68
-
69
- # Grafik 2
70
- fig2, ax2 = plt.subplots(figsize=(10, 5))
71
- sns.histplot(_data["Energy (kCal)"], bins=20, kde=True, color="darkorange", ax=ax2)
72
- plt.tight_layout()
73
-
74
- return fig1, fig2
75
-
76
- if df is not None:
77
- f1, f2 = get_static_plots(df)
78
- c1, c2 = st.columns(2)
79
- with c1:
80
- st.write("🍭 **Average Sugar / Ort. Şeker**")
81
- st.pyplot(f1)
82
- with c2:
83
- st.write("🔥 **Calorie Distribution / Dağılım**")
84
- st.pyplot(f2)
85
-
86
- # 5. TABLO (ETKİLEŞİMSİZ TABLO - TİTREMEYİ KESEN ASIL NOKTA)
87
  st.write("---")
88
- st.subheader("📋 Top 10 High-Calorie Products")
89
- if df is not None:
90
- top_10 = df.sort_values(by="Energy (kCal)", ascending=False).head(10)
91
- # st.dataframe yerine st.table kullanarak JavaScript titremesini bitiriyoruz
92
- st.table(top_10[["Company", "Product", "Energy (kCal)", "Sugar (g)"]])
 
 
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  import seaborn as sns
 
6
 
7
+ # 1. DOKUNUŞ: Sayfa ayarlarını ve cache mekanizmasını dondur
8
+ st.set_page_config(page_title="Fast Food Nutrition Guide", layout="wide")
9
 
10
+ # 2. DOKUNUŞ: Veriyi cache'e al (Bu sayede sürekli dosya okumaz ve titremez)
11
+ @st.cache_data
12
+ def load_data():
13
+ path = "Nutrition_Value_Dataset.csv"
 
 
 
 
 
 
14
  try:
15
+ data = pd.read_csv(path).replace([np.inf, -np.inf], np.nan).dropna()
16
+ return data
17
  except:
18
  return None
19
 
20
+ df = load_data()
21
+
22
+ if df is None:
23
+ st.error("CSV file not found! / Veri seti dosyası bulunamadı!")
24
+ st.stop()
25
+
26
+ # --- SIDEBAR (SAĞLIK REHBERİ) ---
27
+ st.sidebar.title("🏥 Health & Calorie Guide / Sağlık ve Kalori Rehberi")
28
+
29
+ st.sidebar.subheader("⚖️ Daily Calorie Needs / Günlük Kalori İhtiyacı")
30
+ st.sidebar.write("""
31
+ - **Women / Kadınlar:** 2,000 kcal
32
+ - **Men / Erkekler:** 2,500 kcal
33
+ """)
34
+
35
+ st.sidebar.warning("""
36
+ ⚠️ **Health Advice / Sağlık Öğüdü:**
37
+ Fast food meals are high in sodium and low in nutrients.
38
+ *Fast food öğünleri sodyum bakımından yüksek, besin değeri bakımından düşüktür.*
39
+ """)
40
+
41
+ st.sidebar.info("""
42
+ 💡 **Quick Tip / Pratik Bilgi:**
43
+ Choosing water over soda can reduce your meal's sugar content by 40-60g.
44
+ *Asitli içecek yerine su seçmek, öğününüzdeki şeker miktarını 40-60 gr azaltabilir.*
45
+ """)
46
 
47
+ # --- ANA SAYFA BAŞLIK ---
48
+ st.title("🍔 Global Fast Food Nutrition Analysis / Küresel Fast Food Besin Analizi")
 
 
 
 
 
49
 
50
+ # --- TÜKETİCİYE KRİTİK NOT ---
51
+ st.error("### 📢 Important Notice for Consumers / Tüketiciler İçin Önemli Not")
52
 
53
+ col_note_tr, col_note_en = st.columns(2)
54
+
55
+ with col_note_tr:
56
+ st.markdown("""
57
+ **Aşağıdaki verilere istinaden, bu şirketlerden yemek tüketilmemesi sağlığınız için şu nedenlerle yararlı olacaktır:**
58
+
59
+ 1. **Kalp Sağlığı:** Yüksek trans yağ ve sodyum içeriği damar sertliği ve tansiyona neden olur.
60
+ 2. **Kan Şekeri Dengesi:** Aşırı şeker ve işlenmiş karbonhidratlar ani insülin direnci ve diyabet riskini tetikler.
61
+ 3. **Besin Değeri Eksikliği:** Bu ürünler "boş kalori" kaynağıdır; vitamin, mineral ve lif açısından son derece fakirdir.
62
+ 4. **Obezite Riski:** **Pizza Hut, Burger King, KFC, McDonald’s ve Starbucks** şirketlerinden yüksek kalori yoğunluğu olacağından kısa sürede kontrolsüz kilo alımına yol açar.
63
+
64
+ * **🥤 Su İçin:** Asitli içecekler yerine su tüketmek sağlığınız için kritiktir.
65
+ * **🥩 Protein Vurgusu:** Kas sağlığı ve metabolizma için **protein ağırlıklı** beslenmeye özen gösterilmelidir.
66
+ """)
67
+
68
+ with col_note_en:
69
+ st.markdown("""
70
+ **Based on the data below, avoiding these companies' meals will benefit your health for the following reasons:**
71
+
72
+ 1. **Heart Health:** High trans fat and sodium content cause arteriosclerosis and high blood pressure.
73
+ 2. **Blood Sugar Balance:** Excessive sugar and processed carbs trigger insulin resistance and diabetes risk.
74
+ 3. **Lack of Nutrients:** These products are sources of "empty calories"; they are extremely poor in vitamins and minerals.
75
+ 4. **Obesity Risk:** High calorie density in foods from companies like **Pizza Hut, Burger King, KFC, McDonald’s, and Starbucks** can lead to rapid, uncontrolled weight gain.
76
+
77
+ * **🥤 Drink Water:** Choosing water instead of sugary drinks is critical for your health.
78
+ * **🥩 Focus on Protein:** Prioritize **protein-rich** nutrition for muscle health and metabolism.
79
+ """)
80
+
81
+ st.write("---")
82
+
83
+ # --- ÖDEV METNİ (BÜYÜTÜLMÜŞ VE KOYULTULMUŞ) ---
84
  st.markdown("""
85
+ <div style="text-align: center;">
86
+ <h3 style="color: #1E1E1E; font-weight: bold;">
87
+ 🔍 Bu çalışma, fast food ürünlerinin kalori ve şeker içeriklerini görselleştirerek genel bir sağlık tablosu sunmaktadır.
88
+ </h3>
89
+ <h4 style="color: #555555;">
90
+ This study provides a general health overview by visualizing the calorie and sugar content of fast food products.
91
+ </h4>
 
 
92
  </div>
93
  """, unsafe_allow_html=True)
94
 
 
 
 
 
95
  st.write("---")
96
 
97
+ # --- GRAFİKLER ---
98
+ st.subheader("📊 General Visual Analysis / Genel Görsel Analiz")
99
+
100
+ c1, c2 = st.columns(2)
101
+
102
+ with c1:
103
+ st.write("🍭 **Average Sugar by Company / Şirketlere Göre Ort. Şeker**")
104
+ sugar_means = df.groupby("Company")["Sugar (g)"].mean().sort_values()
105
+ # 3. DOKUNUŞ: plt.figure() kullanarak grafiklerin üst üste binmesini ve titremesini önle
106
+ fig1, ax1 = plt.subplots(figsize=(6, 4))
107
+ sugar_means.plot(kind="bar", color="crimson", ax=ax1)
108
+ plt.xticks(rotation=45, fontsize=8)
109
+ st.pyplot(fig1)
110
+
111
+ with c2:
112
+ st.write("🔥 **Overall Calorie Distribution / Genel Kalori Dağılımı**")
113
+ fig2, ax2 = plt.subplots(figsize=(6, 4))
114
+ sns.histplot(df["Energy (kCal)"], bins=20, kde=True, ax=ax2, color="darkorange")
115
+ st.pyplot(fig2)
116
+
117
+ # --- VERİ TABLOSU ---
118
+ st.subheader("📋 High-Calorie Products List / Yüksek Kalorili Ürün Listesi")
119
+ top_20 = df.sort_values(by="Energy (kCal)", ascending=False).head(20)
120
+ # Tabloyu kapsayıcı genişliğine sabitleyerek titremeyi durduruyoruz
121
+ st.dataframe(top_20[["Company", "Product", "Energy (kCal)", "Sugar (g)", "Protein (g)", "Total Fat (g)"]], use_container_width=True)
122
+
123
+ # --- DOWNLOAD ---
124
  st.write("---")
125
+ st.download_button(
126
+ "📥 Download Full Dataset / Tüm Veriyi İndir",
127
+ df.to_csv(index=False),
128
+ "fastfood_nutrition_final.csv",
129
+ "text/csv"
130
+ )