File size: 7,167 Bytes
df3f92e
 
 
 
998eb02
df3f92e
eb131e7
df3f92e
eb131e7
 
 
 
 
 
 
 
 
df3f92e
 
 
eb131e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df3f92e
 
 
eb131e7
 
 
 
 
 
 
 
 
 
df3f92e
eb131e7
df3f92e
 
 
eb131e7
 
 
 
 
 
 
 
 
 
df3f92e
 
eb131e7
 
 
 
 
 
 
df3f92e
 
 
 
 
 
 
eb131e7
df3f92e
eb131e7
df3f92e
eb131e7
 
 
 
 
 
df3f92e
eb131e7
df3f92e
 
 
 
eb131e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df3f92e
 
eb131e7
df3f92e
eb131e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df3f92e
eb131e7
df3f92e
 
 
 
eb131e7
 
 
 
 
 
df3f92e
 
eb131e7
 
 
 
df3f92e
 
 
eb131e7
 
df3f92e
 
eb131e7
 
 
 
 
 
df3f92e
eb131e7
 
df3f92e
eb131e7
 
df3f92e
eb131e7
 
 
 
df3f92e
eb131e7
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import streamlit as st
import os
from groq import Groq
from gtts import gTTS
from langchain_community.document_loaders import PyPDFLoader
import tempfile
import base64

# --- CONFIGURATION ---
st.set_page_config(page_title="Zara: AI Interviewer", page_icon="👩‍💼", layout="wide")

# API Key Check
if "GROQ_API_KEY" in st.secrets:
    api_key = st.secrets["GROQ_API_KEY"]
else:
    st.error("GROQ_API_KEY not found in secrets!")
    st.stop()

client = Groq(api_key=api_key)

# --- AVATAR URLLERİ (Burayı değiştirebilirsin) ---
# "Idle": Dinlerken duran (hafif hareketli) avatar
AVATAR_IDLE = "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcDd5Y3h6a2txY3Z4bnZtY3Z4bnZtY3Z4bnZtY3Z4bnZtY3Z4bnZtJmVwPXYxX2ludGVybmFsX2dpZl9ieV9pZCZjdD1n/l3V0yA9zHe5m29sxW/giphy.gif"
# "Talking": Konuşurken ağzı oynayan avatar
AVATAR_TALKING = "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExYnZ5Y3h6a2txY3Z4bnZtY3Z4bnZtY3Z4bnZtY3Z4bnZtY3Z4bnZtJmVwPXYxX2ludGVybmFsX2dpZl9ieV9pZCZjdD1n/3o7TKs69j4h9vK6qTm/giphy.gif"

# --- CUSTOM CSS (Görüntülü Arama Havası İçin) ---
st.markdown("""
    <style>
        .avatar-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }
        .avatar-img {
            width: 250px;
            height: 250px;
            border-radius: 50%; /* Yuvarlak Çerçeve */
            object-fit: cover;
            border: 4px solid #4F46E5; /* Mavi Çerçeve */
            box-shadow: 0 0 20px rgba(79, 70, 229, 0.5);
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(79, 70, 229, 0); }
            100% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0); }
        }
        .stAudio {
            width: 100% !important;
        }
    </style>
""", unsafe_allow_html=True)

# --- FUNCTIONS ---

def get_response_from_llm(chat_history, resume_text):
    system_prompt = f"""
    You are Zara, a professional AI Technical Recruiter.
    INTERVIEW STYLE: Professional, encouraging, but rigorous.
    
    TASK:
    1. Analyze the candidate's RESUME.
    2. Conduct a voice interview. Ask ONE question at a time.
    3. Keep responses concise (under 3 sentences) so the conversation flows naturally.
    
    OUTPUT FORMAT:
    [Feedback/Question] ||| [Hint/Strategy]
    
    RESUME CONTEXT:
    {resume_text}
    """
    messages = [{"role": "system", "content": system_prompt}] + chat_history
    try:
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=messages,
            temperature=0.6,
            max_tokens=250,
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"Error: {e} ||| No hint."

def text_to_speech(text):
    try:
        tts = gTTS(text=text, lang='en')
        filename = "response.mp3"
        tts.save(filename)
        return filename
    except:
        return None

