File size: 4,762 Bytes
95dbb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import streamlit as st
import google.generativeai as genai
import os
from gtts import gTTS         # <--- YENİ: Seslendirme için
from langdetect import detect # <--- YENİ: Dil algılama için
import io                     # <--- YENİ: Sesi hafızada tutmak için

# --- Sistem Talimatı (System Prompt) ---
SYSTEM_PROMPT = """
You are Kanka-Bot, a friendly and supportive chatbot. 
Your personality is like a close buddy or 'kanka'. 
You are easy-going, informal, and always ready to help with a positive and relaxed attitude. 
You can use friendly slang or emojis where appropriate, but always remain helpful and respectful. 
IMPORTANT: Respond in the exact same language the user is speaking to you (e.g., if they speak Turkish, you MUST respond in Turkish).
"""

# --- Sayfa Yapılandırması ---
st.set_page_config(
    page_title="Kanka-Bot (Sesli)",
    page_icon="🗣️", # İkonu güncelledim
    layout="wide"
)

# --- Yan Çubuk (Sidebar) ---
with st.sidebar:
    st.title("👋 Kanka-Bot'a Hoş Geldin!")
    st.info(
        "Bu bot, senin dijital kankan olmak için burada. "
        "Aklına ne geliyorsa sor, cevaplarını sesli dinle!"
    )
    st.success(
        "**Unutma:** Bu uygulamanın çalışması için Hugging Face Space "
        "ayarlarındaki 'Secrets' kısmına `GEMINI_API_KEY`'ini eklemiş olman gerekiyor."
    )

# --- Ana Başlık ---
st.title("🗣️ Kanka-Bot: Senin Sesli Dijital Dostun")
st.caption("Gemini 2.5 Flash ile güçlendirilmiştir.")


# <--- YENİ: Metni Sese Çeviren Yardımcı Fonksiyon ---
@st.cache_data # Streamlit bu fonksiyonun sonucunu önbelleğe alır, performans artar
def text_to_audio(text_to_read):
    """
    Verilen metni analiz eder, dilini algılar ve sesi MP3 formatında
    byte olarak döndürür.
    """
    try:
        # 1. Adım: Metnin dilini algıla (örn: 'tr', 'en')
        lang = detect(text_to_read)
        
        # 2. Adım: gTTS ile sesi oluştur
        tts = gTTS(text=text_to_read, lang=lang, slow=False)
        
        # 3. Adım: Sesi diske değil, hafızadaki bir byte dosyasına kaydet
        audio_fp = io.BytesIO()
        tts.write_to_fp(audio_fp)
        audio_fp.seek(0) # Dosya imlecini başa sar
        
        return audio_fp.read()
    
    except Exception as e:
        st.warning(f"Seslendirme sırasında bir hata oluştu: {e}")
        return None
# <--- YENİ Fonksiyon Bitişi ---


try:
    # --- API Anahtarını Güvenli Şekilde Alma ---
    api_key = st.secrets["GEMINI_API_KEY"]
    
    if not api_key:
        st.error("GEMINI_API_KEY bulunamadı. Lütfen Hugging Face Space Secrets'a ekleyin.")
        st.stop()

    genai.configure(api_key=api_key)

    # --- Model ve Geçmiş (History) ---
    if "chat" not in st.session_state:
        model = genai.GenerativeModel(
            'gemini-2.5-flash',
            system_instruction=SYSTEM_PROMPT
        )
        st.session_state.chat = model.start_chat(history=[])

    # --- Sohbet Arayüzü ---
    
    # Önceki mesajları göster (Not: Eski mesajlar için ses oynatıcı eklemiyoruz,
    # bu, her yenilemede tüm geçmişi seslendirmeye çalışıp yavaşlatmasın diye.)
    for message in st.session_state.chat.history:
        avatar_icon = "👤" if message.role == "user" else "🤖"
        with st.chat_message(name=message.role, avatar=avatar_icon):
            st.markdown(message.parts[0].text)

    # Kullanıcıdan yeni girdi al
    prompt = st.chat_input("Naber kanka? Aklından ne geçiyor?")

    if prompt:
        # Kullanıcının mesajını ekrana bas
        with st.chat_message("user", avatar="👤"):
            st.markdown(prompt)
        
        # Modeli çalıştır ve cevabı al
        with st.spinner("Kanka bi' saniye, bakıyorum..."):
            try:
                response = st.session_state.chat.send_message(prompt)
                
                # Modelin cevabını ekrana bas
                with st.chat_message("assistant", avatar="🤖"):
                    st.markdown(response.text)
                    
                    # --- YENİ EKLENTİ: Sesi Oluştur ve Oynat ---
                    with st.spinner("Cevap seslendiriliyor..."):
                        audio_data = text_to_audio(response.text)
                        if audio_data:
                            st.audio(audio_data, format='audio/mp3')
                    # <--- YENİ EKLENTİ Bitişi ---
            
            except Exception as e:
                st.error(f"Eyvah, bir sorun çıktı kanka: {e}")

except KeyError:
    st.error("API Anahtarı bulunamadı! Lütfen Hugging Face Space'inizin 'Settings' > 'Secrets' bölümüne 'GEMINI_API_KEY' olarak ekleyin.")
except Exception as e:
    st.error(f"Genel bir hata oluştu: {e}")