ESMATUGBA commited on
Commit
7a16aef
·
verified ·
1 Parent(s): c935f35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -51
app.py CHANGED
@@ -3,76 +3,132 @@ import pandas as pd
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  import seaborn as sns
 
6
 
7
- # 1. KURAL: Sayfayı 'centered' (ortalanmış) yaparak genişlik hesaplama titremesini bitiriyoruz
8
- st.set_page_config(
9
- page_title="Fast Food Nutrition Guide",
10
- layout="centered", # 'wide' yerine 'centered' titremeyi genelde %100 keser
11
- initial_sidebar_state="expanded"
12
- )
13
 
14
- # 2. KURAL: Veriyi dondur
 
 
 
15
  @st.cache_data
16
- def get_data_fixed():
 
17
  try:
18
- data = pd.read_csv("Nutrition_Value_Dataset.csv")
19
- return data.replace([np.inf, -np.inf], np.nan).dropna()
 
20
  except:
21
  return None
22
 
23
- df = get_data_fixed()
24
 
25
- # --- SIDEBAR (SOL PANEL) ---
26
- with st.sidebar:
27
- st.title("🏥 Health & Calorie Guide")
28
- st.write("---")
29
- st.subheader("⚖️ Daily Needs")
30
- st.write("- **Women:** 2,000 kcal\n- **Men:** 2,500 kcal")
31
- st.warning("⚠️ High sodium warning!")
32
- st.info("💡 Tip: Choose water over soda.")
33
 
34
- # --- ANA SAYFA ---
35
- st.title("🍔 Global Fast Food Analysis")
36
 
37
- # KRİTİK NOTLAR
38
- st.error("### 📢 Important Notice")
39
- st.markdown("""
40
- **Aşağıdaki nedenlerle bu ürünlerin tüketimi risklidir:**
41
- 1. **Kalp Sağlığı:** Tansiyon riski.
42
- 2. **Kan Şekeri:** Diyabet riski.
43
- 3. **Besin Değeri:** Boş kalori.
44
- 4. **Obezite:** **Pizza Hut, Burger King, KFC, McDonald’s ve Starbucks** ürünleri kontrolsüz kilo aldırır.
 
 
45
  """)
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  st.write("---")
48
 
49
- # PROJE ÖZETİ (Sabit yazı)
50
- st.subheader("🔍 Besin Değerleri Analiz Raporu")
51
- st.write("Bu çalışma, fast food ürünlerini görselleştirerek genel bir sağlık tablosu sunar.")
 
 
 
 
 
 
 
 
52
 
53
  st.write("---")
54
 
55
- # 3. KURAL: Grafikleri yan yana değil, ALT ALTA koyalım (Genişlik titremesini önler)
56
- if df is not None:
57
- # Grafik 1
58
- st.write("🍭 **Average Sugar by Company / Ort. Şeker**")
59
- fig1, ax1 = plt.subplots(figsize=(10, 5))
60
- df.groupby("Company")["Sugar (g)"].mean().sort_values().plot(kind="bar", color="crimson", ax=ax1)
61
- plt.xticks(rotation=45)
62
- st.pyplot(fig1)
63
 
64
- st.write("---")
 
 
 
 
 
 
65
 
66
- # Grafik 2
67
- st.write("🔥 **Overall Calorie Distribution / Kalori Dağılımı**")
68
- fig2, ax2 = plt.subplots(figsize=(10, 5))
69
- sns.histplot(df["Energy (kCal)"], bins=20, kde=True, color="darkorange", ax=ax2)
70
  st.pyplot(fig2)
71
 
72
- # --- TABLO ---
 
 
 
 
 
 
73
  st.write("---")
74
- st.subheader("📋 High-Calorie Products List")
75
- if df is not None:
76
- top_10 = df.sort_values(by="Energy (kCal)", ascending=False).head(10)
77
- # width='stretch' veya 'content' hatası almamak için parametresiz düz tablo kullanıyoruz
78
- 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
+ import os
7
 
8
+ # Titremeyi önlemek için dosya izleyicisini pasifize et
9
+ os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none"
 
 
 
 
10
 
11
+ # --- SAYFA AYARLARI ---
12
+ st.set_page_config(page_title="Fast Food Nutrition Guide", layout="wide")
13
+
14
+ # --- VERİ YÜKLEME (TITREME ENGELLEYICI CACHE) ---
15
  @st.cache_data
16
+ def load_data():
17
+ path = "Nutrition_Value_Dataset.csv"
18
  try:
19
+ # Veriyi oku ve temizle
20
+ data = pd.read_csv(path).replace([np.inf, -np.inf], np.nan).dropna()
21
+ return data
22
  except:
23
  return None
24
 
25
+ df = load_data()
26
 
27
+ if df is None:
28
+ st.error("CSV file not found! / Veri seti dosyası bulunamadı!")
29
+ st.stop()
 
 
 
 
 
30
 
31
+ # --- SIDEBAR (SOL PANEL - TÜM İÇERİK GERİ GELDİ) ---
32
+ st.sidebar.title("🏥 Health & Calorie Guide / Sağlık ve Kalori Rehberi")
33
 
34
+ st.sidebar.subheader("⚖️ Daily Calorie Needs / Günlük Kalori İhtiyacı")
35
+ st.sidebar.write("""
36
+ - **Women / Kadınlar:** 2,000kcal
37
+ - **Men / Erkekler:** 2,500 kcal
38
+ """)
39
+
40
+ st.sidebar.warning("""
41
+ ⚠️ **Health Advice / Sağlık Öğüdü:**
42
+ Fast food meals are high in sodium and low in nutrients.
43
+ *Fast food öğünleri sodyum bakımından yüksek, besin değeri bakımından düşüktür.*
44
  """)