def extract_text_from_pdf(uploaded_file):
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        tmp_file.write(uploaded_file.getvalue())
        tmp_path = tmp_file.name
    loader = PyPDFLoader(tmp_path)
    pages = loader.load()
    return "".join([p.page_content for p in pages])

# --- UI LAYOUT ---

# Header
col1, col2 = st.columns([1, 4])
with col1:
    st.title("🎙️ Zara")
with col2:
    st.markdown("*AI Interview Coach*")

# Session State
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []
if "resume_text" not in st.session_state:
    st.session_state.resume_text = ""
if "current_hint" not in st.session_state:
    st.session_state.current_hint = "Upload your CV to start!"
if "avatar_state" not in st.session_state:
    st.session_state.avatar_state = "idle" # idle or talking

# Sidebar
with st.sidebar:
    st.header("⚙️ Setup")
    uploaded_file = st.file_uploader("Upload CV (PDF)", type="pdf")
    if st.button("Reset Interview"):
        st.session_state.clear()
        st.rerun()

# --- AVATAR DISPLAY AREA (CENTER STAGE) ---
avatar_placeholder = st.empty()

def render_avatar(state):
    image_url = AVATAR_TALKING if state == "talking" else AVATAR_IDLE
    avatar_placeholder.markdown(f"""
        <div class="avatar-container">
            <img src="{image_url}" class="avatar-img">
        </div>
    """, unsafe_allow_html=True)

# Başlangıçta IDLE (Duran) göster
render_avatar("idle")

# --- MAIN LOGIC ---

if uploaded_file and not st.session_state.resume_text:
    with st.spinner("Zara is reading your resume..."):
        st.session_state.resume_text = extract_text_from_pdf(uploaded_file)
        
        # İlk Soru
        full_response = get_response_from_llm([], st.session_state.resume_text)
        q_part, h_part = full_response.split("|||") if "|||" in full_response else (full_response, "Intro")
        
        st.session_state.chat_history.append({"role": "assistant", "content": q_part.strip()})
        st.session_state.current_hint = h_part.strip()
        
        # KONUŞMA MODU: Avatarı 'talking' yap
        render_avatar("talking")
        
        # Sesi Çal
        audio_file = text_to_speech(q_part.strip())
        if audio_file:
            st.audio(audio_file, format="audio/mp3", autoplay=True)
        
        # (Not: Streamlit audio bitince otomatik resim değiştiremez, 
        # bu yüzden konuşma bitince manuel bir işlem gerekebilir ama görsel olarak bu yeterlidir)

# Chat History Display
for message in st.session_state.chat_history:
    with st.chat_message(message["role"]):
        st.write(message["content"])

# Hint Area
with st.expander("💡 Reveal Hint"):
    st.info(st.session_state.current_hint)

# Audio Input
audio_value = st.audio_input("🎤 Record Your Answer")

if audio_value:
    # Kullanıcı konuşurken Zara IDLE moduna geçer
    render_avatar("idle")
    
    with st.spinner("Listening..."):
        transcription = client.audio.transcriptions.create(
            file=("input.wav", audio_value, "audio/wav"),
            model="whisper-large-v3",
            response_format="text", 
            language="en"
        )
    
    st.session_state.chat_history.append({"role": "user", "content": transcription})
    
    with st.spinner("Zara is thinking..."):
        clean_history = [{"role": m["role"], "content": m["content"]} for m in st.session_state.chat_history]
        full_response = get_response_from_llm(clean_history, st.session_state.resume_text)
        q_part, h_part = full_response.split("|||") if "|||" in full_response else (full_response, "No hint")
    
    st.session_state.chat_history.append({"role": "assistant", "content": q_part.strip()})
    st.session_state.current_hint = h_part.strip()
    
    # CEVAP HAZIRLANDI: Avatarı 'talking' yap
    render_avatar("talking")
    
    # Sesi çal
    audio_file = text_to_speech(q_part.strip())
    if audio_file:
        st.audio(audio_file, format="audio/mp3", autoplay=True)
    
    # Sayfa yenilenmesin diye rerun yapmıyoruz, akış devam ediyor