File size: 4,317 Bytes
c8b1b08
cb33ad7
631b301
 
c8b1b08
631b301
 
c8b1b08
631b301
 
 
 
 
 
 
 
 
 
 
c8b1b08
631b301
c8b1b08
631b301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8b1b08
631b301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb33ad7
631b301
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import streamlit as st
import pickle
import re
import string

# 1. Sayfa Ayarları / Page Settings
st.set_page_config(page_title="Fake-News-Detection | Sahte Haber Tespiti", page_icon="🔍", layout="wide")

# 2. Model ve Vektörleştiriciyi Güvenli Yükle / Load Assets Safely
@st.cache_resource
def load_assets():
    try:
        with open('vectorizer.pkl', 'rb') as f:
            vectorizer = pickle.load(f)
        with open('model_nb.pkl', 'rb') as f:
            model = pickle.load(f)
        return vectorizer, model
    except Exception as e:
        return None, None

tfidf, nb_model = load_assets()

# 3. Güçlendirilmiş Metin Temizleme / Robust Text Cleaning
def clean_text(text):
    try:
        text = str(text).lower()
        # Reuters imzasını temizle
        text = re.sub(r'^.*?\(reuters\)\s*-', '', text) 
        # Linkleri ve parantez içlerini sil
        text = re.sub(r'https?://\S+|www\.\S+', '', text)
        text = re.sub(r'\[.*?\]', '', text)
        # Sadece harf ve boşlukları tut (Hataları önlemek için en güvenli yol)
        text = re.sub(r'[^a-z\s]', '', text) 
        # Fazla boşlukları temizle
        text = re.sub(r'\s+', ' ', text)
        return text.strip()
    except:
        return ""

# --- SOL PANEL (SIDEBAR) ---
st.sidebar.title("⚙️ Kontrol Paneli / Control Panel")
st.sidebar.warning("⚠️ **NOT / NOTE:** Bu model sadece İngilizce metinlere duyarlıdır. / Only English supported.")

st.sidebar.subheader("📌 Kopyalanabilir Örnekler / Examples")

# İstediğin yeni örnekleri buraya ekledim
st.sidebar.info("**Ekonomi (Gerçek):**\n\nWASHINGTON (Reuters) - The Federal Reserve maintained its interest rate target on Wednesday, signaling the economy is expanding at a solid pace and inflation is stable.")
st.sidebar.success("**Uzay & Teknoloji (Gerçek):**\n\nA private space company successfully launched its latest satellite into orbit on Tuesday. The mission aims to provide high-speed internet access to rural areas across the globe, according to official statements.")
st.sidebar.error("**Sosyal Medya (Sahte):**\n\nURGENT: Your smartphone is secretly recording all your family photos and sending them to a hidden server. The government is forcing tech companies to hide this truth. Share now!")
st.sidebar.error("**Sağlık (Sahte):**\n\nDrinking five cups of salted water every hour is proven to cure every single virus instantly. Doctors are being paid to stay silent about this miracle cure!")

st.sidebar.markdown("---")
st.sidebar.write("**Model:** Multinomial NB\n**Accuracy:** %94")

# --- ANA SAYFA ---
st.title("🔍 Fake-News-Detection | Sahte Haber Tespiti")
st.markdown("Haberin gerçek mi yoksa sahte mi olduğunu analiz edin. / Analyze news veracity.")

if tfidf is None or nb_model is None:
    st.error("Model dosyaları bulunamadı! Lütfen vectorizer.pkl ve model_nb.pkl dosyalarını kontrol edin.")

# 4. Kullanıcı Girişi
user_input = st.text_area("Analiz edilecek haber metnini girin / Enter news text:", height=250)

if st.button("Analiz Et / Analyze"):
    if user_input.strip() != "":
        try:
            # Ön İşlem
            cleaned = clean_text(user_input)
            
            if len(cleaned) < 5:
                st.warning("Metin analiz için çok kısa! / Text is too short for analysis!")
            else:
                # Vektörleştirme
                vec = tfidf.transform([cleaned])
                # Tahmin
                pred = nb_model.predict(vec)[0]
                prob = nb_model.predict_proba(vec)

                st.subheader("Analiz Sonucu / Result:")
                
                # Etiket Mantığı: 1 = GERÇEK, 0 = SAHTE
                if pred == 1:
                    st.success(f"✅ GERÇEK GÖRÜNÜYOR / LOOKS REAL (Güven/Confidence: %{prob[0][1]*100:.2f})")
                    st.balloons()
                else:
                    st.error(f"🚨 SAHTE OLABİLİR / MIGHT BE FAKE (Olasılık/Probability: %{prob[0][0]*100:.2f})")
                    
                with st.expander("Temizlenmiş Metin Detayı / View Cleaned Text"):
                    st.write(cleaned)
        except Exception as e:
            st.error(f"Beklenmedik bir hata oluştu: {e}")
    else:
        st.warning("Lütfen bir metin girin. / Please enter a text.")