45
 
46
+ st.sidebar.info("""
47
+ 💡 **Quick Tip / Pratik Bilgi:**
48
+ Choosing water over soda can reduce your meal's sugar content by 40-60g.
49
+ *Asitli içecek yerine su seçmek, öğününüzdeki şeker miktarını 40-60 gr azaltabilir.*
50
+ """)
51
+
52
+ # --- ANA SAYFA BAŞLIK ---
53
+ st.title("🍔 Global Fast Food Nutrition Analysis / Küresel Fast Food Besin Analizi")
54
+
55
+ # --- TÜKETİCİYE KRİTİK NOT ---
56
+ st.error("### 📢 Important Notice for Consumers / Tüketiciler İçin Önemli Not")
57
+
58
+ col_note_tr, col_note_en = st.columns(2)
59
+
60
+ with col_note_tr:
61
+ st.markdown("""
62
+ **Aşağıdaki verilere istinaden, bu şirketlerden yemek tüketilmemesi sağlığınız için şu nedenlerle yararlı olacaktır:**
63
+
64
+ 1. **Kalp Sağlığı:** Yüksek trans yağ ve sodyum içeriği damar sertliği ve tansiyona neden olur.
65
+ 2. **Kan Şekeri Dengesi:** Aşırı şeker ve işlenmiş karbonhidratlar ani insülin direnci ve diyabet riskini tetikler.
66
+ 3. **Besin Değeri Eksikliği:** Bu ürünler "boş kalori" kaynağıdır; vitamin, mineral ve lif açısından son derece fakirdir.
67
+ 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.
68
+
69
+ * **🥤 Su İçin:** Asitli içecekler yerine su tüketmek sağlığınız için kritiktir.
70
+ * **🥩 Protein Vurgusu:** Kas sağlığı ve metabolizma için **protein ağırlıklı** beslenmeye özen gösterilmelidir.
71
+ """)
72
+
73
+ with col_note_en:
74
+ st.markdown("""
75
+ **Based on the data below, avoiding these companies' meals will benefit your health for the following reasons:**
76
+
77
+ 1. **Heart Health:** High trans fat and sodium content cause arteriosclerosis and high blood pressure.
78
+ 2. **Blood Sugar Balance:** Excessive sugar and processed carbs trigger insulin resistance and diabetes risk.
79
+ 3. **Lack of Nutrients:** These products are sources of "empty calories"; they are extremely poor in vitamins and minerals.
80
+ 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.
81
+
82
+ * **🥤 Drink Water:** Choosing water instead of sugary drinks is critical for your health.
83
+ * **🥩 Focus on Protein:** Prioritize **protein-rich** nutrition for muscle health and metabolism.
84
+ """)
85
+
86
  st.write("---")
87
 
88
+ # --- ÖDEV METNİ (BÜYÜTÜLMÜŞ VE KOYULTULMUŞ) ---
89
+ st.markdown("""
90
+ <div style="text-align: center;">
91
+ <h3 style="color: #1E1E1E; font-weight: bold;">
92
+ 🔍 Bu çalışma, fast food ürünlerinin kalori ve şeker içeriklerini görselleştirerek genel bir sağlık tablosu sunmaktadır.
93
+ </h3>
94
+ <h4 style="color: #555555;">
95
+ This study provides a general health overview by visualizing the calorie and sugar content of fast food products.
96
+ </h4>
97
+ </div>
98
+ """, unsafe_allow_html=True)
99
 
100
  st.write("---")
101
 
102
+ # --- GRAFİKLER ---
103
+ st.subheader("📊 General Visual Analysis / Genel Görsel Analiz")
104
+
105
+ c1, c2 = st.columns(2)
 
 
 
 
106
 
107
+ with c1:
108
+ st.write("🍭 **Average Sugar by Company / Şirketlere Göre Ort. Şeker**")
109
+ sugar_means = df.groupby("Company")["Sugar (g)"].mean().sort_values()
110
+ fig1, ax1 = plt.subplots(figsize=(6, 4))
111
+ sugar_means.plot(kind="bar", color="crimson", ax=ax1)
112
+ plt.xticks(rotation=45, fontsize=8)
113
+ st.pyplot(fig1)
114
 
115
+ with c2:
116
+ st.write("🔥 **Overall Calorie Distribution / Genel Kalori Dağılımı**")
117
+ fig2, ax2 = plt.subplots(figsize=(6, 4))
118
+ sns.histplot(df["Energy (kCal)"], bins=20, kde=True, ax=ax2, color="darkorange")
119
  st.pyplot(fig2)
120
 
121
+ # --- VERİ TABLOSU (LOG ONAYLI GENİŞLİK AYARI) ---
122
+ st.subheader("📋 High-Calorie Products List / Yüksek Kalorili Ürün Listesi")
123
+ top_20 = df.sort_values(by="Energy (kCal)", ascending=False).head(20)
124
+ # 'use_container_width' yerine titremeyi durduran 'width="stretch"' kullanıldı
125
+ st.dataframe(top_20[["Company", "Product", "Energy (kCal)", "Sugar (g)", "Protein (g)", "Total Fat (g)"]], width="stretch")
126
+
127
+ # --- DOWNLOAD ---
128
  st.write("---")
129
+ st.download_button(
130
+ "📥 Download Full Dataset / Tüm Veriyi İndir",
131
+ df.to_csv(index=False),
132
+ "fastfood_nutrition_final.csv",
133
+ "text/csv"
134
+ )