huseyinemretech commited on
Commit
cdbf52e
·
verified ·
1 Parent(s): 5fd80c9

Direct API Deployment: Backend Only

Browse files
.gitattributes CHANGED
@@ -1,35 +1,39 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.jpg filter=lfs diff=lfs merge=lfs -text
38
+ *.svg filter=lfs diff=lfs merge=lfs -text
39
+ *.json filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Node
2
+ node_modules/
3
+ package-lock.json
4
+ .pnpm-lock.yaml
5
+
6
+ # Python
7
+ __pycache__/
8
+ *.pyc
9
+ *.pyo
10
+ *.egg-info/
11
+ .eggs/
12
+ dist/
13
+ build/
14
+ *.egg
15
+
16
+ # Vite
17
+ dist/
18
+ .vite/
19
+
20
+ # IDE
21
+ .idea/
22
+ .vscode/
23
+ *.swp
24
+ *.swo
25
+
26
+ # OS
27
+ .DS_Store
28
+ Thumbs.db
29
+
30
+ # Logs
31
+ *.log
32
+ npm-debug.log*
33
+
34
+ # Test
35
+ .pytest_cache/
36
+ .coverage
37
+
38
+ # Large files (optional - add specific ones if needed)
39
+ # *.h5
40
+ # *.pkl
41
+ # *.pt
42
+ `n# Large data folders`nbackend/data/`nbackend/models/`n*.ckpt`n
DEPLOYMENT.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Hugging Face Spaces Deployment Rehberi
2
+
3
+ SesleAI projesini Hugging Face Spaces'e yayınlamak için adım adım kılavuz.
4
+
5
+ ## 📋 Ön Gereksinimler
6
+
7
+ 1. **Hugging Face Hesabı**: [huggingface.co](https://huggingface.co) üzerinde ücretsiz hesap oluşturun
8
+ 2. **Git**: Sisteminizde Git yüklü olmalı
9
+ 3. **Git LFS**: Büyük dosyalar için Git LFS kurulu olmalı
10
+
11
+ ### Git LFS Kurulumu
12
+
13
+ ```bash
14
+ # Windows için
15
+ git lfs install
16
+ ```
17
+
18
+ ## 🎯 Adım 1: Hugging Face Space Oluşturma
19
+
20
+ 1. Hugging Face hesabınıza giriş yapın
21
+ 2. [https://huggingface.co/new-space](https://huggingface.co/new-space) adresine gidin
22
+ 3. Aşağıdaki bilgileri girin:
23
+ - **Space name**: `sesleai-customer-support` (veya tercih ettiğiniz isim)
24
+ - **License**: MIT
25
+ - **Select the Space SDK**: **Docker** seçin
26
+ - **Space hardware**: CPU basic (ücretsiz) ile başlayabilirsiniz
27
+ - **Visibility**: Public veya Private (tercihinize göre)
28
+
29
+ 4. **Create Space** butonuna tıklayın
30
+
31
+ ## 🔗 Adım 2: Git Repository Hazırlama
32
+
33
+ Space oluşturulduktan sonra, terminal veya PowerShell'de şu komutları çalıştırın:
34
+
35
+ ```bash
36
+ # Proje dizinine gidin
37
+ cd "C:\Users\hsyne\Desktop\Sesli-Kimlik-ve-Duygu-Dogrulamali-Musteri-Temsilcisi-Destek-Sistemi_SesleAI\turkcell-proje"
38
+
39
+ # Git LFS'i başlatın (eğer daha önce yapmadıysanız)
40
+ git lfs install
41
+
42
+ # Hugging Face Space'inizi remote olarak ekleyin
43
+ # NOT: <USERNAME> yerine kendi Hugging Face kullanıcı adınızı yazın
44
+ # NOT: <SPACE_NAME> yerine oluşturduğunuz space adını yazın
45
+ git remote add hf https://huggingface.co/spaces/<USERNAME>/<SPACE_NAME>
46
+ ```
47
+
48
+ **Örnek:**
49
+ ```bash
50
+ git remote add hf https://huggingface.co/spaces/johndoe/sesleai-customer-support
51
+ ```
52
+
53
+ ## 📤 Adım 3: Kodu Hugging Face'e Push Etme
54
+
55
+ ### Kimlik Doğrulama
56
+
57
+ İlk push işleminde Hugging Face sizden kullanıcı adı ve şifre isteyecek:
58
+ - **Username**: Hugging Face kullanıcı adınız
59
+ - **Password**: Hugging Face Access Token (şifre değil!)
60
+
61
+ > [!IMPORTANT]
62
+ > **Access Token Oluşturma:**
63
+ > 1. [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) adresine gidin
64
+ > 2. **New token** butonuna tıklayın
65
+ > 3. Token adı verin (örn. "space-upload")
66
+ > 4. **Role**: **Write** seçin
67
+ > 5. **Generate token** ve token'ı kopyalayın
68
+ > 6. Bu token'ı şifre yerine kullanın
69
+
70
+ ### Push İşlemi
71
+
72
+ ```bash
73
+ # Tüm dosyaları staging'e ekleyin
74
+ git add .
75
+
76
+ # Commit oluşturun
77
+ git commit -m "Initial deployment to Hugging Face Spaces"
78
+
79
+ # Hugging Face'e push edin
80
+ git push hf main
81
+ ```
82
+
83
+ > [!TIP]
84
+ > Eğer branch adınız `main` değil de `master` ise:
85
+ > ```bash
86
+ > git push hf master:main
87
+ > ```
88
+
89
+ ## ⏱️ Adım 4: Build Sürecini İzleme
90
+
91
+ 1. Space sayfanıza gidin: `https://huggingface.co/spaces/<USERNAME>/<SPACE_NAME>`
92
+ 2. Üst kısımda build durumunu göreceksiniz
93
+ 3. **Building** durumunu göreceksiniz (yaklaşık 10-15 dakika sürer)
94
+ 4. Build tamamlandığında **Running** durumuna geçecek
95
+
96
+ ### Build Loglarını İzleme
97
+
98
+ - Space sayfasında **Logs** sekmesine tıklayarak build sürecini takip edebilirsiniz
99
+ - Hata durumunda logları kontrol edin
100
+
101
+ ## ✅ Adım 5: Doğrulama ve Test
102
+
103
+ Build tamamlandıktan sonra:
104
+
105
+ ### Otomatik Testler
106
+
107
+ 1. **Uygulama Yükleme**: Space URL'ine gidin ve ana sayfanın yüklendiğini kontrol edin
108
+ 2. **Mikrofon Erişimi**: Tarayıcı mikrofon izni isteyecek, izin verin
109
+ 3. **Ses Kaydı**: "Kayıt Başlat" butonuna tıklayın ve test edin
110
+ 4. **API Yanıtları**: Ses kaydı sonrası sonuçların geldiğini kontrol edin
111
+ 5. **Tema**: Açık/Koyu mod geçişini test edin
112
+
113
+ ### Manuel Kontrollar
114
+
115
+ - [ ] Ana sayfa düzgün yükleniyor mu?
116
+ - [ ] Kayıt butonu çalışıyor mu?
117
+ - [ ] Ses kaydı yapılabiliyor mu?
118
+ - [ ] Kimlik doğrulama API'si yanıt veriyor mu?
119
+ - [ ] Duygu analizi API'si yanıt veriyor mu?
120
+ - [ ] Müşteri bilgileri görüntüleniyor mu?
121
+ - [ ] Mobil görünüm düzgün çalışıyor mu?
122
+ - [ ] Tema değişimi çalışıyor mu?
123
+
124
+ ## 🔧 Sorun Giderme
125
+
126
+ ### Build Hatası
127
+
128
+ **Problem**: Docker build başarısız oluyor
129
+
130
+ **Çözüm**:
131
+ 1. Logs sekmesinden hata mesajını kontrol edin
132
+ 2. Genellikle eksik dependency veya syntax hatası olur
133
+ 3. Gerekli düzeltmeleri yapıp tekrar push edin
134
+
135
+ ### Uygulama Başlamıyor
136
+
137
+ **Problem**: Build başarılı ama uygulama çalışmıyor
138
+
139
+ **Çözüm**:
140
+ 1. Logs sekmesinde runtime hatalarını kontrol edin
141
+ 2. Port 7860'ın doğru kullanıldığından emin olun
142
+ 3. supervisord loglarını inceleyin
143
+
144
+ ### Model İndirilemiyor
145
+
146
+ **Problem**: Hugging Face modelleri indirilemedi
147
+
148
+ **Çözüm**:
149
+ - İlk çalıştırmada modeller otomatik indirilir, bu zaman alabilir
150
+ - Timeout olursa Space'i yeniden başlatın (Settings > Factory reboot)
151
+
152
+ ### API Çalışmıyor
153
+
154
+ **Problem**: Frontend yükleniyor ama API istekleri başarısız
155
+
156
+ **Çözüm**:
157
+ 1. Browser Console'da network hatalarını kontrol edin
158
+ 2. nginx proxy ayarlarını kontrol edin
159
+ 3. Backend loglarına bakın
160
+
161
+ ## 🔄 Güncelleme Yapmak
162
+
163
+ Projeyi güncellemek için:
164
+
165
+ ```bash
166
+ # Değişiklikleri commit edin
167
+ git add .
168
+ git commit -m "Update: açıklama"
169
+
170
+ # Hugging Face'e push edin
171
+ git push hf main
172
+ ```
173
+
174
+ Her push sonrası Space otomatik olarak yeniden build edilir.
175
+
176
+ ## 📊 Performans Optimizasyonu
177
+
178
+ ### Build Süresini Azaltma
179
+
180
+ 1. **Layer Cache**: Dockerfile'da sık değişmeyen komutları üste alın
181
+ 2. **Dependencies**: Gereksiz bağımlılıkları kaldırın
182
+ 3. **.dockerignore**: Gereksiz dosyaların kopyalanmasını engelleyin
183
+
184
+ ### Runtime Performansı
185
+
186
+ 1. **Hardware Upgrade**: Ücretsiz CPU yeterli değilse, CPU Upgrade veya GPU düşünün
187
+ 2. **Model Cache**: Model indirme süresini azaltmak için custom Dockerfile layer'ı ekleyin
188
+
189
+ ## 🌐 Özel Domain (Opsiyonel)
190
+
191
+ Hugging Face Spaces, özel domain bağlamanıza izin verir:
192
+
193
+ 1. Space Settings > Custom domain
194
+ 2. DNS kayıtlarını yapılandırın
195
+ 3. Doğrulama bekleyin
196
+
197
+ ## 📱 Paylaşım
198
+
199
+ Space'inizi paylaşmak için:
200
+
201
+ - **Direct Link**: `https://huggingface.co/spaces/<USERNAME>/<SPACE_NAME>`
202
+ - **Embed**: Space'i iframe ile embedding yapabilirsiniz
203
+ - **Badge**: README'ye badge ekleyebilirsiniz
204
+
205
+ ## 🎉 Başarılı Deployment!
206
+
207
+ Tebrikler! SesleAI projeniz artık Hugging Face Spaces'de yayında!
208
+
209
+ Space URL'inizi paylaşabilir ve herkesin kullanımına sunabilirsiniz.
210
+
211
+ ---
212
+
213
+ ## 📞 Destek
214
+
215
+ Sorun yaşarsanız:
216
+ - Hugging Face Discord: [https://huggingface.co/join/discord](https://huggingface.co/join/discord)
217
+ - Hugging Face Forum: [https://discuss.huggingface.co](https://discuss.huggingface.co)
Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-stage build for SesleAI
2
+ # Use Python 3.11 slim image
3
+ FROM python:3.11-slim
4
+
5
+ # Install system dependencies in stages to avoid RAM spikes
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ nginx \
8
+ supervisor \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ libsndfile1 \
13
+ ffmpeg \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ WORKDIR /app
17
+
18
+ # Copy backend requirements and install
19
+ COPY requirements.txt .
20
+ RUN pip install --no-cache-dir -r requirements.txt
21
+
22
+ # Copy backend code
23
+ COPY backend ./backend
24
+ COPY emotion_api ./emotion_api
25
+
26
+ # Copy configuration files
27
+ COPY nginx.conf /etc/nginx/nginx.conf
28
+ COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
29
+
30
+ # Create directory for nginx logs
31
+ RUN mkdir -p /var/log/nginx && \
32
+ chown -R www-data:www-data /var/log/nginx
33
+
34
+ # Expose the port (7860 is standard for HF Spaces)
35
+ EXPOSE 7860
36
+
37
+ # Start supervisor to run both APIs and Nginx
38
+ CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
README.md CHANGED
@@ -1,10 +1,77 @@
1
- ---
2
- title: Turkcell 2
3
- emoji: 🐨
4
- colorFrom: red
5
- colorTo: pink
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Turkcell Proje - SesleAI
3
+ emoji: 🎤
4
+ colorFrom: yellow
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: mit
10
+ ---
11
+
12
+ # 🎤 SesleAI - Sesli Kimlik ve Duygu Doğrulama Sistemi
13
+
14
+ Müşteri temsilcisi destek sistemi için yapay zeka destekli sesli kimlik doğrulama ve duygu analizi uygulaması.
15
+
16
+ ## ✨ Özellikler
17
+
18
+ - 🎤 **Sesli Kimlik Doğrulama**: Ses kaydı ile kullanıcı kimlik doğrulama (SpeechBrain speaker recognition)
19
+ - 😊 **Duygu Analizi**: Ses tonundan gerçek zamanlı duygu tespiti (Wav2Vec2)
20
+ - 📊 **Müşteri Bilgileri**: Detaylı paket ve kullanım bilgileri
21
+ - 🌙 **Modern Arayüz**: Liquid Glass tasarımı ile açık/koyu mod desteği
22
+ - 🔒 **Güvenli**: Ses verileri işlendikten sonra saklanmaz
23
+ - 📱 **Responsive**: Mobil ve masaüstü uyumlu
24
+
25
+ ## 🚀 Kullanım
26
+
27
+ 1. Uygulamayı açın ve mikrofon iznini verin
28
+ 2. "Kayıt Başlat" butonuna tıklayın
29
+ 3. Birkaç saniye konuşun
30
+ 4. Sistem otomatik olarak kimliğinizi doğrulayacak ve duygunuzu analiz edecek
31
+ 5. Müşteri bilgileriniz ekranda görüntülenecek
32
+
33
+ ## 🛠️ Teknolojiler
34
+
35
+ ### Frontend
36
+ - **React 18** + **Vite** - Modern, hızlı web arayüzü
37
+ - **Liquid Glass Design** - Premium görsel tasarım
38
+
39
+ ### Backend
40
+ - **FastAPI** - Yüksek performanslı Python web framework
41
+ - **Nginx** - Reverse proxy ve static file serving
42
+ - **Supervisor** - Process management
43
+
44
+ ### AI/ML
45
+ - **Wav2Vec2** - Duygu analizi için Facebook'un pre-trained modeli
46
+ - **SpeechBrain** - Konuşmacı tanıma ve doğrulama
47
+ - **PyTorch** - Deep learning framework
48
+ - **Transformers** - Hugging Face model kütüphanesi
49
+
50
+ ## 📦 Deployment
51
+
52
+ Detaylı deployment talimatları için [DEPLOYMENT.md](DEPLOYMENT.md) dosyasına bakın.
53
+
54
+ ### Hızlı Başlangıç
55
+
56
+ ```bash
57
+ # Docker ile lokal çalıştırma
58
+ docker build -t sesleai .
59
+ docker run -p 7860:7860 sesleai
60
+ ```
61
+
62
+ Tarayıcınızda `http://localhost:7860` adresine gidin.
63
+
64
+ ## 📄 Lisans
65
+
66
+ MIT License - Detaylar için LICENSE dosyasına bakın.
67
+
68
+ ## 🤝 Katkıda Bulunma
69
+
70
+ Katkılarınızı bekliyoruz! Pull request göndermekten çekinmeyin.
71
+
72
+ ## 📧 İletişim
73
+
74
+ Sorularınız için issue açabilirsiniz.
75
+
76
+ <!-- Trigger rebuild: fix-paused-state -->
77
+
backend/api/6319.wav ADDED
Binary file (91.3 kB). View file
 
backend/api/672_0.flac ADDED
Binary file (87.1 kB). View file
 
backend/api/audio.webm;codecs=opus ADDED
Binary file (110 Bytes). View file
 
backend/api/main.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uvicorn
3
+ from fastapi import FastAPI, File, UploadFile
4
+ from fastapi.responses import JSONResponse
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from speaker_api import SpeakerRecognitionAPI
7
+
8
+ # FastAPI uygulamasını başlat
9
+ app = FastAPI()
10
+
11
+ # CORS ayarları
12
+ origins = [
13
+ "*"
14
+ ]
15
+
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=origins,
19
+ allow_credentials=True,
20
+ allow_methods=["*"],
21
+ allow_headers=["*"],
22
+ )
23
+
24
+ try:
25
+ api = SpeakerRecognitionAPI()
26
+ except Exception as e:
27
+ print(f"API başlatılırken bir hata oluştu: {e}")
28
+ api = None
29
+
30
+ @app.get("/")
31
+ def read_root():
32
+ return {"message": "Ses Kimlik Tespiti API'si çalışıyor."}
33
+
34
+ @app.post("/register/")
35
+ async def register_speaker(name: str, audio_files: list[UploadFile] = File(...)):
36
+ if not api:
37
+ return JSONResponse(status_code=500, content={"error": "API başlatılamadı."})
38
+
39
+ temp_audio_paths = []
40
+ for audio_file in audio_files:
41
+ temp_audio_path = os.path.join(os.getcwd(), audio_file.filename)
42
+ with open(temp_audio_path, "wb") as f:
43
+ f.write(await audio_file.read())
44
+ temp_audio_paths.append(temp_audio_path)
45
+
46
+ success, message = api.register_speaker_with_multiple_files(name, temp_audio_paths)
47
+
48
+ for temp_path in temp_audio_paths:
49
+ os.remove(temp_path)
50
+
51
+ if success:
52
+ return JSONResponse(status_code=200, content={"message": message})
53
+ else:
54
+ return JSONResponse(status_code=400, content={"error": message})
55
+
56
+ @app.post("/recognize/")
57
+ async def recognize_speaker(audio_file: UploadFile = File(...)):
58
+ if not api:
59
+ return JSONResponse(status_code=500, content={"error": "API başlatılamadı."})
60
+
61
+ temp_audio_path = os.path.join(os.getcwd(), audio_file.filename)
62
+ with open(temp_audio_path, "wb") as f:
63
+ f.write(await audio_file.read())
64
+
65
+ success, result = api.recognize_speaker(temp_audio_path)
66
+
67
+ os.remove(temp_audio_path)
68
+
69
+ if success:
70
+ return JSONResponse(status_code=200, content=result)
71
+ else:
72
+ return JSONResponse(status_code=404, content={"error": result})
73
+
74
+ @app.post("/update_speaker/")
75
+ async def update_speaker(name: str, audio_files: list[UploadFile] = File(...)):
76
+ if not api:
77
+ return JSONResponse(status_code=500, content={"error": "API başlatılamadı."})
78
+
79
+ temp_audio_paths = []
80
+ for audio_file in audio_files:
81
+ temp_audio_path = os.path.join(os.getcwd(), audio_file.filename)
82
+ with open(temp_audio_path, "wb") as f:
83
+ f.write(await audio_file.read())
84
+ temp_audio_paths.append(temp_audio_path)
85
+
86
+ success, message = api.update_speaker(name, temp_audio_paths)
87
+
88
+ for temp_path in temp_audio_paths:
89
+ os.remove(temp_path)
90
+
91
+ if success:
92
+ return JSONResponse(status_code=200, content={"message": message})
93
+ else:
94
+ return JSONResponse(status_code=400, content={"error": message})
95
+
96
+ @app.post("/correct_guess/")
97
+ async def correct_guess(name: str, audio_file: UploadFile = File(...)):
98
+ if not api:
99
+ return JSONResponse(status_code=500, content={"error": "API başlatılamadı."})
100
+
101
+ temp_audio_path = os.path.join(os.getcwd(), audio_file.filename)
102
+ with open(temp_audio_path, "wb") as f:
103
+ f.write(await audio_file.read())
104
+
105
+ success, message = api.correct_guess(name, [temp_audio_path])
106
+
107
+ os.remove(temp_audio_path)
108
+
109
+ if success:
110
+ return JSONResponse(status_code=200, content={"message": message})
111
+ else:
112
+ return JSONResponse(status_code=400, content={"error": message})
113
+
114
+ if __name__ == "__main__":
115
+ uvicorn.run(app, host="0.0.0.0", port=8000)
backend/api/speaker_api.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ import torchaudio
5
+ import json
6
+ import numpy as np
7
+ from speechbrain.pretrained import EncoderClassifier
8
+ from sklearn.preprocessing import LabelEncoder
9
+ import soundfile as sf
10
+ import io
11
+
12
+ # Bu dosyanın bulunduğu klasörün mutlak yolunu al
13
+ API_DIR = os.path.dirname(os.path.abspath(__file__))
14
+
15
+ # GPU varsa kullan, yoksa CPU
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+ class SpeakerRecognitionAPI:
19
+ def __init__(self):
20
+ self.models_path = os.path.join(API_DIR, '../models')
21
+ self.db_path = os.path.join(API_DIR, 'speakers_db.json')
22
+
23
+ # Sadece encoder kısmını yüklüyoruz. Sınıflandırıcı artık kullanılmayacak.
24
+ self.encoder_classifier = self._load_encoder()
25
+ self.speakers_db = {}
26
+ self._load_speakers_db()
27
+ self._update_label_encoder()
28
+
29
+ def _load_encoder(self):
30
+ print("Model yükleniyor...")
31
+ try:
32
+ model = EncoderClassifier.from_hparams(
33
+ source="speechbrain/spkrec-xvect-voxceleb",
34
+ savedir=os.path.join(self.models_path, "pretrained-ecapa"),
35
+ run_opts={"device": device}
36
+ )
37
+ model.to(device)
38
+ model.eval()
39
+ print("Model başarıyla yüklendi.")
40
+ return model
41
+ except Exception as e:
42
+ print(f"Hata: Model yüklenirken bir sorun oluştu. Detay: {e}")
43
+ raise
44
+
45
+ def _load_speakers_db(self):
46
+ if os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
47
+ with open(self.db_path, 'r') as f:
48
+ self.speakers_db = json.load(f)
49
+ else:
50
+ self.speakers_db = {}
51
+
52
+ def _update_label_encoder(self): #Sadece api uygulamalarında güncelleme kullanılabilecek, müşteri hizmetleri tarafında bulunması mantıklı değil.
53
+ if not self.speakers_db:
54
+ self.label_encoder = None
55
+ return
56
+
57
+ speakers = list(self.speakers_db.keys())
58
+ self.label_encoder = LabelEncoder()
59
+ self.label_encoder.fit(speakers)
60
+
61
+ def _extract_embedding(self, audio_path):
62
+ try:
63
+ # Ses dosyasını soundfile ile oku (daha esnek)
64
+ audio, sr = sf.read(audio_path)
65
+ # numpy array'ini torch tensor'a dönüştür
66
+ signal = torch.from_numpy(audio).float().unsqueeze(0).to(device)
67
+
68
+ with torch.no_grad():
69
+ embeddings = self.encoder_classifier.encode_batch(signal).squeeze()
70
+ return embeddings.detach().cpu().numpy()
71
+ except Exception as e:
72
+ print(f"Embedding çıkarma hatası: {e}")
73
+ raise
74
+
75
+ def register_speaker_with_multiple_files(self, name, audio_paths):
76
+ if name in self.speakers_db:
77
+ return False, "Bu isimde bir konuşmacı zaten kayıtlı."
78
+
79
+ embeddings = []
80
+ for path in audio_paths:
81
+ embedding = self._extract_embedding(path)
82
+ embeddings.append(embedding.tolist())
83
+
84
+ self.speakers_db[name] = embeddings
85
+
86
+ with open(self.db_path, 'w') as f:
87
+ json.dump(self.speakers_db, f, indent=4)
88
+
89
+ self._update_label_encoder()
90
+ return True, "Konuşmacı başarıyla kaydedildi."
91
+
92
+ def update_speaker(self, name, audio_paths):
93
+ if name not in self.speakers_db:
94
+ return False, "Bu isimde bir konuşmacı kayıtlı değil."
95
+
96
+ for path in audio_paths:
97
+ new_embedding = self._extract_embedding(path)
98
+ self.speakers_db[name].append(new_embedding.tolist())
99
+
100
+ with open(self.db_path, 'w') as f:
101
+ json.dump(self.speakers_db, f, indent=4)
102
+
103
+ self._update_label_encoder()
104
+ return True, "Konuşmacı başarıyla güncellendi."
105
+
106
+ def recognize_speaker(self, audio_path, threshold=0.85):
107
+ if not self.speakers_db:
108
+ return False, {"error": "Sistemde kayıtlı konuşmacı bulunamadı. Lütfen önce birini kaydedin."}
109
+
110
+ new_embedding = self._extract_embedding(audio_path)
111
+
112
+ max_similarity = -1.0
113
+ predicted_speaker = "Bilinmiyor"
114
+
115
+ for speaker_name, embeddings_list in self.speakers_db.items():
116
+ for embedding_from_db in embeddings_list:
117
+ db_embedding_np = np.array(embedding_from_db)
118
+ similarity = np.dot(new_embedding, db_embedding_np) / (np.linalg.norm(new_embedding) * np.linalg.norm(db_embedding_np))
119
+
120
+ if similarity > max_similarity:
121
+ max_similarity = similarity
122
+ predicted_speaker = speaker_name
123
+
124
+ if max_similarity > threshold:
125
+ return True, {"speaker": predicted_speaker, "confidence": max_similarity}
126
+ else:
127
+ return False, {"message": "Konuşmacı tanınamıyor. Veritabanına kayıtlı değil.", "confidence": max_similarity}
128
+
129
+ def correct_guess(self, name, audio_paths):
130
+ if name not in self.speakers_db:
131
+ return False, f"Doğru olduğunu belirttiğiniz '{name}' isimli konuşmacı kayıtlı değil."
132
+
133
+ return self.update_speaker(name, audio_paths)
backend/api/speakers_db.json ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "phone_number": "05327678989",
4
+ "role": "owner",
5
+ "full_name": "Mehmet Şimşek",
6
+ "package_name": "GNC 8 GB",
7
+ "voice_embedding": null
8
+ },
9
+ {
10
+ "phone_number": "05327678989",
11
+ "role": "user",
12
+ "full_name": "Derya Şimşek",
13
+ "package_name": "Platinum 40 GB",
14
+ "voice_embedding": null
15
+ },
16
+ {
17
+ "phone_number": "05321234567",
18
+ "role": "owner",
19
+ "full_name": "Ayşe Yılmaz",
20
+ "package_name": "GNC 8 GB",
21
+ "voice_embedding": null
22
+ },
23
+ {
24
+ "phone_number": "05418065249",
25
+ "role": "owner",
26
+ "full_name": "İlayda Özdemir",
27
+ "package_name": "GNC 8 GB",
28
+ "voice_embedding": null
29
+ },
30
+ {
31
+ "phone_number": "05301828830",
32
+ "role": "owner",
33
+ "full_name": "Ali Şimşek",
34
+ "package_name": "GNC 8 GB",
35
+ "voice_embedding": null
36
+ },
37
+ {
38
+ "phone_number": "05359600990",
39
+ "role": "user",
40
+ "full_name": "Selin Çetin",
41
+ "package_name": "Super 10 GB",
42
+ "voice_embedding": null
43
+ },
44
+ {
45
+ "phone_number": "05373310699",
46
+ "role": "owner",
47
+ "full_name": "Nil Şahin",
48
+ "package_name": "GNC 20 GB",
49
+ "voice_embedding": null
50
+ },
51
+ {
52
+ "phone_number": "05386352363",
53
+ "role": "owner",
54
+ "full_name": "Volkan Yıldız",
55
+ "package_name": "GNC 30 GB",
56
+ "voice_embedding": null
57
+ },
58
+ {
59
+ "phone_number": "05328117971",
60
+ "role": "owner",
61
+ "full_name": "Fatma Yıldız",
62
+ "package_name": "GNC 30 GB",
63
+ "voice_embedding": null
64
+ },
65
+ {
66
+ "phone_number": "05361964588",
67
+ "role": "user",
68
+ "full_name": "Ahmet Şahin",
69
+ "package_name": "GNC 20 GB",
70
+ "voice_embedding": null
71
+ },
72
+ {
73
+ "phone_number": "05339301563",
74
+ "role": "owner",
75
+ "full_name": "Pınar Demir",
76
+ "package_name": "Super 10 GB",
77
+ "voice_embedding": null
78
+ },
79
+ {
80
+ "phone_number": "05357886420",
81
+ "role": "owner",
82
+ "full_name": "Deniz Özkan",
83
+ "package_name": "GNC 30 GB",
84
+ "voice_embedding": null
85
+ },
86
+ {
87
+ "phone_number": "05342160016",
88
+ "role": "owner",
89
+ "full_name": "Mehmet Yıldırım",
90
+ "package_name": "GNC 8 GB",
91
+ "voice_embedding": null
92
+ },
93
+ {
94
+ "phone_number": "05341242095",
95
+ "role": "user",
96
+ "full_name": "Mustafa Özdemir",
97
+ "package_name": "Platinum 40 GB",
98
+ "voice_embedding": null
99
+ },
100
+ {
101
+ "phone_number": "05313138063",
102
+ "role": "user",
103
+ "full_name": "Kaan Aslan",
104
+ "package_name": "Super 10 GB",
105
+ "voice_embedding": null
106
+ },
107
+ {
108
+ "phone_number": "05313511367",
109
+ "role": "user",
110
+ "full_name": "Burak Kara",
111
+ "package_name": "Super 10 GB",
112
+ "voice_embedding": null
113
+ },
114
+ {
115
+ "phone_number": "05383255738",
116
+ "role": "user",
117
+ "full_name": "Can Yıldırım",
118
+ "package_name": "GNC 30 GB",
119
+ "voice_embedding": null
120
+ },
121
+ {
122
+ "phone_number": "05398577037",
123
+ "role": "user",
124
+ "full_name": "Ahmet Özdemir",
125
+ "package_name": "GNC 30 GB",
126
+ "voice_embedding": null
127
+ },
128
+ {
129
+ "phone_number": "05352593785",
130
+ "role": "owner",
131
+ "full_name": "Deniz Aslan",
132
+ "package_name": "GNC 30 GB",
133
+ "voice_embedding": null
134
+ },
135
+ {
136
+ "phone_number": "05307185056",
137
+ "role": "owner",
138
+ "full_name": "Ali Öztürk",
139
+ "package_name": "GNC 30 GB",
140
+ "voice_embedding": null
141
+ },
142
+ {
143
+ "phone_number": "05395529648",
144
+ "role": "user",
145
+ "full_name": "Ahmet Demir",
146
+ "package_name": "Platinum 40 GB",
147
+ "voice_embedding": null
148
+ },
149
+ {
150
+ "phone_number": "05357380459",
151
+ "role": "owner",
152
+ "full_name": "Mert Kaya",
153
+ "package_name": "Platinum 40 GB",
154
+ "voice_embedding": null
155
+ },
156
+ {
157
+ "phone_number": "05321344003",
158
+ "role": "owner",
159
+ "full_name": "Ayşe Arslan",
160
+ "package_name": "GNC 8 GB",
161
+ "voice_embedding": null
162
+ },
163
+ {
164
+ "phone_number": "05332840057",
165
+ "role": "owner",
166
+ "full_name": "Yağmur Doğan",
167
+ "package_name": "GNC 30 GB",
168
+ "voice_embedding": null
169
+ },
170
+ {
171
+ "phone_number": "05327923132",
172
+ "role": "user",
173
+ "full_name": "Ozan Demir",
174
+ "package_name": "GNC 8 GB",
175
+ "voice_embedding": null
176
+ },
177
+ {
178
+ "phone_number": "05384670633",
179
+ "role": "owner",
180
+ "full_name": "Zehra Aslan",
181
+ "package_name": "Super 10 GB",
182
+ "voice_embedding": null
183
+ },
184
+ {
185
+ "phone_number": "05308484941",
186
+ "role": "owner",
187
+ "full_name": "Ece Özkan",
188
+ "package_name": "GNC 8 GB",
189
+ "voice_embedding": null
190
+ },
191
+ {
192
+ "phone_number": "05308647415",
193
+ "role": "user",
194
+ "full_name": "Can Yıldırım",
195
+ "package_name": "GNC 30 GB",
196
+ "voice_embedding": null
197
+ },
198
+ {
199
+ "phone_number": "05305819193",
200
+ "role": "owner",
201
+ "full_name": "Mert Koç",
202
+ "package_name": "GNC 8 GB",
203
+ "voice_embedding": null
204
+ },
205
+ {
206
+ "phone_number": "05394920187",
207
+ "role": "user",
208
+ "full_name": "Burak Kurt",
209
+ "package_name": "Super 10 GB",
210
+ "voice_embedding": null
211
+ },
212
+ {
213
+ "phone_number": "05304631193",
214
+ "role": "owner",
215
+ "full_name": "Zeynep Kurt",
216
+ "package_name": "Super 10 GB",
217
+ "voice_embedding": null
218
+ },
219
+ {
220
+ "phone_number": "05332413534",
221
+ "role": "owner",
222
+ "full_name": "Zehra Yıldız",
223
+ "package_name": "Super 10 GB",
224
+ "voice_embedding": null
225
+ },
226
+ {
227
+ "phone_number": "05393920129",
228
+ "role": "owner",
229
+ "full_name": "Ahmet Yıldırım",
230
+ "package_name": "GNC 30 GB",
231
+ "voice_embedding": null
232
+ },
233
+ {
234
+ "phone_number": "05364169162",
235
+ "role": "user",
236
+ "full_name": "Ali Doğan",
237
+ "package_name": "GNC 30 GB",
238
+ "voice_embedding": null
239
+ },
240
+ {
241
+ "phone_number": "05315858208",
242
+ "role": "owner",
243
+ "full_name": "Deniz Yıldız",
244
+ "package_name": "GNC 30 GB",
245
+ "voice_embedding": null
246
+ },
247
+ {
248
+ "phone_number": "05308009396",
249
+ "role": "owner",
250
+ "full_name": "Deniz Doğan",
251
+ "package_name": "GNC 8 GB",
252
+ "voice_embedding": null
253
+ },
254
+ {
255
+ "phone_number": "05307294782",
256
+ "role": "owner",
257
+ "full_name": "Selin Arslan",
258
+ "package_name": "Super 10 GB",
259
+ "voice_embedding": null
260
+ },
261
+ {
262
+ "phone_number": "05371722957",
263
+ "role": "owner",
264
+ "full_name": "Burak Öztürk",
265
+ "package_name": "GNC 30 GB",
266
+ "voice_embedding": null
267
+ },
268
+ {
269
+ "phone_number": "05309337790",
270
+ "role": "owner",
271
+ "full_name": "Yağmur Koç",
272
+ "package_name": "GNC 20 GB",
273
+ "voice_embedding": null
274
+ },
275
+ {
276
+ "phone_number": "05364925630",
277
+ "role": "owner",
278
+ "full_name": "Cem Kılıç",
279
+ "package_name": "Super 10 GB",
280
+ "voice_embedding": null
281
+ },
282
+ {
283
+ "phone_number": "05326177918",
284
+ "role": "owner",
285
+ "full_name": "Zeynep Aslan",
286
+ "package_name": "Super 10 GB",
287
+ "voice_embedding": null
288
+ },
289
+ {
290
+ "phone_number": "05324710113",
291
+ "role": "user",
292
+ "full_name": "Deniz Doğan",
293
+ "package_name": "Platinum 40 GB",
294
+ "voice_embedding": null
295
+ },
296
+ {
297
+ "phone_number": "05327446137",
298
+ "role": "owner",
299
+ "full_name": "Hakan Yıldız",
300
+ "package_name": "GNC 8 GB",
301
+ "voice_embedding": null
302
+ },
303
+ {
304
+ "phone_number": "05353264138",
305
+ "role": "user",
306
+ "full_name": "Leyla Kurt",
307
+ "package_name": "GNC 20 GB",
308
+ "voice_embedding": null
309
+ },
310
+ {
311
+ "phone_number": "05324632973",
312
+ "role": "user",
313
+ "full_name": "Umut Özdemir",
314
+ "package_name": "GNC 8 GB",
315
+ "voice_embedding": null
316
+ },
317
+ {
318
+ "phone_number": "05362092709",
319
+ "role": "user",
320
+ "full_name": "Fatma Doğan",
321
+ "package_name": "GNC 20 GB",
322
+ "voice_embedding": null
323
+ },
324
+ {
325
+ "phone_number": "05375903042",
326
+ "role": "owner",
327
+ "full_name": "Hakan Kurt",
328
+ "package_name": "GNC 8 GB",
329
+ "voice_embedding": null
330
+ },
331
+ {
332
+ "phone_number": "05326334233",
333
+ "role": "user",
334
+ "full_name": "Cem Arslan",
335
+ "package_name": "GNC 30 GB",
336
+ "voice_embedding": null
337
+ },
338
+ {
339
+ "phone_number": "05393613655",
340
+ "role": "user",
341
+ "full_name": "Burak Şimşek",
342
+ "package_name": "GNC 8 GB",
343
+ "voice_embedding": null
344
+ },
345
+ {
346
+ "phone_number": "05329731659",
347
+ "role": "owner",
348
+ "full_name": "Volkan Aydın",
349
+ "package_name": "Super 10 GB",
350
+ "voice_embedding": null
351
+ },
352
+ {
353
+ "phone_number": "05336381936",
354
+ "role": "owner",
355
+ "full_name": "İrem Çetin",
356
+ "package_name": "GNC 20 GB",
357
+ "voice_embedding": null
358
+ },
359
+ {
360
+ "phone_number": "05377477923",
361
+ "role": "owner",
362
+ "full_name": "Mehmet Arslan",
363
+ "package_name": "GNC 30 GB",
364
+ "voice_embedding": null
365
+ },
366
+ {
367
+ "phone_number": "05365472687",
368
+ "role": "owner",
369
+ "full_name": "Mustafa Aslan",
370
+ "package_name": "GNC 20 GB",
371
+ "voice_embedding": null
372
+ },
373
+ {
374
+ "phone_number": "05395383193",
375
+ "role": "owner",
376
+ "full_name": "Leyla Arslan",
377
+ "package_name": "GNC 8 GB",
378
+ "voice_embedding": null
379
+ }
380
+ ]
backend/api/wav2vec_emotion_api.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydub import AudioSegment
4
+ import uvicorn
5
+ import torch
6
+ import torchaudio
7
+ import numpy as np
8
+ from tensorflow.keras.models import load_model
9
+ import os
10
+ import logging
11
+ import uuid
12
+ from transformers import Wav2Vec2Processor, Wav2Vec2Model
13
+
14
+ # Mirror behavior of apibackend_w2v/main_w2v.py but inside this backend
15
+
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+ app = FastAPI(
20
+ title="🎤 Wav2Vec2 Emotion Recognition API",
21
+ description="Ses tabanlı duygu tanıma API'si - Wav2Vec2 modeli ile eğitilmiş",
22
+ version="1.0.0"
23
+ )
24
+
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["*"],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
34
+ MODELS = {}
35
+ LABEL_ENCODER = None
36
+ WAV2VEC_PROCESSOR = None
37
+ WAV2VEC_MODEL = None
38
+
39
+ EN_TO_TR = {
40
+ "neutral": "Nötr",
41
+ "calm": "Sakin",
42
+ "happy": "Mutlu",
43
+ "sad": "Üzgün",
44
+ "angry": "Kızgın",
45
+ "fearful": "Endişeli",
46
+ "disgust": "Hoşnutsuz",
47
+ "surprised": "Şaşkın",
48
+ }
49
+
50
+ def load_wav2vec_models():
51
+ global WAV2VEC_PROCESSOR, WAV2VEC_MODEL
52
+ try:
53
+ WAV2VEC_PROCESSOR = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base")
54
+ WAV2VEC_MODEL = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base")
55
+ WAV2VEC_MODEL.eval()
56
+ logger.info("✅ Wav2Vec2 models loaded successfully")
57
+ return True
58
+ except Exception as e:
59
+ logger.error(f"❌ Failed to load Wav2Vec2 models: {e}")
60
+ return False
61
+
62
+ def load_classifier_model():
63
+ global MODELS
64
+ # Model path resolution: Environment variable > Relative path
65
+ default_path = os.path.join(BASE_DIR, "models", "wav2vec2_model.h5")
66
+ model_path = os.environ.get(
67
+ "W2V_CLASSIFIER_PATH",
68
+ default_path
69
+ )
70
+ if not os.path.exists(model_path):
71
+ logger.error(f"❌ Model file not found: {model_path}")
72
+ return False
73
+ try:
74
+ model = load_model(model_path, compile=False)
75
+ MODELS["Wav2Vec2"] = model
76
+ logger.info("✅ Wav2Vec2 classifier loaded successfully")
77
+ return True
78
+ except Exception as e:
79
+ logger.error(f"❌ Failed to load classifier: {e}")
80
+ return False
81
+
82
+ def load_label_encoder():
83
+ global LABEL_ENCODER
84
+ # Encoder path resolution: Environment variable > Relative path
85
+ default_path = os.path.join(BASE_DIR, "models", "classes.npy")
86
+ encoder_path = os.environ.get(
87
+ "W2V_LABELS_PATH",
88
+ default_path
89
+ )
90
+ if os.path.exists(encoder_path):
91
+ try:
92
+ LABEL_ENCODER = np.load(encoder_path)
93
+ logger.info(f"✅ Label encoder loaded: {LABEL_ENCODER}")
94
+ return True
95
+ except Exception as e:
96
+ logger.warning(f"⚠️ Could not load label encoder: {e}")
97
+ else:
98
+ logger.info("ℹ️ No label encoder found, using default classes")
99
+ return False
100
+
101
+ @app.on_event("startup")
102
+ async def startup_event():
103
+ logger.info("🚀 Starting Wav2Vec2 Emotion Recognition API")
104
+ load_wav2vec_models()
105
+ load_classifier_model()
106
+ load_label_encoder()
107
+ logger.info("✅ API ready for predictions")
108
+
109
+ def convert_to_wav(input_path: str) -> str:
110
+ try:
111
+ output_path = input_path + "_conv.wav"
112
+ sound = AudioSegment.from_file(input_path)
113
+ sound = sound.set_frame_rate(16000).set_channels(1)
114
+ sound.export(output_path, format="wav")
115
+ return output_path
116
+ except Exception as e:
117
+ logger.error(f"❌ Conversion to wav failed: {e}")
118
+ return None
119
+
120
+ def extract_wav2vec_features(file_path: str) -> np.ndarray:
121
+ try:
122
+ waveform, sample_rate = torchaudio.load(file_path)
123
+ waveform = waveform.mean(dim=0)
124
+ if sample_rate != 16000:
125
+ resampler = torchaudio.transforms.Resample(sample_rate, 16000)
126
+ waveform = resampler(waveform)
127
+ inputs = WAV2VEC_PROCESSOR(waveform, sampling_rate=16000, return_tensors="pt", padding=True)
128
+ with torch.no_grad():
129
+ outputs = WAV2VEC_MODEL(inputs.input_values)
130
+ hidden_states = outputs.last_hidden_state.mean(dim=1).cpu().numpy()
131
+ return hidden_states.squeeze()
132
+ except Exception as e:
133
+ logger.error(f"❌ Wav2Vec2 feature extraction failed: {e}")
134
+ return None
135
+
136
+ def preprocess_for_wav2vec(features: np.ndarray) -> np.ndarray:
137
+ if features is None or len(features.shape) == 0:
138
+ return None
139
+ if len(features.shape) == 1:
140
+ features = features.reshape(1, -1)
141
+ return features
142
+
143
+ @app.get("/")
144
+ async def root():
145
+ return {
146
+ "message": "🎤 Wav2Vec2 Emotion Recognition API",
147
+ "status": "running",
148
+ "models_loaded": list(MODELS.keys()),
149
+ }
150
+
151
+ @app.post("/predict")
152
+ async def predict(file: UploadFile = File(...)):
153
+ if not file or not file.filename:
154
+ return {"error": "Dosya yüklenmedi"}
155
+
156
+ temp_path = os.path.join(BASE_DIR, f"temp_{uuid.uuid4().hex}_{file.filename}")
157
+ try:
158
+ with open(temp_path, "wb") as f:
159
+ f.write(await file.read())
160
+ except Exception as e:
161
+ return {"error": f"Dosya kaydedilemedi: {str(e)}"}
162
+
163
+ try:
164
+ wav_path = convert_to_wav(temp_path)
165
+ if not wav_path:
166
+ return {"error": "Ses dönüştürülemedi"}
167
+
168
+ features = extract_wav2vec_features(wav_path)
169
+ if features is None:
170
+ return {"error": "Özellik çıkarılamadı"}
171
+
172
+ x = preprocess_for_wav2vec(features)
173
+ if x is None:
174
+ return {"error": "Özellik işlenemedi"}
175
+
176
+ model = MODELS.get("Wav2Vec2")
177
+ if model is None:
178
+ return {"error": "Model yüklenmedi"}
179
+
180
+ prediction = model.predict(x, verbose=0)
181
+ pred_idx = int(np.argmax(prediction))
182
+ confidence = float(np.max(prediction))
183
+
184
+ if LABEL_ENCODER is not None and pred_idx < len(LABEL_ENCODER):
185
+ predicted_emotion = LABEL_ENCODER[pred_idx]
186
+ else:
187
+ return {"error": "Label encoder not loaded properly"}
188
+
189
+ prediction_tr = EN_TO_TR.get(predicted_emotion, predicted_emotion)
190
+ return {"prediction": predicted_emotion, "prediction_tr": prediction_tr, "confidence": confidence}
191
+ except Exception as e:
192
+ logger.error(f"Prediction error: {e}")
193
+ return {"error": "Tahmin sırasında hata oluştu"}
194
+ finally:
195
+ for path in [temp_path, temp_path + "_conv.wav"]:
196
+ if os.path.exists(path):
197
+ try:
198
+ os.remove(path)
199
+ except Exception:
200
+ pass
201
+
202
+ if __name__ == "__main__":
203
+ uvicorn.run("wav2vec_emotion_api:app", host="127.0.0.1", port=8001, reload=True, log_level="info")
204
+
205
+
206
+
207
+
backend/utils/feature_extractor.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import librosa
2
+ import numpy as np
3
+
4
+ def extract_features(file_path, num_mfcc=13, n_mels=40):
5
+ """
6
+ Ses dosyasından MFCC özniteliklerini çıkarır.
7
+
8
+ Args:
9
+ file_path (str): Ses dosyasının yolu.
10
+ num_mfcc (int): Çıkarılacak MFCC sayısı.
11
+ n_mels (int): Mel bankası sayısı.
12
+
13
+ Returns:
14
+ numpy.ndarray: Çıkarılan MFCC öznitelikleri.
15
+ Eğer dosya okuma hatası oluşursa None döner.
16
+ """
17
+ try:
18
+ # Ses dosyasını librosa ile yükle
19
+ audio, sr = librosa.load(file_path, sr=None)
20
+
21
+ # Log-Mel spektrogramını oluştur
22
+ S = librosa.feature.melspectrogram(y=audio, sr=sr, n_mels=n_mels)
23
+ log_S = librosa.power_to_db(S, ref=np.max)
24
+
25
+ # MFCC'leri log-mel spektrogramından çıkar
26
+ mfccs = librosa.feature.mfcc(S=log_S, sr=sr, n_mfcc=num_mfcc)
27
+
28
+ # Ortalama ve standart sapmasını alarak vektör haline getir
29
+ mfccs_mean = np.mean(mfccs.T, axis=0)
30
+ mfccs_std = np.std(mfccs.T, axis=0)
31
+
32
+ # Her iki vektörü birleştir
33
+ features = np.concatenate((mfccs_mean, mfccs_std))
34
+
35
+ except Exception as e:
36
+ print(f"Hata: {file_path} dosyası işlenirken bir sorun oluştu. Hata: {e}")
37
+ return None
38
+
39
+ return features
40
+
41
+ if __name__ == '__main__':
42
+ # Bu dosya tek başına çalıştırıldığında test etmek için
43
+ sample_file_path = "ornek_ses_dosyasi.wav"
44
+
45
+ # Varsayılan MFCC parametreleri ile öznitelikleri çıkar
46
+ extracted_features = extract_features(sample_file_path)
47
+
48
+ if extracted_features is not None:
49
+ print("Öznitelikler başarıyla çıkarıldı.")
50
+ print("Vektör boyutu:", extracted_features.shape)
51
+ # print("Öznitelikler:", extracted_features)
52
+ else:
53
+ print("Öznitelik çıkarma işlemi başarısız oldu.")
deploy-hf.ps1 ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Spaces - Quick Deploy Script
2
+ # Bu script, projeyi Hugging Face Spaces'e yayınlamak için gerekli git komutlarını içerir
3
+
4
+ Write-Host "🚀 SesleAI - Hugging Face Spaces Deployment" -ForegroundColor Cyan
5
+ Write-Host "==========================================`n" -ForegroundColor Cyan
6
+
7
+ # Kullanıcıdan bilgileri al
8
+ $username = Read-Host "Hugging Face kullanıcı adınız"
9
+ $spacename = Read-Host "Space adınız (örn: sesleai-customer-support)"
10
+
11
+ Write-Host "`n📋 Yapılandırma:" -ForegroundColor Yellow
12
+ Write-Host " Username: $username" -ForegroundColor White
13
+ Write-Host " Space: $spacename" -ForegroundColor White
14
+ Write-Host " URL: https://huggingface.co/spaces/$username/$spacename`n" -ForegroundColor White
15
+
16
+ $confirm = Read-Host "Devam etmek istiyor musunuz? (E/H)"
17
+ if ($confirm -ne "E" -and $confirm -ne "e") {
18
+ Write-Host "❌ İşlem iptal edildi." -ForegroundColor Red
19
+ exit
20
+ }
21
+
22
+ Write-Host "`n🔧 Git yapılandırması..." -ForegroundColor Yellow
23
+
24
+ # Mevcut remote'u kontrol et
25
+ $remoteExists = git remote | Select-String -Pattern "^hf$"
26
+
27
+ if ($remoteExists) {
28
+ Write-Host "⚠️ 'hf' remote zaten mevcut. Güncelleniyor..." -ForegroundColor Yellow
29
+ git remote remove hf
30
+ }
31
+
32
+ # Hugging Face remote ekle
33
+ $hfUrl = "https://huggingface.co/spaces/$username/$spacename"
34
+ git remote add hf $hfUrl
35
+ Write-Host "✅ Remote eklendi: $hfUrl" -ForegroundColor Green
36
+
37
+ Write-Host "`n📦 Dosyalar hazırlanıyor..." -ForegroundColor Yellow
38
+
39
+ # Git status kontrol
40
+ $status = git status --porcelain
41
+ if ($status) {
42
+ Write-Host "📝 Değişiklikler tespit edildi. Commit oluşturuluyor..." -ForegroundColor Yellow
43
+ git add .
44
+
45
+ $commitMsg = Read-Host "Commit mesajı (Enter = varsayılan)"
46
+ if ([string]::IsNullOrWhiteSpace($commitMsg)) {
47
+ $commitMsg = "Deploy to Hugging Face Spaces"
48
+ }
49
+
50
+ git commit -m $commitMsg
51
+ Write-Host "✅ Commit oluşturuldu" -ForegroundColor Green
52
+ } else {
53
+ Write-Host "✅ Tüm değişiklikler commit edilmiş" -ForegroundColor Green
54
+ }
55
+
56
+ Write-Host "`n🚀 Hugging Face Spaces'e yükleniyor..." -ForegroundColor Yellow
57
+ Write-Host "⚠️ Access Token girmeniz istenecek (şifre değil!)" -ForegroundColor Yellow
58
+ Write-Host "📌 Token almak için: https://huggingface.co/settings/tokens`n" -ForegroundColor Cyan
59
+
60
+ # Push et
61
+ $branch = git rev-parse --abbrev-ref HEAD
62
+ git push hf ${branch}:main
63
+
64
+ if ($LASTEXITCODE -eq 0) {
65
+ Write-Host "`n✅ Başarıyla yüklendi!" -ForegroundColor Green
66
+ Write-Host "`n🌐 Space URL: https://huggingface.co/spaces/$username/$spacename" -ForegroundColor Cyan
67
+ Write-Host "⏱️ Build süreci 10-15 dakika sürebilir" -ForegroundColor Yellow
68
+ Write-Host "📊 Build durumunu yukarıdaki URL'den takip edebilirsiniz`n" -ForegroundColor Yellow
69
+ } else {
70
+ Write-Host "`n❌ Yükleme başarısız oldu!" -ForegroundColor Red
71
+ Write-Host "Lütfen hata mesajını kontrol edin ve DEPLOYMENT.md dosyasına bakın.`n" -ForegroundColor Yellow
72
+ }
deploy.bat ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ REM SesleAI - Hugging Face Spaces Deployment Script
3
+ REM Bu script hf-space klasorunu hazirlar
4
+
5
+ echo ==========================================
6
+ echo SesleAI - HF Spaces Deployment
7
+ echo ==========================================
8
+
9
+ set PROJECT_ROOT=%~dp0..
10
+ set HF_SPACE=%PROJECT_ROOT%\hf-space
11
+
12
+ echo.
13
+ echo [1/4] Frontend'i kopyalaniyor...
14
+ xcopy "%PROJECT_ROOT%\sesleAI Proje Web Sitesi\frontend" "%HF_SPACE%\frontend\" /E /Y /I
15
+ if errorlevel 1 goto :error
16
+
17
+ echo.
18
+ echo [2/4] Backend API kopyalaniyor...
19
+ xcopy "%PROJECT_ROOT%\sesleAI Proje Web Sitesi\backend" "%HF_SPACE%\backend\" /E /Y /I
20
+ if errorlevel 1 goto :error
21
+
22
+ echo.
23
+ echo [3/4] Duygu API kopyalaniyor...
24
+ xcopy "%PROJECT_ROOT%\Duygu Dogrulama\apibackend_w2v" "%HF_SPACE%\emotion_api\" /E /Y /I
25
+ if errorlevel 1 goto :error
26
+
27
+ echo.
28
+ echo [4/4] Model dosyalari kontrol ediliyor...
29
+ if exist "%HF_SPACE%\backend\api\speakers_db.json" (
30
+ echo speakers_db.json bulundu
31
+ )
32
+ if exist "%HF_SPACE%\emotion_api\emotion_model_w2v" (
33
+ echo emotion_model_w2v klasoru bulundu
34
+ )
35
+
36
+ echo.
37
+ echo ==========================================
38
+ echo Tamamlandi!
39
+ echo ==========================================
40
+ echo.
41
+ echo Sonraki adimlar:
42
+ echo 1. https://huggingface.co/new-space adresine git
43
+ echo 2. Space adı: turkcell-proje
44
+ echo 3. SDK: Docker
45
+ echo 4. Visibility: Private (linki olanlar erisebilir)
46
+ echo 5. hf-space klasorundeki tum dosyalari yukle
47
+ echo.
48
+ echo VEYA git ile:
49
+ echo git clone https://huggingface.co/spaces/YOUR_USERNAME/turkcell-proje
50
+ echo cd turkcell-proje
51
+ echo copy hf-space\* .
52
+ echo git add . && git commit -m "Initial deploy" && git push
53
+ echo.
54
+ pause
55
+ goto :end
56
+
57
+ :error
58
+ echo.
59
+ echo HATA: Bir sorun olustu!
60
+ pause
61
+
62
+ :end
emotion_api/README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wav2Vec2 Emotion Recognition Backend
2
+
3
+ FastAPI tabanlı duygu analizi backend servisi - Wav2Vec2 modeli ile.
4
+
5
+ ## Kurulum
6
+
7
+ ```bash
8
+ cd apibackend_w2v
9
+ pip install -r requirements.txt
10
+ ```
11
+
12
+ ## Model Dosyaları
13
+
14
+ Aşağıdaki dosyaların `modeller/` klasöründe bulunması gerekir:
15
+ - `Bab2Vec.h5` - Eğitilmiş Wav2Vec2 sınıflandırıcı modeli
16
+ - `classes.npy` - Sınıf etiketleri (opsiyonel)
17
+
18
+ ## Çalıştırma
19
+
20
+ ```bash
21
+ python main_w2v.py
22
+ ```
23
+
24
+ API http://localhost:8001 adresinde çalışacak.
25
+
26
+ ## Endpoints
27
+
28
+ - `GET /` - API bilgileri
29
+ - `GET /health` - Sağlık kontrolü
30
+ - `POST /predict` - Duygu analizi
31
+
32
+ ## Özellikler
33
+
34
+ - Wav2Vec2 özellik çıkarımı
35
+ - 16kHz ses işleme
36
+ - 7 sınıf duygu tanıma
37
+ - JSON hata yönetimi
38
+ - CORS desteği
emotion_api/main_w2v.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydub import AudioSegment
4
+ import uvicorn
5
+ import torch
6
+ import torchaudio
7
+ import numpy as np
8
+ from tensorflow.keras.models import load_model
9
+ import os
10
+ import logging
11
+ import uuid
12
+ from transformers import Wav2Vec2Processor, Wav2Vec2Model
13
+
14
+ # ==========================
15
+ # Logging
16
+ # ==========================
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # ==========================
21
+ # FastAPI App
22
+ # ==========================
23
+ app = FastAPI(
24
+ title="🎤 Wav2Vec2 Emotion Recognition API",
25
+ description="Ses tabanlı duygu tanıma API'si - Wav2Vec2 modeli ile eğitilmiş",
26
+ version="1.0.0"
27
+ )
28
+
29
+ # CORS
30
+ app.add_middleware(
31
+ CORSMiddleware,
32
+ allow_origins=["*"],
33
+ allow_credentials=True,
34
+ allow_methods=["*"],
35
+ allow_headers=["*"],
36
+ )
37
+
38
+ # ==========================
39
+ # Global Variables
40
+ # ==========================
41
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
42
+ MODELS = {}
43
+ LABEL_ENCODER = None
44
+ WAV2VEC_PROCESSOR = None
45
+ WAV2VEC_MODEL = None
46
+
47
+ # Turkish-English emotion mapping
48
+ EN_TO_TR = {
49
+ "neutral": "Nötr",
50
+ "calm": "Sakin",
51
+ "happy": "Mutlu",
52
+ "sad": "Üzgün",
53
+ "angry": "Kızgın",
54
+ "fearful": "Endişeli",
55
+ "disgust": "Hoşnutsuz",
56
+ "surprised": "Şaşkın"
57
+ }
58
+
59
+ # ==========================
60
+ # Model Loading
61
+ # ==========================
62
+ def load_wav2vec_models():
63
+ global WAV2VEC_PROCESSOR, WAV2VEC_MODEL
64
+ try:
65
+ WAV2VEC_PROCESSOR = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base")
66
+ WAV2VEC_MODEL = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base")
67
+ WAV2VEC_MODEL.eval()
68
+ logger.info("✅ Wav2Vec2 models loaded successfully")
69
+ return True
70
+ except Exception as e:
71
+ logger.error(f"❌ Failed to load Wav2Vec2 models: {e}")
72
+ return False
73
+
74
+ def load_classifier_model():
75
+ global MODELS
76
+ # Model yolunu belirle: Önce env var, yoksa BASE_DIR/models/...
77
+ default_path = os.path.join(BASE_DIR, "models", "wav2vec2_model.h5")
78
+ model_path = os.environ.get("W2V_CLASSIFIER_PATH", default_path)
79
+
80
+ if not os.path.exists(model_path):
81
+ logger.error(f"❌ Model file not found: {model_path}")
82
+ return False
83
+ try:
84
+ model = load_model(model_path, compile=False)
85
+ MODELS["Wav2Vec2"] = model
86
+ logger.info("✅ Wav2Vec2 classifier loaded successfully")
87
+ return True
88
+ except Exception as e:
89
+ logger.error(f"❌ Failed to load classifier: {e}")
90
+ return False
91
+
92
+
93
+ def load_label_encoder():
94
+ global LABEL_ENCODER
95
+ # Encoder yolunu belirle: Önce env var, yoksa BASE_DIR/models/...
96
+ default_path = os.path.join(BASE_DIR, "models", "classes.npy")
97
+ encoder_path = os.environ.get("W2V_LABELS_PATH", default_path)
98
+
99
+ if os.path.exists(encoder_path):
100
+ try:
101
+ LABEL_ENCODER = np.load(encoder_path)
102
+ logger.info(f"✅ Label encoder loaded: {LABEL_ENCODER}")
103
+ return True
104
+ except Exception as e:
105
+ logger.warning(f"⚠️ Could not load label encoder: {e}")
106
+ else:
107
+ logger.info("ℹ️ No label encoder found, using default classes")
108
+ return False
109
+
110
+ @app.on_event("startup")
111
+ async def startup_event():
112
+ logger.info("🚀 Starting Wav2Vec2 Emotion Recognition API")
113
+ load_wav2vec_models()
114
+ load_classifier_model()
115
+ load_label_encoder()
116
+ logger.info("✅ API ready for predictions")
117
+
118
+ # ==========================
119
+ # Helpers
120
+ # ==========================
121
+ def convert_to_wav(input_path: str) -> str:
122
+ """Convert any input (e.g. webm/opus) to WAV 16kHz mono"""
123
+ try:
124
+ output_path = input_path + "_conv.wav"
125
+ sound = AudioSegment.from_file(input_path)
126
+ sound = sound.set_frame_rate(16000).set_channels(1)
127
+ sound.export(output_path, format="wav")
128
+ return output_path
129
+ except Exception as e:
130
+ logger.error(f"❌ Conversion to wav failed: {e}")
131
+ return None
132
+
133
+ def extract_wav2vec_features(file_path: str) -> np.ndarray:
134
+ try:
135
+ waveform, sample_rate = torchaudio.load(file_path)
136
+ waveform = waveform.mean(dim=0) # mono
137
+ if sample_rate != 16000:
138
+ resampler = torchaudio.transforms.Resample(sample_rate, 16000)
139
+ waveform = resampler(waveform)
140
+ inputs = WAV2VEC_PROCESSOR(waveform, sampling_rate=16000, return_tensors="pt", padding=True)
141
+ with torch.no_grad():
142
+ outputs = WAV2VEC_MODEL(inputs.input_values)
143
+ hidden_states = outputs.last_hidden_state.mean(dim=1).cpu().numpy()
144
+ return hidden_states.squeeze()
145
+ except Exception as e:
146
+ logger.error(f"❌ Wav2Vec2 feature extraction failed: {e}")
147
+ return None
148
+
149
+ def preprocess_for_wav2vec(features: np.ndarray) -> np.ndarray:
150
+ if features is None or len(features.shape) == 0:
151
+ return None
152
+ if len(features.shape) == 1:
153
+ features = features.reshape(1, -1)
154
+ return features
155
+
156
+ def predict_emotion_segmented(audio_path: str, segment_length: int = 5000):
157
+ """
158
+ Ses dosyasını belirtilen uzunluktaki segmentlere ayırır (varsayılan 5 saniye).
159
+ Her segmenti geçici bir dosya olarak kaydeder.
160
+ predict_emotion() fonksiyonunu kullanarak her segment için duygu tahmini yapar.
161
+ Sonuçları hem sırayla listeler hem de majority voting yöntemiyle genel duyguyu döndürür.
162
+
163
+ Args:
164
+ audio_path (str): Ses dosyası yolu
165
+ segment_length (int): Segment uzunluğu (milisaniye, varsayılan 5000ms = 5sn)
166
+
167
+ Returns:
168
+ tuple: (results, final_emotion)
169
+ - results: Her segmentin duygusu listesi
170
+ - final_emotion: Majority voting sonucu genel duygu
171
+ """
172
+ try:
173
+ # Ses dosyasını yükle
174
+ audio = AudioSegment.from_file(audio_path)
175
+ total_duration = len(audio) # milisaniye
176
+
177
+ # logger.info(f"🎵 Ses dosyası yüklendi: {total_duration}ms ({total_duration/1000:.1f}sn)")
178
+
179
+ results = []
180
+ emotion_counts = {}
181
+ temp_files = []
182
+
183
+ # Segmentlere ayır
184
+ for start_time in range(0, total_duration, segment_length):
185
+ end_time = min(start_time + segment_length, total_duration)
186
+ segment = audio[start_time:end_time]
187
+
188
+ # Geçici dosya oluştur
189
+ temp_file = f"temp_segment_{start_time}_{uuid.uuid4().hex}.wav"
190
+ temp_path = os.path.join(BASE_DIR, temp_file)
191
+ temp_files.append(temp_path)
192
+
193
+ # Segmenti kaydet
194
+ segment.export(temp_path, format="wav")
195
+
196
+ # Duygu tahmini yap - doğrudan mevcut mantığı kullan
197
+ try:
198
+ # Convert to wav if needed
199
+ wav_path = convert_to_wav(temp_path)
200
+ if not wav_path:
201
+ continue
202
+
203
+ # Extract features
204
+ features = extract_wav2vec_features(wav_path)
205
+ if features is None:
206
+ continue
207
+
208
+ x = preprocess_for_wav2vec(features)
209
+ if x is None:
210
+ continue
211
+
212
+ model = MODELS.get("Wav2Vec2")
213
+ if model is None:
214
+ continue
215
+
216
+ prediction = model.predict(x, verbose=0)
217
+ pred_idx = int(np.argmax(prediction))
218
+ confidence = float(np.max(prediction))
219
+
220
+ if LABEL_ENCODER is not None and pred_idx < len(LABEL_ENCODER):
221
+ predicted_emotion = LABEL_ENCODER[pred_idx]
222
+ prediction_tr = EN_TO_TR.get(predicted_emotion, predicted_emotion)
223
+ else:
224
+ continue
225
+
226
+ prediction_result = {
227
+ "prediction": predicted_emotion,
228
+ "prediction_tr": prediction_tr,
229
+ "confidence": confidence
230
+ }
231
+ except Exception as e:
232
+ logger.warning(f"Segment {start_time}-{end_time}ms için hata: {e}")
233
+ continue
234
+
235
+ if "error" in prediction_result:
236
+ logger.warning(f"⚠️ Segment {start_time}-{end_time}ms için hata: {prediction_result['error']}")
237
+ continue
238
+
239
+ # Sonucu kaydet
240
+ emotion_tr = prediction_result.get("prediction_tr", "Bilinmiyor")
241
+ confidence = prediction_result.get("confidence", 0.0)
242
+
243
+ results.append({
244
+ "start_time": start_time,
245
+ "end_time": end_time,
246
+ "emotion": emotion_tr,
247
+ "confidence": confidence
248
+ })
249
+
250
+ # Majority voting için say
251
+ if emotion_tr in emotion_counts:
252
+ emotion_counts[emotion_tr] += 1
253
+ else:
254
+ emotion_counts[emotion_tr] = 1
255
+
256
+ # Sonucu yazdır (sadece gerekirse)
257
+ # start_sec = start_time / 1000
258
+ # end_sec = end_time / 1000
259
+ # print(f"{start_sec:.0f}-{end_sec:.0f} sn: {emotion_tr} (güven: {confidence:.2f})")
260
+
261
+ # Majority voting ile final duygu
262
+ if emotion_counts:
263
+ final_emotion = max(emotion_counts, key=emotion_counts.get)
264
+ else:
265
+ final_emotion = "Bilinmiyor"
266
+
267
+ # logger.info(f"📊 Segment analizi tamamlandı. Final duygu: {final_emotion}")
268
+ # logger.info(f"📈 Duygu dağılımı: {emotion_counts}")
269
+
270
+ return results, final_emotion
271
+
272
+ except Exception as e:
273
+ logger.error(f"❌ Segment analizi hatası: {e}")
274
+ return [], "Hata"
275
+ finally:
276
+ # Geçici dosyaları temizle
277
+ for temp_file in temp_files:
278
+ if os.path.exists(temp_file):
279
+ try:
280
+ os.remove(temp_file)
281
+ except Exception:
282
+ pass
283
+
284
+ # ==========================
285
+ # Endpoints
286
+ # ==========================
287
+ @app.get("/")
288
+ async def root():
289
+ return {
290
+ "message": "🎤 Wav2Vec2 Emotion Recognition API",
291
+ "status": "running",
292
+ "models_loaded": list(MODELS.keys())
293
+ }
294
+
295
+ @app.post("/predict")
296
+ async def predict(file: UploadFile = File(...)):
297
+ if not file or not file.filename:
298
+ return {"error": "Dosya yüklenmedi"}
299
+
300
+ temp_path = os.path.join(BASE_DIR, f"temp_{uuid.uuid4().hex}_{file.filename}")
301
+ try:
302
+ with open(temp_path, "wb") as f:
303
+ f.write(await file.read())
304
+ except Exception as e:
305
+ return {"error": f"Dosya kaydedilemedi: {str(e)}"}
306
+
307
+ try:
308
+ # 🔹 Zorunlu dönüşüm
309
+ wav_path = convert_to_wav(temp_path)
310
+ if not wav_path:
311
+ return {"error": "Ses dönüştürülemedi"}
312
+
313
+ # Özellik çıkar
314
+ features = extract_wav2vec_features(wav_path)
315
+ if features is None:
316
+ return {"error": "Özellik çıkarılamadı"}
317
+
318
+ x = preprocess_for_wav2vec(features)
319
+ if x is None:
320
+ return {"error": "Özellik işlenemedi"}
321
+
322
+ model = MODELS.get("Wav2Vec2")
323
+ if model is None:
324
+ return {"error": "Model yüklenmedi"}
325
+
326
+ prediction = model.predict(x, verbose=0)
327
+ pred_idx = int(np.argmax(prediction))
328
+ confidence = float(np.max(prediction))
329
+
330
+ if LABEL_ENCODER is not None and pred_idx < len(LABEL_ENCODER):
331
+ predicted_emotion = LABEL_ENCODER[pred_idx]
332
+ else:
333
+ return {"error": "Label encoder not loaded properly"}
334
+
335
+ # Get Turkish translation
336
+ prediction_tr = EN_TO_TR.get(predicted_emotion, predicted_emotion)
337
+
338
+ return {
339
+ "prediction": predicted_emotion,
340
+ "prediction_tr": prediction_tr,
341
+ "confidence": confidence
342
+ }
343
+
344
+
345
+
346
+ except Exception as e:
347
+ logger.error(f"Prediction error: {e}")
348
+ return {"error": "Tahmin sırasında hata oluştu"}
349
+ finally:
350
+ for path in [temp_path, temp_path + "_conv.wav"]:
351
+ if os.path.exists(path):
352
+ try:
353
+ os.remove(path)
354
+ except Exception:
355
+ pass
356
+
357
+ # ==========================
358
+ # Main
359
+ # ==========================
360
+ if __name__ == "__main__":
361
+ uvicorn.run("main_w2v:app", host="127.0.0.1", port=8001, reload=True, log_level="info")
362
+
emotion_api/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn==0.24.0
3
+ python-multipart==0.0.6
4
+ pydub==0.25.1
5
+ torch==2.1.0
6
+ torchaudio==2.1.0
7
+ transformers==4.35.0
8
+ tensorflow==2.15.0
9
+ numpy==1.24.3
10
+ scikit-learn==1.3.2
emotion_api/uvicorn ADDED
File without changes
frontend/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
frontend/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
9
+
10
+ ## Expanding the ESLint configuration
11
+
12
+ If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
frontend/eslint.config.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import { defineConfig, globalIgnores } from 'eslint/config'
6
+
7
+ export default defineConfig([
8
+ globalIgnores(['dist']),
9
+ {
10
+ files: ['**/*.{js,jsx}'],
11
+ extends: [
12
+ js.configs.recommended,
13
+ reactHooks.configs['recommended-latest'],
14
+ reactRefresh.configs.vite,
15
+ ],
16
+ languageOptions: {
17
+ ecmaVersion: 2020,
18
+ globals: globals.browser,
19
+ parserOptions: {
20
+ ecmaVersion: 'latest',
21
+ ecmaFeatures: { jsx: true },
22
+ sourceType: 'module',
23
+ },
24
+ },
25
+ rules: {
26
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
27
+ },
28
+ },
29
+ ])
frontend/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/DaualMindIcon.png" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>SesleAI</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.jsx"></script>
12
+ </body>
13
+ </html>
frontend/package.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "start": "vite",
8
+ "dev": "vite",
9
+ "build": "vite build",
10
+ "lint": "eslint .",
11
+ "preview": "vite preview"
12
+ },
13
+ "dependencies": {
14
+ "@fortawesome/free-solid-svg-icons": "^7.0.1",
15
+ "@fortawesome/react-fontawesome": "^3.0.2",
16
+ "audiobuffer-to-wav": "^1.0.0",
17
+ "react": "^19.1.1",
18
+ "react-dom": "^19.1.1",
19
+ "react-router-dom": "^7.8.2"
20
+ },
21
+ "devDependencies": {
22
+ "@eslint/js": "^9.33.0",
23
+ "@types/react": "^19.1.10",
24
+ "@types/react-dom": "^19.1.7",
25
+ "@vitejs/plugin-react": "^5.0.0",
26
+ "eslint": "^9.33.0",
27
+ "eslint-plugin-react-hooks": "^5.2.0",
28
+ "eslint-plugin-react-refresh": "^0.4.20",
29
+ "globals": "^16.3.0",
30
+ "vite": "^7.1.2"
31
+ }
32
+ }
frontend/public/DaualMindIcon.png ADDED
frontend/public/vite.svg ADDED
frontend/src/App.css ADDED
@@ -0,0 +1,1287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;700;800&display=swap');
2
+
3
+ /* ================================
4
+ LIGHT MODE (Default - Beyaz)
5
+ ================================ */
6
+ :root {
7
+ /* Primary Colors */
8
+ --turkcell-yellow: #ffc107;
9
+ --turkcell-yellow-glow: #ffd54f;
10
+ --turkcell-blue: #1a237e;
11
+ --turkcell-blue-dark: #0a0e35;
12
+ --turkcell-blue-light: #283593;
13
+
14
+ /* Light Mode Theme Colors */
15
+ --bg-primary: #f8fafc;
16
+ --bg-secondary: #ffffff;
17
+ --bg-gradient-1: #e3f2fd;
18
+ --bg-gradient-2: #fff8e1;
19
+
20
+ --glass-bg: rgba(255, 255, 255, 0.75);
21
+ --glass-border: rgba(26, 35, 126, 0.15);
22
+ --glass-blur: blur(20px);
23
+
24
+ --text-primary: #1a237e;
25
+ --text-secondary: #546e7a;
26
+ --text-muted: #90a4ae;
27
+
28
+ --card-shadow: 0 8px 32px rgba(26, 35, 126, 0.12);
29
+ --card-shadow-hover: 0 16px 48px rgba(26, 35, 126, 0.18);
30
+
31
+ --success-color: #4caf50;
32
+ --success-bg: rgba(76, 175, 80, 0.1);
33
+ --error-color: #f44336;
34
+ --error-bg: rgba(244, 67, 54, 0.1);
35
+
36
+ --button-text: #0b144a;
37
+ --input-bg: rgba(26, 35, 126, 0.05);
38
+ --input-border: rgba(26, 35, 126, 0.2);
39
+ --input-focus-shadow: rgba(255, 193, 7, 0.25);
40
+
41
+ /* Floating orbs for light mode */
42
+ --orb-1-color: rgba(26, 35, 126, 0.08);
43
+ --orb-2-color: rgba(255, 193, 7, 0.12);
44
+ --orb-1-opacity: 0.6;
45
+ --orb-2-opacity: 0.4;
46
+
47
+ /* Animation & Transition */
48
+ --transition-fast: 0.2s ease;
49
+ --transition-medium: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
50
+ --transition-slow: 0.5s cubic-bezier(0.4, 0, 0.2, 1);
51
+ }
52
+
53
+ /* ================================
54
+ DARK MODE (Mevcut Lacivert Tasarım)
55
+ ================================ */
56
+ [data-theme="dark"] {
57
+ --bg-primary: #0a0e35;
58
+ --bg-secondary: #1a237e;
59
+ --bg-gradient-1: #1a237e;
60
+ --bg-gradient-2: #ffc107;
61
+
62
+ --glass-bg: rgba(26, 35, 126, 0.4);
63
+ --glass-border: rgba(255, 193, 7, 0.3);
64
+
65
+ --text-primary: #ffffff;
66
+ --text-secondary: #e0e6ed;
67
+ --text-muted: #90a4ae;
68
+
69
+ --card-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
70
+ --card-shadow-hover: 0 16px 48px rgba(0, 0, 0, 0.7);
71
+
72
+ --success-bg: rgba(76, 175, 80, 0.2);
73
+ --error-bg: rgba(244, 67, 54, 0.2);
74
+
75
+ --button-text: #0b144a;
76
+ --input-bg: rgba(255, 255, 255, 0.05);
77
+ --input-border: rgba(255, 255, 255, 0.2);
78
+ --input-focus-shadow: rgba(255, 193, 7, 0.3);
79
+
80
+ /* Floating orbs for dark mode */
81
+ --orb-1-color: var(--turkcell-blue);
82
+ --orb-2-color: var(--turkcell-yellow);
83
+ --orb-1-opacity: 0.6;
84
+ --orb-2-opacity: 0.2;
85
+ }
86
+
87
+ /* ================================
88
+ Global Transition for Theme Change
89
+ ================================ */
90
+ *,
91
+ *::before,
92
+ *::after {
93
+ transition: background-color var(--transition-medium),
94
+ border-color var(--transition-medium),
95
+ box-shadow var(--transition-medium),
96
+ color var(--transition-fast);
97
+ }
98
+
99
+ body {
100
+ margin: 0;
101
+ font-family: 'Outfit', sans-serif;
102
+ background: var(--bg-primary);
103
+ color: var(--text-primary);
104
+ display: flex;
105
+ justify-content: center;
106
+ align-items: center;
107
+ min-height: 100vh;
108
+ overflow-x: hidden;
109
+ transition: background var(--transition-slow);
110
+ }
111
+
112
+ /* Hareketli Arka Plan - Tema Uyumlu */
113
+ body::before,
114
+ body::after {
115
+ content: '';
116
+ position: fixed;
117
+ width: 600px;
118
+ height: 600px;
119
+ border-radius: 50%;
120
+ filter: blur(120px);
121
+ z-index: -1;
122
+ animation: float 12s infinite ease-in-out;
123
+ transition: background var(--transition-slow), opacity var(--transition-slow);
124
+ }
125
+
126
+ body::before {
127
+ background: var(--orb-1-color);
128
+ top: -150px;
129
+ left: -150px;
130
+ opacity: var(--orb-1-opacity);
131
+ }
132
+
133
+ body::after {
134
+ background: var(--orb-2-color);
135
+ bottom: -150px;
136
+ right: -150px;
137
+ opacity: var(--orb-2-opacity);
138
+ animation-delay: -6s;
139
+ }
140
+
141
+ @keyframes float {
142
+
143
+ 0%,
144
+ 100% {
145
+ transform: translate(0, 0);
146
+ }
147
+
148
+ 50% {
149
+ transform: translate(60px, 40px);
150
+ }
151
+ }
152
+
153
+ .App {
154
+ text-align: center;
155
+ padding: 40px 20px;
156
+ min-height: 100vh;
157
+ display: flex;
158
+ flex-direction: column;
159
+ align-items: center;
160
+ justify-content: center;
161
+ width: 100%;
162
+ box-sizing: border-box;
163
+ }
164
+
165
+ /* Glassmorphism Container */
166
+ .container {
167
+ position: relative;
168
+ max-width: 900px;
169
+ width: 100%;
170
+ padding: 48px;
171
+ border-radius: 24px;
172
+ color: var(--text-primary);
173
+ background: var(--glass-bg);
174
+ backdrop-filter: var(--glass-blur);
175
+ -webkit-backdrop-filter: var(--glass-blur);
176
+ border: 1px solid var(--glass-border);
177
+ box-shadow: var(--card-shadow);
178
+ z-index: 10;
179
+ overflow: visible;
180
+ transition: transform var(--transition-medium), box-shadow var(--transition-medium);
181
+ animation: fadeInUp 0.6s ease-out;
182
+ }
183
+
184
+ .container:hover {
185
+ box-shadow: var(--card-shadow-hover);
186
+ }
187
+
188
+ /* Entrance Animations */
189
+ @keyframes fadeInUp {
190
+ from {
191
+ opacity: 0;
192
+ transform: translateY(30px);
193
+ }
194
+
195
+ to {
196
+ opacity: 1;
197
+ transform: translateY(0);
198
+ }
199
+ }
200
+
201
+ @keyframes slideInLeft {
202
+ from {
203
+ opacity: 0;
204
+ transform: translateX(-50px);
205
+ }
206
+
207
+ to {
208
+ opacity: 1;
209
+ transform: translateX(0);
210
+ }
211
+ }
212
+
213
+ @keyframes slideInRight {
214
+ from {
215
+ opacity: 0;
216
+ transform: translateX(50px);
217
+ }
218
+
219
+ to {
220
+ opacity: 1;
221
+ transform: translateX(0);
222
+ }
223
+ }
224
+
225
+ @keyframes scaleIn {
226
+ from {
227
+ opacity: 0;
228
+ transform: scale(0.8);
229
+ }
230
+
231
+ to {
232
+ opacity: 1;
233
+ transform: scale(1);
234
+ }
235
+ }
236
+
237
+ @keyframes bounceIn {
238
+ 0% {
239
+ opacity: 0;
240
+ transform: scale(0.3);
241
+ }
242
+
243
+ 50% {
244
+ transform: scale(1.05);
245
+ }
246
+
247
+ 70% {
248
+ transform: scale(0.9);
249
+ }
250
+
251
+ 100% {
252
+ opacity: 1;
253
+ transform: scale(1);
254
+ }
255
+ }
256
+
257
+ /* Typography */
258
+ h1 {
259
+ font-size: 2.8em;
260
+ font-weight: 800;
261
+ background: linear-gradient(135deg, var(--text-primary) 30%, var(--turkcell-yellow) 100%);
262
+ background-clip: text;
263
+ -webkit-background-clip: text;
264
+ -webkit-text-fill-color: transparent;
265
+ margin-bottom: 20px;
266
+ text-shadow: 0 4px 20px rgba(255, 193, 7, 0.3);
267
+ animation: slideInLeft 0.6s ease-out 0.1s both;
268
+ }
269
+
270
+ .subtitle {
271
+ font-size: 1.1em;
272
+ color: var(--text-secondary);
273
+ margin-bottom: 32px;
274
+ font-weight: 300;
275
+ letter-spacing: 0.5px;
276
+ animation: slideInLeft 0.6s ease-out 0.2s both;
277
+ }
278
+
279
+ /* Inputs & Selects */
280
+ .speaker-input,
281
+ .role-select,
282
+ .phone-input,
283
+ .form-group input,
284
+ .form-group select {
285
+ width: 100%;
286
+ padding: 16px;
287
+ border-radius: 12px;
288
+ border: 1px solid var(--input-border);
289
+ background: var(--input-bg);
290
+ color: var(--text-primary);
291
+ font-family: inherit;
292
+ font-size: 1em;
293
+ transition: all var(--transition-medium);
294
+ box-sizing: border-box;
295
+ }
296
+
297
+ .speaker-input:focus,
298
+ .role-select:focus,
299
+ .phone-input:focus,
300
+ .form-group input:focus {
301
+ outline: none;
302
+ border-color: var(--turkcell-yellow);
303
+ background: var(--glass-bg);
304
+ box-shadow: 0 0 0 4px var(--input-focus-shadow);
305
+ transform: translateY(-2px);
306
+ }
307
+
308
+ .speaker-input::placeholder {
309
+ color: var(--text-muted);
310
+ }
311
+
312
+ /* Buttons */
313
+ .controls {
314
+ display: flex;
315
+ flex-wrap: wrap;
316
+ justify-content: center;
317
+ gap: 20px;
318
+ margin-top: 32px;
319
+ }
320
+
321
+ .button {
322
+ flex: 1 1 200px;
323
+ padding: 16px 24px;
324
+ font-size: 1.1em;
325
+ font-weight: 700;
326
+ cursor: pointer;
327
+ border-radius: 14px;
328
+ border: none;
329
+ transition: all var(--transition-medium);
330
+ color: var(--button-text);
331
+ background: linear-gradient(180deg, var(--turkcell-yellow-glow), var(--turkcell-yellow));
332
+ box-shadow: 0 4px 20px rgba(255, 193, 7, 0.4);
333
+ text-transform: uppercase;
334
+ letter-spacing: 0.5px;
335
+ position: relative;
336
+ overflow: hidden;
337
+ }
338
+
339
+ .button::after {
340
+ content: '';
341
+ position: absolute;
342
+ top: 0;
343
+ left: 0;
344
+ width: 100%;
345
+ height: 100%;
346
+ background: linear-gradient(rgba(255, 255, 255, 0.4), transparent);
347
+ opacity: 0;
348
+ transition: opacity 0.3s ease;
349
+ }
350
+
351
+ .button:hover {
352
+ transform: translateY(-3px) scale(1.02);
353
+ box-shadow: 0 8px 30px rgba(255, 193, 7, 0.6);
354
+ }
355
+
356
+ .button:hover::after {
357
+ opacity: 1;
358
+ }
359
+
360
+ .stop-button {
361
+ background: linear-gradient(135deg, var(--error-color), #b71c1c);
362
+ color: white;
363
+ box-shadow: 0 4px 15px rgba(244, 67, 54, 0.4);
364
+ }
365
+
366
+
367
+
368
+ /* Lacivert Buton (Emotion vb için) */
369
+ .emotion-button {
370
+ background: linear-gradient(135deg, var(--turkcell-blue-light), var(--turkcell-blue));
371
+ color: var(--turkcell-yellow);
372
+ border: 1px solid var(--turkcell-yellow);
373
+ box-shadow: 0 4px 15px rgba(26, 35, 126, 0.5);
374
+ }
375
+
376
+ .button.recording {
377
+ animation: pulse-glow 2s infinite;
378
+ }
379
+
380
+ @keyframes pulse-glow {
381
+ 0% {
382
+ box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7);
383
+ }
384
+
385
+ 70% {
386
+ box-shadow: 0 0 0 20px rgba(255, 193, 7, 0);
387
+ }
388
+
389
+ 100% {
390
+ box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
391
+ }
392
+ }
393
+
394
+ /* Results */
395
+ .result {
396
+ margin-top: 30px;
397
+ padding: 20px;
398
+ border-radius: 16px;
399
+ background: var(--glass-bg);
400
+ border: 1px solid var(--glass-border);
401
+ font-weight: 600;
402
+ font-size: 1.1em;
403
+ animation: slideUp 0.5s ease-out;
404
+ backdrop-filter: blur(10px);
405
+ }
406
+
407
+ .result-success,
408
+ .result-SUCCESS {
409
+ background: var(--success-bg);
410
+ border-color: rgba(76, 175, 80, 0.5);
411
+ color: var(--success-color);
412
+ }
413
+
414
+ .result-error,
415
+ .result-FAILURE {
416
+ background: var(--error-bg);
417
+ border-color: rgba(244, 67, 54, 0.5);
418
+ color: var(--error-color);
419
+ }
420
+
421
+ @keyframes slideUp {
422
+ from {
423
+ opacity: 0;
424
+ transform: translateY(20px);
425
+ }
426
+
427
+ to {
428
+ opacity: 1;
429
+ transform: translateY(0);
430
+ }
431
+ }
432
+
433
+ /* Logo */
434
+ .logo {
435
+ width: 150px;
436
+ height: 150px;
437
+ object-fit: cover;
438
+ border-radius: 50%;
439
+ box-shadow: 0 0 40px rgba(255, 193, 7, 0.3);
440
+ margin-bottom: 24px;
441
+ border: 4px solid var(--turkcell-yellow);
442
+ background: white;
443
+ padding: 5px;
444
+ transition: transform var(--transition-slow), box-shadow var(--transition-slow);
445
+ animation: bounceIn 0.8s ease-out;
446
+ }
447
+
448
+ .logo:hover {
449
+ transform: scale(1.08) rotate(5deg);
450
+ box-shadow: 0 0 60px rgba(255, 193, 7, 0.6);
451
+ }
452
+
453
+ /* User Info Badge */
454
+ .user-info {
455
+ position: absolute;
456
+ top: 20px;
457
+ left: 20px;
458
+ background: var(--glass-bg);
459
+ backdrop-filter: blur(15px);
460
+ -webkit-backdrop-filter: blur(15px);
461
+ padding: 12px 20px;
462
+ border-radius: 12px;
463
+ border: 1px solid var(--glass-border);
464
+ color: var(--text-primary);
465
+ font-size: 0.9em;
466
+ text-align: left;
467
+ box-shadow: var(--card-shadow);
468
+ display: flex;
469
+ flex-direction: column;
470
+ gap: 4px;
471
+ }
472
+
473
+ .logout-button {
474
+ background: var(--error-bg);
475
+ color: var(--error-color);
476
+ border: 1px solid rgba(244, 67, 54, 0.3);
477
+ padding: 6px 12px;
478
+ border-radius: 8px;
479
+ margin-top: 8px;
480
+ font-size: 0.8em;
481
+ transition: all var(--transition-fast);
482
+ cursor: pointer;
483
+ }
484
+
485
+ .logout-button:hover {
486
+ background: rgba(244, 67, 54, 0.3);
487
+ transform: translateY(-1px);
488
+ }
489
+
490
+ /* Tabs */
491
+ .tabs {
492
+ background: var(--input-bg);
493
+ padding: 6px;
494
+ border-radius: 16px;
495
+ display: inline-flex;
496
+ gap: 0;
497
+ border: 1px solid var(--glass-border);
498
+ }
499
+
500
+ .tab-button {
501
+ background: transparent;
502
+ color: var(--text-secondary);
503
+ border: none;
504
+ padding: 10px 24px;
505
+ border-radius: 12px;
506
+ font-weight: 500;
507
+ cursor: pointer;
508
+ transition: all 0.3s ease;
509
+ }
510
+
511
+ .tab-button.active {
512
+ background: var(--turkcell-yellow);
513
+ color: var(--turkcell-blue-dark);
514
+ font-weight: 700;
515
+ box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
516
+ }
517
+
518
+ /* Modern Sidebar */
519
+ .modern-sidebar {
520
+ background: rgba(10, 14, 53, 0.95);
521
+ border-right: 1px solid var(--turkcell-yellow);
522
+ backdrop-filter: blur(30px);
523
+ }
524
+
525
+ .modern-sidebar-toggle {
526
+ background: linear-gradient(135deg, var(--turkcell-yellow), var(--turkcell-yellow-glow));
527
+ color: var(--turkcell-blue-dark);
528
+ box-shadow: 0 0 20px rgba(255, 193, 7, 0.4);
529
+ }
530
+
531
+ .sidebar-header {
532
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
533
+ }
534
+
535
+ .info-item,
536
+ .usage-item,
537
+ .recommendation-card,
538
+ .package-info {
539
+ background: rgba(255, 255, 255, 0.05);
540
+ border: 1px solid rgba(255, 255, 255, 0.1);
541
+ color: var(--text-primary);
542
+ }
543
+
544
+ .info-item:hover,
545
+ .recommendation-card:hover {
546
+ background: rgba(255, 255, 255, 0.1);
547
+ border-color: var(--turkcell-yellow);
548
+ }
549
+
550
+ .section-title,
551
+ .package-name,
552
+ .rec-title {
553
+ color: var(--turkcell-yellow);
554
+ }
555
+
556
+ .info-label,
557
+ .usage-label,
558
+ .rec-desc {
559
+ color: var(--text-secondary);
560
+ }
561
+
562
+ .info-value,
563
+ .usage-text {
564
+ color: white;
565
+ }
566
+
567
+ /* Popup */
568
+ .popup-content {
569
+ background: var(--turkcell-blue-dark);
570
+ border: 1px solid var(--turkcell-yellow);
571
+ color: white;
572
+ }
573
+
574
+ .popup-header {
575
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
576
+ }
577
+
578
+ .popup-header h2 {
579
+ color: var(--turkcell-yellow);
580
+ }
581
+
582
+ .popup-footer {
583
+ background: rgba(0, 0, 0, 0.2);
584
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
585
+ }
586
+
587
+ .close-button {
588
+ color: var(--text-secondary);
589
+ }
590
+
591
+ .close-button:hover {
592
+ background: rgba(255, 255, 255, 0.1);
593
+ color: white;
594
+ }
595
+
596
+ /* ================================
597
+ VERIFICATION FORM - Modern Design
598
+ ================================ */
599
+
600
+ .verification-form {
601
+ width: 100%;
602
+ display: flex;
603
+ flex-direction: column;
604
+ gap: 32px;
605
+ margin-top: 20px;
606
+ }
607
+
608
+ .form-section {
609
+ display: flex;
610
+ flex-direction: column;
611
+ gap: 24px;
612
+ animation: slideInLeft 0.6s ease-out 0.3s both;
613
+ }
614
+
615
+ .input-group {
616
+ display: flex;
617
+ flex-direction: column;
618
+ align-items: flex-start;
619
+ gap: 8px;
620
+ width: 100%;
621
+ }
622
+
623
+ .input-group:nth-child(1) {
624
+ animation: slideInLeft 0.5s ease-out 0.4s both;
625
+ }
626
+
627
+ .input-group:nth-child(2) {
628
+ animation: slideInLeft 0.5s ease-out 0.5s both;
629
+ }
630
+
631
+ .input-label {
632
+ font-size: 0.9em;
633
+ font-weight: 600;
634
+ color: var(--text-secondary);
635
+ text-transform: uppercase;
636
+ letter-spacing: 1px;
637
+ }
638
+
639
+ .modern-input {
640
+ font-size: 1.2em !important;
641
+ padding: 18px 24px !important;
642
+ text-align: center;
643
+ letter-spacing: 2px;
644
+ font-weight: 500;
645
+ }
646
+
647
+ /* Role Toggle - Modern Button Group */
648
+ .role-toggle {
649
+ display: flex;
650
+ gap: 12px;
651
+ width: 100%;
652
+ }
653
+
654
+ .role-option {
655
+ flex: 1;
656
+ display: flex;
657
+ align-items: center;
658
+ justify-content: center;
659
+ gap: 10px;
660
+ padding: 16px 20px;
661
+ border-radius: 14px;
662
+ border: 2px solid var(--glass-border);
663
+ background: var(--input-bg);
664
+ color: var(--text-secondary);
665
+ font-size: 1em;
666
+ font-weight: 600;
667
+ cursor: pointer;
668
+ transition: all var(--transition-medium);
669
+ }
670
+
671
+ .role-option:hover {
672
+ border-color: var(--turkcell-yellow);
673
+ background: var(--glass-bg);
674
+ transform: translateY(-2px);
675
+ }
676
+
677
+ .role-option.active {
678
+ background: linear-gradient(135deg, var(--turkcell-yellow-glow), var(--turkcell-yellow));
679
+ border-color: var(--turkcell-yellow);
680
+ color: var(--button-text);
681
+ box-shadow: 0 4px 20px rgba(255, 193, 7, 0.4);
682
+ }
683
+
684
+ .role-option.active:hover {
685
+ transform: translateY(-2px) scale(1.02);
686
+ }
687
+
688
+ .role-icon {
689
+ font-size: 1.3em;
690
+ }
691
+
692
+ /* Action Buttons Section */
693
+ .action-buttons {
694
+ display: flex;
695
+ align-items: center;
696
+ justify-content: center;
697
+ gap: 20px;
698
+ flex-wrap: wrap;
699
+ }
700
+
701
+ .action-button {
702
+ flex: 0 1 200px;
703
+ display: flex;
704
+ align-items: center;
705
+ justify-content: center;
706
+ gap: 12px;
707
+ padding: 18px 28px;
708
+ font-size: 1.1em;
709
+ }
710
+
711
+ .action-button svg {
712
+ font-size: 1.2em;
713
+ }
714
+
715
+ .record-btn {
716
+ background: linear-gradient(135deg, var(--turkcell-blue-light), var(--turkcell-blue));
717
+ color: white;
718
+ border: 2px solid var(--turkcell-yellow);
719
+ box-shadow: 0 4px 20px rgba(26, 35, 126, 0.4);
720
+ }
721
+
722
+ .record-btn:hover {
723
+ box-shadow: 0 8px 30px rgba(26, 35, 126, 0.6);
724
+ }
725
+
726
+ .stop-btn {
727
+ background: linear-gradient(135deg, #f44336, #b71c1c);
728
+ color: white;
729
+ border: none;
730
+ }
731
+
732
+ .upload-btn {
733
+ background: var(--glass-bg);
734
+ border: 2px dashed var(--glass-border);
735
+ color: var(--text-primary);
736
+ box-shadow: none;
737
+ }
738
+
739
+ .upload-btn:hover {
740
+ border-color: var(--turkcell-yellow);
741
+ border-style: solid;
742
+ background: var(--input-bg);
743
+ }
744
+
745
+ .divider-text {
746
+ color: var(--text-muted);
747
+ font-size: 0.9em;
748
+ font-weight: 500;
749
+ text-transform: uppercase;
750
+ letter-spacing: 1px;
751
+ }
752
+
753
+ /* Status Section */
754
+ .status {
755
+ margin-top: 24px;
756
+ padding: 16px 24px;
757
+ background: var(--input-bg);
758
+ border-radius: 12px;
759
+ border: 1px solid var(--glass-border);
760
+ color: var(--text-secondary);
761
+ font-size: 0.95em;
762
+ }
763
+
764
+ .status span {
765
+ color: var(--turkcell-yellow);
766
+ font-weight: 600;
767
+ }
768
+
769
+ /* Responsive adjustments */
770
+ @media (max-width: 600px) {
771
+ .role-toggle {
772
+ flex-direction: column;
773
+ }
774
+
775
+ .action-buttons {
776
+ flex-direction: column;
777
+ }
778
+
779
+ .action-button {
780
+ width: 100%;
781
+ flex: none;
782
+ }
783
+
784
+ .divider-text {
785
+ margin: 8px 0;
786
+ }
787
+ }
788
+
789
+ /* ================================
790
+ EMOTION VERIFICATION PAGE
791
+ ================================ */
792
+
793
+ /* Modern Sidebar Toggle Button */
794
+ .modern-sidebar-toggle {
795
+ position: fixed;
796
+ top: 80px;
797
+ left: 20px;
798
+ z-index: 100;
799
+ display: flex;
800
+ align-items: center;
801
+ gap: 10px;
802
+ padding: 12px 20px;
803
+ background: linear-gradient(135deg, var(--turkcell-yellow-glow), var(--turkcell-yellow));
804
+ border: none;
805
+ border-radius: 14px;
806
+ color: var(--button-text);
807
+ font-weight: 700;
808
+ font-size: 0.95em;
809
+ cursor: pointer;
810
+ box-shadow: 0 4px 20px rgba(255, 193, 7, 0.4);
811
+ transition: all var(--transition-medium);
812
+ animation: slideInLeft 0.5s ease-out 0.6s both;
813
+ }
814
+
815
+ .modern-sidebar-toggle:hover {
816
+ transform: translateX(5px) scale(1.02);
817
+ box-shadow: 0 6px 25px rgba(255, 193, 7, 0.5);
818
+ }
819
+
820
+ .toggle-text {
821
+ font-size: 0.9em;
822
+ }
823
+
824
+ /* Sidebar Overlay */
825
+ .sidebar-overlay {
826
+ position: fixed;
827
+ top: 0;
828
+ left: 0;
829
+ right: 0;
830
+ bottom: 0;
831
+ background: rgba(0, 0, 0, 0.5);
832
+ backdrop-filter: blur(5px);
833
+ z-index: 200;
834
+ animation: fadeIn 0.3s ease-out;
835
+ }
836
+
837
+ @keyframes fadeIn {
838
+ from {
839
+ opacity: 0;
840
+ }
841
+
842
+ to {
843
+ opacity: 1;
844
+ }
845
+ }
846
+
847
+ /* Modern Sidebar */
848
+ .modern-sidebar {
849
+ position: fixed;
850
+ top: 0;
851
+ left: -400px;
852
+ width: 380px;
853
+ height: 100vh;
854
+ background: var(--glass-bg);
855
+ backdrop-filter: blur(25px);
856
+ -webkit-backdrop-filter: blur(25px);
857
+ border-right: 1px solid var(--glass-border);
858
+ z-index: 300;
859
+ transition: left var(--transition-medium);
860
+ overflow-y: auto;
861
+ box-shadow: 4px 0 30px rgba(0, 0, 0, 0.3);
862
+ }
863
+
864
+ .modern-sidebar.open {
865
+ left: 0;
866
+ }
867
+
868
+ .sidebar-header {
869
+ display: flex;
870
+ justify-content: space-between;
871
+ align-items: center;
872
+ padding: 24px;
873
+ border-bottom: 1px solid var(--glass-border);
874
+ background: var(--input-bg);
875
+ }
876
+
877
+ .header-content {
878
+ display: flex;
879
+ align-items: center;
880
+ gap: 12px;
881
+ }
882
+
883
+ .header-icon {
884
+ font-size: 1.8em;
885
+ }
886
+
887
+ .sidebar-header h3 {
888
+ margin: 0;
889
+ color: var(--text-primary);
890
+ font-size: 1.2em;
891
+ }
892
+
893
+ .close-btn {
894
+ background: none;
895
+ border: none;
896
+ color: var(--text-secondary);
897
+ font-size: 1.5em;
898
+ cursor: pointer;
899
+ padding: 8px;
900
+ border-radius: 8px;
901
+ transition: all var(--transition-fast);
902
+ }
903
+
904
+ .close-btn:hover {
905
+ background: var(--error-bg);
906
+ color: var(--error-color);
907
+ }
908
+
909
+ .sidebar-content {
910
+ padding: 20px;
911
+ display: flex;
912
+ flex-direction: column;
913
+ gap: 24px;
914
+ }
915
+
916
+ /* Info Sections */
917
+ .info-section {
918
+ background: var(--input-bg);
919
+ border-radius: 16px;
920
+ padding: 20px;
921
+ border: 1px solid var(--glass-border);
922
+ }
923
+
924
+ .section-title {
925
+ margin: 0 0 16px 0;
926
+ color: var(--turkcell-yellow);
927
+ font-size: 1em;
928
+ font-weight: 600;
929
+ }
930
+
931
+ .info-grid {
932
+ display: flex;
933
+ flex-direction: column;
934
+ gap: 12px;
935
+ }
936
+
937
+ .info-item {
938
+ display: flex;
939
+ justify-content: space-between;
940
+ align-items: center;
941
+ padding: 10px 14px;
942
+ background: var(--glass-bg);
943
+ border-radius: 10px;
944
+ border: 1px solid var(--glass-border);
945
+ }
946
+
947
+ .info-label {
948
+ color: var(--text-secondary);
949
+ font-size: 0.85em;
950
+ }
951
+
952
+ .info-value {
953
+ color: var(--text-primary);
954
+ font-weight: 600;
955
+ }
956
+
957
+ /* Package Info */
958
+ .package-info {
959
+ text-align: center;
960
+ padding: 16px;
961
+ background: linear-gradient(135deg, var(--turkcell-blue), var(--turkcell-blue-dark));
962
+ border-radius: 12px;
963
+ color: white;
964
+ }
965
+
966
+ .package-name {
967
+ font-size: 1.3em;
968
+ font-weight: 700;
969
+ color: var(--turkcell-yellow);
970
+ margin-bottom: 4px;
971
+ }
972
+
973
+ .package-price {
974
+ font-size: 1.1em;
975
+ margin-bottom: 12px;
976
+ opacity: 0.9;
977
+ }
978
+
979
+ .package-features {
980
+ font-size: 0.9em;
981
+ line-height: 1.8;
982
+ opacity: 0.85;
983
+ }
984
+
985
+ /* Usage Stats */
986
+ .usage-stats {
987
+ display: flex;
988
+ flex-direction: column;
989
+ gap: 16px;
990
+ }
991
+
992
+ .usage-item {
993
+ display: flex;
994
+ flex-direction: column;
995
+ gap: 8px;
996
+ }
997
+
998
+ .usage-header {
999
+ display: flex;
1000
+ align-items: center;
1001
+ gap: 8px;
1002
+ }
1003
+
1004
+ .usage-icon {
1005
+ font-size: 1.1em;
1006
+ }
1007
+
1008
+ .usage-label {
1009
+ flex: 1;
1010
+ color: var(--text-secondary);
1011
+ font-size: 0.9em;
1012
+ }
1013
+
1014
+ .usage-text {
1015
+ color: var(--text-primary);
1016
+ font-weight: 600;
1017
+ font-size: 0.85em;
1018
+ }
1019
+
1020
+ .usage-bar {
1021
+ height: 8px;
1022
+ background: var(--input-bg);
1023
+ border-radius: 4px;
1024
+ overflow: hidden;
1025
+ }
1026
+
1027
+ .usage-fill {
1028
+ height: 100%;
1029
+ border-radius: 4px;
1030
+ transition: width 0.5s ease-out;
1031
+ }
1032
+
1033
+ .usage-fill.internet {
1034
+ background: linear-gradient(90deg, #4FC3F7, #0288D1);
1035
+ }
1036
+
1037
+ .usage-fill.minutes {
1038
+ background: linear-gradient(90deg, #81C784, #388E3C);
1039
+ }
1040
+
1041
+ .usage-fill.sms {
1042
+ background: linear-gradient(90deg, #FFB74D, #F57C00);
1043
+ }
1044
+
1045
+ /* Recommendations */
1046
+ .recommendations {
1047
+ display: flex;
1048
+ flex-direction: column;
1049
+ gap: 12px;
1050
+ }
1051
+
1052
+ .recommendation-card {
1053
+ background: var(--glass-bg);
1054
+ border: 1px solid var(--glass-border);
1055
+ border-radius: 12px;
1056
+ padding: 16px;
1057
+ transition: all var(--transition-medium);
1058
+ }
1059
+
1060
+ .recommendation-card:hover {
1061
+ border-color: var(--turkcell-yellow);
1062
+ transform: translateY(-2px);
1063
+ box-shadow: 0 4px 15px rgba(255, 193, 7, 0.2);
1064
+ }
1065
+
1066
+ .rec-title {
1067
+ font-weight: 700;
1068
+ color: var(--text-primary);
1069
+ margin-bottom: 4px;
1070
+ }
1071
+
1072
+ .rec-price {
1073
+ color: var(--turkcell-yellow);
1074
+ font-weight: 600;
1075
+ font-size: 1.1em;
1076
+ margin-bottom: 8px;
1077
+ }
1078
+
1079
+ .rec-desc {
1080
+ color: var(--text-secondary);
1081
+ font-size: 0.85em;
1082
+ margin-bottom: 12px;
1083
+ }
1084
+
1085
+ .rec-button {
1086
+ background: linear-gradient(135deg, var(--turkcell-yellow-glow), var(--turkcell-yellow));
1087
+ border: none;
1088
+ color: var(--button-text);
1089
+ padding: 8px 16px;
1090
+ border-radius: 8px;
1091
+ font-weight: 600;
1092
+ cursor: pointer;
1093
+ transition: all var(--transition-fast);
1094
+ }
1095
+
1096
+ .rec-button:hover {
1097
+ transform: scale(1.05);
1098
+ }
1099
+
1100
+ /* Emojis Grid */
1101
+ .emojis-grid {
1102
+ display: grid;
1103
+ grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
1104
+ gap: 16px;
1105
+ margin: 24px 0;
1106
+ animation: fadeInUp 0.6s ease-out 0.4s both;
1107
+ }
1108
+
1109
+ .emoji-card {
1110
+ display: flex;
1111
+ flex-direction: column;
1112
+ align-items: center;
1113
+ justify-content: center;
1114
+ padding: 20px 16px;
1115
+ background: var(--glass-bg);
1116
+ border: 2px solid var(--glass-border);
1117
+ border-radius: 16px;
1118
+ cursor: pointer;
1119
+ transition: all var(--transition-medium);
1120
+ }
1121
+
1122
+ .emoji-card:hover {
1123
+ transform: translateY(-4px) scale(1.05);
1124
+ border-color: var(--turkcell-yellow);
1125
+ box-shadow: 0 8px 25px rgba(255, 193, 7, 0.2);
1126
+ }
1127
+
1128
+ .emoji-card.active {
1129
+ background: linear-gradient(135deg, rgba(255, 193, 7, 0.2), rgba(255, 213, 79, 0.1));
1130
+ border-color: var(--turkcell-yellow);
1131
+ box-shadow: 0 0 30px rgba(255, 193, 7, 0.4);
1132
+ animation: pulse-glow 2s infinite;
1133
+ }
1134
+
1135
+ .emoji-icon {
1136
+ font-size: 2.5em;
1137
+ margin-bottom: 8px;
1138
+ transition: transform var(--transition-medium);
1139
+ }
1140
+
1141
+ .emoji-card:hover .emoji-icon {
1142
+ transform: scale(1.2);
1143
+ }
1144
+
1145
+ .emoji-card.active .emoji-icon {
1146
+ animation: bounce 0.6s ease infinite;
1147
+ }
1148
+
1149
+ @keyframes bounce {
1150
+
1151
+ 0%,
1152
+ 100% {
1153
+ transform: translateY(0);
1154
+ }
1155
+
1156
+ 50% {
1157
+ transform: translateY(-8px);
1158
+ }
1159
+ }
1160
+
1161
+ .emoji-label {
1162
+ font-size: 0.9em;
1163
+ font-weight: 600;
1164
+ color: var(--text-secondary);
1165
+ }
1166
+
1167
+ .emoji-card.active .emoji-label {
1168
+ color: var(--turkcell-yellow);
1169
+ }
1170
+
1171
+ /* Active Emotion Badge */
1172
+ .active-emotion-badge {
1173
+ display: inline-flex;
1174
+ align-items: center;
1175
+ gap: 12px;
1176
+ padding: 16px 28px;
1177
+ background: linear-gradient(135deg, var(--turkcell-yellow-glow), var(--turkcell-yellow));
1178
+ border-radius: 50px;
1179
+ margin: 20px 0;
1180
+ box-shadow: 0 4px 25px rgba(255, 193, 7, 0.5);
1181
+ animation: scaleIn 0.5s ease-out;
1182
+ }
1183
+
1184
+ .emotion-title {
1185
+ color: var(--button-text);
1186
+ font-weight: 500;
1187
+ font-size: 0.95em;
1188
+ }
1189
+
1190
+ .emotion-value {
1191
+ color: var(--button-text);
1192
+ font-weight: 800;
1193
+ font-size: 1.3em;
1194
+ }
1195
+
1196
+ /* Recommendations Section (Main Content) */
1197
+ .recommendations-section {
1198
+ margin-top: 32px;
1199
+ animation: fadeInUp 0.6s ease-out 0.5s both;
1200
+ }
1201
+
1202
+ .recommendations-title {
1203
+ color: var(--text-primary);
1204
+ font-size: 1.5em;
1205
+ margin-bottom: 20px;
1206
+ background: linear-gradient(135deg, var(--text-primary) 30%, var(--turkcell-yellow) 100%);
1207
+ background-clip: text;
1208
+ -webkit-background-clip: text;
1209
+ -webkit-text-fill-color: transparent;
1210
+ }
1211
+
1212
+ .recommendations-grid {
1213
+ display: grid;
1214
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
1215
+ gap: 20px;
1216
+ }
1217
+
1218
+ /* Audio Player */
1219
+ .audio-player-container {
1220
+ margin: 20px 0;
1221
+ padding: 16px;
1222
+ background: var(--input-bg);
1223
+ border-radius: 14px;
1224
+ border: 1px solid var(--glass-border);
1225
+ }
1226
+
1227
+ .custom-audio {
1228
+ width: 100%;
1229
+ height: 40px;
1230
+ border-radius: 8px;
1231
+ }
1232
+
1233
+ /* Upload Button Style */
1234
+ .upload-button {
1235
+ background: var(--glass-bg) !important;
1236
+ border: 2px dashed var(--glass-border) !important;
1237
+ color: var(--text-primary) !important;
1238
+ }
1239
+
1240
+ .upload-button:hover {
1241
+ border-color: var(--turkcell-yellow) !important;
1242
+ border-style: solid !important;
1243
+ }
1244
+
1245
+ /* File Info */
1246
+ .file-info {
1247
+ margin-top: 16px;
1248
+ padding: 16px 20px;
1249
+ background: var(--input-bg);
1250
+ border-radius: 12px;
1251
+ border: 1px solid var(--glass-border);
1252
+ color: var(--text-secondary);
1253
+ }
1254
+
1255
+ .file-info strong {
1256
+ color: var(--turkcell-yellow);
1257
+ }
1258
+
1259
+ /* Responsive Sidebar */
1260
+ @media (max-width: 480px) {
1261
+ .modern-sidebar {
1262
+ width: 100%;
1263
+ left: -100%;
1264
+ }
1265
+
1266
+ .modern-sidebar-toggle {
1267
+ padding: 10px 14px;
1268
+ font-size: 0.85em;
1269
+ }
1270
+
1271
+ .toggle-text {
1272
+ display: none;
1273
+ }
1274
+
1275
+ .emojis-grid {
1276
+ grid-template-columns: repeat(3, 1fr);
1277
+ gap: 10px;
1278
+ }
1279
+
1280
+ .emoji-card {
1281
+ padding: 14px 10px;
1282
+ }
1283
+
1284
+ .emoji-icon {
1285
+ font-size: 2em;
1286
+ }
1287
+ }
frontend/src/App.jsx ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //App.jsx
2
+ import React, { useState } from 'react';
3
+ import './App.css';
4
+ import VerificationPage from './VerificationPage.jsx';
5
+ import ManagementPage from './ManagementPage.jsx';
6
+ import EmotionVerificationPage from './EmotionVerificationPage.jsx';
7
+ import { ThemeProvider } from './ThemeContext.jsx';
8
+ import ThemeToggle from './ThemeToggle.jsx';
9
+
10
+ const App = () => {
11
+ const [currentPage, setCurrentPage] = useState('verify');
12
+ const [verification, setVerification] = useState(null);
13
+
14
+ const handleVerified = (verificationResult) => {
15
+ setVerification(verificationResult);
16
+ setCurrentPage('manage');
17
+ };
18
+
19
+ const handleBackToVerify = () => {
20
+ setCurrentPage('verify');
21
+ setVerification(null);
22
+ };
23
+
24
+ const openEmotionPage = () => {
25
+ setCurrentPage('emotion');
26
+ };
27
+
28
+ const backToManage = () => {
29
+ setCurrentPage('manage');
30
+ };
31
+
32
+ return (
33
+ <ThemeProvider>
34
+ <div className="App">
35
+ <ThemeToggle />
36
+ {currentPage === 'verify' && (
37
+ <VerificationPage onVerified={handleVerified} />
38
+ )}
39
+ {currentPage === 'manage' && (
40
+ <ManagementPage verification={verification} onBack={handleBackToVerify} onOpenEmotion={openEmotionPage} />
41
+ )}
42
+ {currentPage === 'emotion' && (
43
+ <EmotionVerificationPage verification={verification} onBack={backToManage} />
44
+ )}
45
+ </div>
46
+ </ThemeProvider>
47
+ );
48
+ };
49
+
50
+ export default App;
frontend/src/AudioVisualizer.jsx ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useRef, useEffect } from 'react';
2
+
3
+ const AudioVisualizer = ({ audioData }) => {
4
+ const canvasRef = useRef(null);
5
+
6
+ useEffect(() => {
7
+ if (!audioData) return;
8
+
9
+ const canvas = canvasRef.current;
10
+ const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
11
+ const analyser = audioCtx.createAnalyser();
12
+
13
+ // Daha yumuşak geçişler için
14
+ analyser.smoothingTimeConstant = 0.85;
15
+ analyser.fftSize = 256;
16
+
17
+ const source = audioCtx.createMediaStreamSource(audioData);
18
+ source.connect(analyser);
19
+
20
+ const bufferLength = analyser.frequencyBinCount;
21
+ const dataArray = new Uint8Array(bufferLength);
22
+ const canvasCtx = canvas.getContext('2d');
23
+
24
+ const draw = () => {
25
+ requestAnimationFrame(draw);
26
+
27
+ analyser.getByteFrequencyData(dataArray);
28
+
29
+ const width = canvas.width;
30
+ const height = canvas.height;
31
+ const centerX = width / 2;
32
+ const centerY = height / 2;
33
+
34
+ canvasCtx.clearRect(0, 0, width, height);
35
+
36
+ // Ortalama ses seviyesini hesapla
37
+ let average = 0;
38
+ for (let i = 0; i < bufferLength; i++) {
39
+ average += dataArray[i];
40
+ }
41
+ average = average / bufferLength;
42
+
43
+ // Glow efekti
44
+ const glowRadius = average * 1.5;
45
+ const gradient = canvasCtx.createRadialGradient(centerX, centerY, 5, centerX, centerY, 100);
46
+ gradient.addColorStop(0, 'rgba(79, 70, 229, 0.8)'); // Primary
47
+ gradient.addColorStop(0.5, 'rgba(236, 72, 153, 0.4)'); // Secondary
48
+ gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
49
+
50
+ // Merkezi daire (sürekli var olan)
51
+ canvasCtx.beginPath();
52
+ canvasCtx.arc(centerX, centerY, 20 + (average / 5), 0, 2 * Math.PI);
53
+ canvasCtx.fillStyle = gradient;
54
+ canvasCtx.fill();
55
+
56
+ // Dış halkalar (frekansa göre)
57
+ // Bass
58
+ const bass = dataArray[10];
59
+ if (bass > 0) {
60
+ canvasCtx.beginPath();
61
+ canvasCtx.arc(centerX, centerY, 30 + (bass / 2), 0, 2 * Math.PI);
62
+ canvasCtx.strokeStyle = `rgba(139, 92, 246, ${bass / 255 * 0.5})`;
63
+ canvasCtx.lineWidth = 4;
64
+ canvasCtx.stroke();
65
+ }
66
+
67
+ // Mid
68
+ const mid = dataArray[50];
69
+ if (mid > 0) {
70
+ canvasCtx.beginPath();
71
+ canvasCtx.arc(centerX, centerY, 40 + (mid / 2), 0, 2 * Math.PI);
72
+ canvasCtx.strokeStyle = `rgba(236, 72, 153, ${mid / 255 * 0.4})`;
73
+ canvasCtx.lineWidth = 3;
74
+ canvasCtx.stroke();
75
+ }
76
+
77
+ // High
78
+ const high = dataArray[100];
79
+ if (high > 0) {
80
+ canvasCtx.beginPath();
81
+ canvasCtx.arc(centerX, centerY, 50 + (high / 2), 0, 2 * Math.PI);
82
+ canvasCtx.strokeStyle = `rgba(79, 70, 229, ${high / 255 * 0.3})`;
83
+ canvasCtx.lineWidth = 2;
84
+ canvasCtx.stroke();
85
+ }
86
+ };
87
+
88
+ draw();
89
+
90
+ return () => {
91
+ source.disconnect();
92
+ analyser.disconnect();
93
+ };
94
+ }, [audioData]);
95
+
96
+ return (
97
+ <canvas
98
+ ref={canvasRef}
99
+ width={400}
100
+ height={300}
101
+ style={{
102
+ marginTop: '20px',
103
+ maxWidth: '100%',
104
+ filter: 'drop-shadow(0 0 10px rgba(79, 70, 229, 0.5))'
105
+ }}
106
+ />
107
+ );
108
+ };
109
+
110
+ export default AudioVisualizer;
frontend/src/DualMind_Logo.png ADDED

Git LFS Details

  • SHA256: a18a10b9456e4333b18faf400277a8ffb7448ac0cced027bdfd773326bbcf044
  • Pointer size: 131 Bytes
  • Size of remote file: 732 kB
frontend/src/EmotionVerificationPage.jsx ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useMemo } from 'react';
2
+ import toWav from 'audiobuffer-to-wav';
3
+ import './App.css';
4
+ import logo from './DualMind_Logo.png';
5
+ import { API_CONFIG } from './config.js';
6
+
7
+ const EmotionVerificationPage = ({ onBack, verification }) => {
8
+ const [status, setStatus] = useState('Hazır');
9
+ const [isListening, setIsListening] = useState(false);
10
+ const [sidebarOpen, setSidebarOpen] = useState(false);
11
+ const mediaRecorderRef = useRef(null);
12
+ const audioChunksRef = useRef([]);
13
+ const [audioUrl, setAudioUrl] = useState(null);
14
+ const [results, setResults] = useState([]); // [{model, prediction, confidence}]
15
+ const [speechText, setSpeechText] = useState('');
16
+
17
+ const API_URL = API_CONFIG.DUYGU_API;
18
+
19
+ // Debug: verification prop'unu kontrol et
20
+ console.log('EmotionVerificationPage - verification:', verification);
21
+
22
+ const translateToTr = (label) => {
23
+ if (!label || typeof label !== 'string') return null;
24
+ const key = label.toString().trim().toLowerCase();
25
+ const enToTr = {
26
+ neutral: 'Sakin',
27
+ calm: 'Sakin',
28
+ happy: 'Mutlu',
29
+ sad: 'Üzgün',
30
+ angry: 'Kızgın',
31
+ fear: 'Endişeli',
32
+ fearful: 'Endişeli',
33
+ disgust: 'Hoşnutsuz',
34
+ surprised: 'Şaşkın',
35
+ surprise: 'Şaşkın'
36
+ };
37
+ if (enToTr[key]) return enToTr[key];
38
+ const trMap = {
39
+ 'nötr': 'Sakin',
40
+ 'sakin': 'Sakin',
41
+ 'mutlu': 'Mutlu',
42
+ 'üzgün': 'Üzgün',
43
+ 'kızgın': 'Kızgın',
44
+ 'kizgin': 'Kızgın',
45
+ 'korku': 'Endişeli',
46
+ 'endişeli': 'Endişeli',
47
+ 'endiseli': 'Endişeli',
48
+ 'tiksinmiş': 'Hoşnutsuz',
49
+ 'hosnutsuz': 'Hoşnutsuz',
50
+ 'hoşnutsuz': 'Hoşnutsuz',
51
+ 'şaşkın': 'Şaşkın',
52
+ 'saskin': 'Şaşkın'
53
+ };
54
+ return trMap[key] || null;
55
+ };
56
+
57
+ // Seed subscribers
58
+ const SEED_SUBSCRIBERS = useMemo(() => ([
59
+ { basePhone: '05327678989', role: 'owner', fullName: 'Mehmet Şimşek', packageName: 'GNC 30 GB' },
60
+ { basePhone: '05327678989', role: 'user', fullName: 'Derya Şimşek', packageName: 'GNC 30 GB' },
61
+ { basePhone: '05321234567', role: 'owner', fullName: 'Ayşe Yılmaz', packageName: 'GNC 20 GB' },
62
+ { basePhone: '05321234567', role: 'user', fullName: 'Ali Yılmaz', packageName: 'GNC 20 GB' },
63
+ { basePhone: '05339876543', role: 'owner', fullName: 'Can Demir', packageName: 'Platinum 40 GB' },
64
+ { basePhone: '05339876543', role: 'user', fullName: 'Elif Demir', packageName: 'Platinum 40 GB' },
65
+ { basePhone: '05325556677', role: 'owner', fullName: 'Fatma Kaya', packageName: 'Super 10 GB' },
66
+ { basePhone: '05325556677', role: 'user', fullName: 'Mert Kaya', packageName: 'Super 10 GB' },
67
+ { basePhone: '05329991122', role: 'owner', fullName: 'Zeynep Acar', packageName: 'GNC 8 GB' },
68
+ { basePhone: '05418065249', role: 'owner', fullName: 'İlayda Özdemir', packageName: 'GNC 30 GB' },
69
+ { basePhone: '05329991122', role: 'user', fullName: 'Burak Acar', packageName: 'GNC 8 GB' },
70
+ ].map(s => ({
71
+ ...s,
72
+ suffix: s.role === 'owner' ? 'HatSahibi' : 'Kullanici',
73
+ combinedName: `${s.basePhone}${s.role === 'owner' ? 'HatSahibi' : 'Kullanici'}`,
74
+ }))), []);
75
+
76
+ const subscribers = useMemo(() => {
77
+ try {
78
+ const saved = localStorage.getItem('subscribers');
79
+ return saved ? JSON.parse(saved) : [];
80
+ } catch { return []; }
81
+ }, []);
82
+
83
+ const allSubscribers = useMemo(() => ([...SEED_SUBSCRIBERS, ...subscribers]), [SEED_SUBSCRIBERS, subscribers]);
84
+ const currentCombined = verification?.expectedName;
85
+ const currentProfile = useMemo(() => {
86
+ if (currentCombined) {
87
+ return allSubscribers.find(s => s.combinedName === currentCombined);
88
+ }
89
+ // Fallback: İlk kullanıcıyı al
90
+ return allSubscribers[0] || null;
91
+ }, [allSubscribers, currentCombined]);
92
+
93
+ // Paket bilgileri - localStorage'dan gelen kullanıcıya göre
94
+ const getPackageInfo = useMemo(() => {
95
+ if (!currentProfile?.packageName) return null;
96
+
97
+ const packageMap = {
98
+ 'GNC 30 GB': { internet: 30, minutes: 1000, sms: 1000, price: '₺89.90/ay' },
99
+ 'GNC 20 GB': { internet: 20, minutes: 1000, sms: 1000, price: '₺69.90/ay' },
100
+ 'GNC 8 GB': { internet: 8, minutes: 500, sms: 500, price: '₺49.90/ay' },
101
+ 'Platinum 40 GB': { internet: 40, minutes: 1500, sms: 1500, price: '₺119.90/ay' },
102
+ 'Super 10 GB': { internet: 10, minutes: 500, sms: 500, price: '₺59.90/ay' }
103
+ };
104
+
105
+ const baseInfo = packageMap[currentProfile.packageName] || { internet: 30, minutes: 1000, sms: 1000, price: '₺89.90/ay' };
106
+
107
+ // Rastgele kullanım verileri
108
+ const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
109
+
110
+ return {
111
+ name: currentProfile.packageName,
112
+ price: baseInfo.price,
113
+ internetTotal: baseInfo.internet,
114
+ internetUsed: getRandomInt(5, Math.floor(baseInfo.internet * 0.8)),
115
+ minutesTotal: baseInfo.minutes,
116
+ minutesUsed: getRandomInt(50, Math.floor(baseInfo.minutes * 0.7)),
117
+ smsTotal: baseInfo.sms,
118
+ smsUsed: getRandomInt(20, Math.floor(baseInfo.sms * 0.6))
119
+ };
120
+ }, [currentProfile]);
121
+
122
+ // Emojis ve durum
123
+ const emojis = [
124
+ { label: 'Sakin', icon: '😐' },
125
+ { label: 'Mutlu', icon: '😊' },
126
+ { label: 'Üzgün', icon: '😢' },
127
+ { label: 'Kızgın', icon: '😡' },
128
+ { label: 'Hoşnutsuz', icon: '🤢' },
129
+ { label: 'Şaşkın', icon: '😮' },
130
+ { label: 'Endişeli', icon: '😨' }
131
+ ];
132
+
133
+ const topResult = Array.isArray(results) && results.length ? results[0] : null;
134
+ const activeEmotion = topResult?.prediction || null;
135
+
136
+ const getRecommendations = useMemo(() => {
137
+ return () => {
138
+ // Basit öneri listesi (duyguya göre çeşitlenir)
139
+ const internet = 30;
140
+ const same = internet;
141
+ const lower = 20;
142
+ const higher = 40;
143
+ const base = [
144
+ { title: `${same}GB Standart`, price: `${199} TL`, desc: `${same}GB + 1000 dk + 1000 SMS` },
145
+ { title: `${higher}GB Plus`, price: `${229} TL`, desc: `${higher}GB + 1500 dk + 1500 SMS` },
146
+ { title: `${lower}GB Ekonomik`, price: `${159} TL`, desc: `${lower}GB uygun fiyat` },
147
+ ];
148
+ switch (activeEmotion) {
149
+ case 'Mutlu':
150
+ return [base[1], base[0]];
151
+ case 'Üzgün':
152
+ case 'Hoşnutsuz':
153
+ case 'Endişeli':
154
+ return [base[2], base[0]];
155
+ case 'Kızgın':
156
+ return [base[0], base[2]];
157
+ default:
158
+ return base;
159
+ }
160
+ };
161
+ }, [activeEmotion]);
162
+
163
+ const startStopListening = async () => {
164
+ if (isListening) {
165
+ try { mediaRecorderRef.current && mediaRecorderRef.current.stop(); } catch (_) { }
166
+ setIsListening(false);
167
+ setStatus('Dinleme durduruldu.');
168
+ return;
169
+ }
170
+
171
+ try {
172
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
173
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/wav';
174
+ const mediaRecorder = new MediaRecorder(stream, { mimeType });
175
+ mediaRecorderRef.current = mediaRecorder;
176
+ audioChunksRef.current = [];
177
+
178
+ mediaRecorder.ondataavailable = (e) => audioChunksRef.current.push(e.data);
179
+
180
+ mediaRecorder.onstop = async () => {
181
+ if (!audioChunksRef.current.length) return;
182
+ const recordedBlob = new Blob(audioChunksRef.current, { type: mediaRecorder.mimeType });
183
+ try {
184
+ const arrayBuffer = await recordedBlob.arrayBuffer();
185
+ const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
186
+ const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
187
+ const wavBuffer = toWav(audioBuffer);
188
+ const wavBlob = new Blob([wavBuffer], { type: 'audio/wav' });
189
+ try {
190
+ const url = URL.createObjectURL(wavBlob);
191
+ if (audioUrl) URL.revokeObjectURL(audioUrl);
192
+ setAudioUrl(url);
193
+ } catch (_) { }
194
+ const formData = new FormData();
195
+ formData.append('file', wavBlob, 'live_audio.wav');
196
+ setStatus('Analiz ediliyor...');
197
+ const res = await fetch(`${API_URL}/predict`, { method: 'POST', body: formData });
198
+ const api = await res.json();
199
+ if (api && api.prediction) {
200
+ const predTr = translateToTr(api.prediction_tr) || translateToTr(api.prediction) || api.prediction;
201
+ const data = [{ model: 'Wav2Vec2', prediction: predTr, confidence: api.confidence || 0 }];
202
+ setResults(data);
203
+ setStatus('Analiz tamamlandı.');
204
+ } else if (api && api.error) {
205
+ setStatus(`Hata: ${api.error}`);
206
+ } else {
207
+ setStatus('Analiz sonucu alınamadı.');
208
+ }
209
+ } catch (err) {
210
+ console.error(err);
211
+ setStatus('Kayıt işlenirken hata oluştu.');
212
+ } finally {
213
+ stream.getTracks().forEach(t => t.stop());
214
+ }
215
+ };
216
+
217
+ mediaRecorder.start();
218
+ setIsListening(true);
219
+ setStatus('Dinleniyor...');
220
+ } catch (err) {
221
+ console.error(err);
222
+ setStatus('Mikrofon açılamadı.');
223
+ }
224
+ };
225
+
226
+ const handleFileChange = async (e) => {
227
+ const file = e.target.files && e.target.files[0];
228
+ if (!file) return;
229
+ try {
230
+ const url = URL.createObjectURL(file);
231
+ if (audioUrl) URL.revokeObjectURL(audioUrl);
232
+ setAudioUrl(url);
233
+ } catch (_) { }
234
+
235
+ const formData = new FormData();
236
+ formData.append('file', file);
237
+ try {
238
+ setStatus('Analiz ediliyor...');
239
+ const res = await fetch(`${API_URL}/predict`, { method: 'POST', body: formData });
240
+ const api = await res.json();
241
+ if (api && api.prediction) {
242
+ const predTr = translateToTr(api.prediction_tr) || translateToTr(api.prediction) || api.prediction;
243
+ const data = [{ model: 'Wav2Vec2', prediction: predTr, confidence: api.confidence || 0 }];
244
+ setResults(data);
245
+ setStatus('Analiz tamamlandı.');
246
+ } else if (api && api.error) {
247
+ setStatus(`Hata: ${api.error}`);
248
+ } else {
249
+ setStatus('Analiz sonucu alınamadı.');
250
+ }
251
+ } catch (err) {
252
+ console.error(err);
253
+ setStatus('Dosya yüklenirken hata oluştu.');
254
+ }
255
+ };
256
+
257
+ const handleSpeechAnalysis = () => {
258
+ setSpeechText('');
259
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
260
+ if (!SpeechRecognition) {
261
+ setSpeechText('Tarayıcınız konuşma tanımayı desteklemiyor.');
262
+ return;
263
+ }
264
+ const recognition = new SpeechRecognition();
265
+ recognition.lang = 'tr-TR';
266
+ recognition.interimResults = true;
267
+ recognition.maxAlternatives = 3;
268
+ recognition.continuous = false;
269
+
270
+ let finalTranscript = '';
271
+ let timeoutId = setTimeout(() => {
272
+ setSpeechText('Konuşma algılanamadı. Lütfen daha yüksek sesle konuşun ve tekrar deneyin.');
273
+ try { recognition.stop(); } catch (_) { }
274
+ }, 10000);
275
+
276
+ recognition.onstart = () => { setSpeechText('🎤 Dinleniyor... Lütfen konuşun.'); };
277
+ recognition.onresult = (event) => {
278
+ let interimTranscript = '';
279
+ for (let i = event.resultIndex; i < event.results.length; i++) {
280
+ const transcript = event.results[i][0].transcript;
281
+ if (event.results[i].isFinal) finalTranscript += transcript; else interimTranscript += transcript;
282
+ }
283
+ if (interimTranscript) setSpeechText(`🎤 Dinleniyor: ${interimTranscript}`);
284
+ if (finalTranscript) { clearTimeout(timeoutId); setSpeechText(finalTranscript); }
285
+ };
286
+ recognition.onerror = (event) => { clearTimeout(timeoutId); setSpeechText(`Konuşma tanıma hatası: ${event.error}`); };
287
+ recognition.onend = () => { clearTimeout(timeoutId); };
288
+ try { recognition.start(); } catch (_) { }
289
+ };
290
+
291
+ // Debug: Sayfa yükleniyor mu kontrol et
292
+ console.log('EmotionVerificationPage render ediliyor');
293
+
294
+ return (
295
+ <div className="App">
296
+ {/* Modern Sidebar Toggle Button */}
297
+ <button
298
+ className="modern-sidebar-toggle"
299
+ onClick={() => setSidebarOpen(!sidebarOpen)}
300
+ >
301
+ <span className="toggle-icon">📊</span>
302
+ <span className="toggle-text">Müşteri Detayları</span>
303
+ </button>
304
+
305
+ {/* Sidebar Overlay */}
306
+ {sidebarOpen && (
307
+ <div
308
+ className="sidebar-overlay"
309
+ onClick={() => setSidebarOpen(false)}
310
+ ></div>
311
+ )}
312
+
313
+ {/* Modern Sidebar */}
314
+ <div className={`modern-sidebar ${sidebarOpen ? 'open' : ''}`}>
315
+ <div className="sidebar-header">
316
+ <div className="header-content">
317
+ <div className="header-icon">👤</div>
318
+ <h3>Müşteri Bilgileri</h3>
319
+ </div>
320
+ <button
321
+ className="close-btn"
322
+ onClick={() => setSidebarOpen(false)}
323
+ >
324
+ ✕
325
+ </button>
326
+ </div>
327
+
328
+ <div className="sidebar-content">
329
+ {/* Müşteri Bilgileri */}
330
+ {currentProfile && (
331
+ <div className="info-section">
332
+ <h4 className="section-title">👤 Müşteri Bilgileri</h4>
333
+ <div className="info-grid">
334
+ <div className="info-item">
335
+ <span className="info-label">Ad Soyad</span>
336
+ <span className="info-value">{currentProfile.fullName}</span>
337
+ </div>
338
+ <div className="info-item">
339
+ <span className="info-label">Telefon</span>
340
+ <span className="info-value">{currentProfile.basePhone}</span>
341
+ </div>
342
+ <div className="info-item">
343
+ <span className="info-label">Rol</span>
344
+ <span className="info-value">{currentProfile.role === 'owner' ? 'Hat Sahibi' : 'Kullanıcı'}</span>
345
+ </div>
346
+ </div>
347
+ </div>
348
+ )}
349
+
350
+ {/* Paket Bilgileri */}
351
+ {getPackageInfo && (
352
+ <div className="info-section">
353
+ <h4 className="section-title">📦 Mevcut Paket</h4>
354
+ <div className="package-info">
355
+ <div className="package-name">{getPackageInfo.name}</div>
356
+ <div className="package-price">{getPackageInfo.price}</div>
357
+ <div className="package-features">
358
+ 🌐 {getPackageInfo.internetTotal}GB internet<br />
359
+ 📞 {getPackageInfo.minutesTotal} dk<br />
360
+ 💬 {getPackageInfo.smsTotal} SMS
361
+ </div>
362
+ </div>
363
+ </div>
364
+ )}
365
+
366
+ {/* Kullanım Durumu */}
367
+ {getPackageInfo && (
368
+ <div className="info-section">
369
+ <h4 className="section-title">📊 Kullanım Durumu</h4>
370
+ <div className="usage-stats">
371
+ <div className="usage-item">
372
+ <div className="usage-header">
373
+ <span className="usage-icon">🌐</span>
374
+ <span className="usage-label">İnternet</span>
375
+ <span className="usage-text">{getPackageInfo.internetUsed}GB / {getPackageInfo.internetTotal}GB</span>
376
+ </div>
377
+ <div className="usage-bar">
378
+ <div
379
+ className="usage-fill internet"
380
+ style={{ width: `${(getPackageInfo.internetUsed / getPackageInfo.internetTotal) * 100}%` }}
381
+ ></div>
382
+ </div>
383
+ </div>
384
+
385
+ <div className="usage-item">
386
+ <div className="usage-header">
387
+ <span className="usage-icon">📞</span>
388
+ <span className="usage-label">Dakika</span>
389
+ <span className="usage-text">{getPackageInfo.minutesUsed}dk / {getPackageInfo.minutesTotal}dk</span>
390
+ </div>
391
+ <div className="usage-bar">
392
+ <div
393
+ className="usage-fill minutes"
394
+ style={{ width: `${(getPackageInfo.minutesUsed / getPackageInfo.minutesTotal) * 100}%` }}
395
+ ></div>
396
+ </div>
397
+ </div>
398
+
399
+ <div className="usage-item">
400
+ <div className="usage-header">
401
+ <span className="usage-icon">💬</span>
402
+ <span className="usage-label">SMS</span>
403
+ <span className="usage-text">{getPackageInfo.smsUsed} / {getPackageInfo.smsTotal}</span>
404
+ </div>
405
+ <div className="usage-bar">
406
+ <div
407
+ className="usage-fill sms"
408
+ style={{ width: `${(getPackageInfo.smsUsed / getPackageInfo.smsTotal) * 100}%` }}
409
+ ></div>
410
+ </div>
411
+ </div>
412
+ </div>
413
+ </div>
414
+ )}
415
+
416
+ {/* Önerilen Paketler */}
417
+ {activeEmotion && (
418
+ <div className="info-section">
419
+ <h4 className="section-title">💡 Önerilen Paketler</h4>
420
+ <div className="recommendations">
421
+ {getRecommendations().slice(0, 3).map((rec, idx) => (
422
+ <div key={`${rec.title}-${idx}`} className="recommendation-card">
423
+ <div className="rec-title">{rec.title}</div>
424
+ <div className="rec-price">{rec.price}</div>
425
+ <div className="rec-desc">{rec.desc}</div>
426
+ <button className="rec-button">Öner</button>
427
+ </div>
428
+ ))}
429
+ </div>
430
+ </div>
431
+ )}
432
+ </div>
433
+ </div>
434
+
435
+ <div className="container">
436
+ <img src={logo} alt="Sesli AI Logosu" className="logo" />
437
+ <h1>Duygu Doğrulama</h1>
438
+ <p className="subtitle">Sesinizi canlı kaydedin veya dosya yükleyin; duygu sonucu ve öneriler burada görünecek.</p>
439
+
440
+ {currentProfile && (
441
+ <div className="user-info">
442
+ <span><strong>Ad Soyad:</strong> {currentProfile.fullName}</span>
443
+ <span><strong>Telefon:</strong> {currentProfile.basePhone}</span>
444
+ <span><strong>Paket:</strong> {currentProfile.packageName}</span>
445
+ <span><strong>Rol:</strong> {currentProfile.role === 'owner' ? 'Hat Sahibi' : 'Kullanıcı'}</span>
446
+ </div>
447
+ )}
448
+
449
+ <div className="controls">
450
+ <button className="button" onClick={startStopListening}>{isListening ? '⏹️ Durdur' : '🎤 Canlı Analiz'}</button>
451
+ <label htmlFor="emotion-file" className="button upload-button">📁 Dosya Yükle</label>
452
+ <input id="emotion-file" type="file" accept="audio/*" onChange={handleFileChange} style={{ display: 'none' }} />
453
+ <button className="button emotion-button" onClick={handleSpeechAnalysis}>🗣️ Konuşma Analizi</button>
454
+ <button className="button emotion-button" onClick={onBack}>Geri</button>
455
+ </div>
456
+
457
+ {audioUrl && (
458
+ <div className="audio-player-container">
459
+ <audio
460
+ className="custom-audio"
461
+ controls
462
+ src={audioUrl}
463
+ />
464
+ </div>
465
+ )}
466
+
467
+ <div className="status">Durum: <span>{status}</span></div>
468
+
469
+ {/* Emojiler */}
470
+ <div className="emojis-grid">
471
+ {emojis.map((e) => (
472
+ <div
473
+ key={e.label}
474
+ className={`emoji-card ${activeEmotion === e.label ? 'active' : ''}`}
475
+ >
476
+ <div className="emoji-icon">{e.icon}</div>
477
+ <div className="emoji-label">{e.label}</div>
478
+ </div>
479
+ ))}
480
+ </div>
481
+
482
+ {/* Aktif Duygu Kutu */}
483
+ {/* Aktif Duygu Kutu */}
484
+ {activeEmotion && (
485
+ <div className="active-emotion-badge">
486
+ <span className="emotion-title">Aktif Duygu:</span>
487
+ <span className="emotion-value">{activeEmotion}</span>
488
+ </div>
489
+ )}
490
+
491
+ {/* Öneriler */}
492
+ {/* Öneriler */}
493
+ {activeEmotion && (
494
+ <div className="recommendations-section">
495
+ <h2 className="recommendations-title">Öneriler</h2>
496
+ <div className="recommendations-grid">
497
+ {getRecommendations().map((c, idx) => (
498
+ <div key={`${c.title}-${idx}`} className="recommendation-card">
499
+ <div className="rec-title">{c.title}</div>
500
+ <div className="rec-price">{c.price}</div>
501
+ <div className="rec-desc">{c.desc}</div>
502
+ <button className="button small-button">Öner</button>
503
+ </div>
504
+ ))}
505
+ </div>
506
+ </div>
507
+ )}
508
+
509
+ {speechText && (
510
+ <div className="file-info" style={{ textAlign: 'left' }}>
511
+ <strong>Konuşma Analizi:</strong> {speechText}
512
+ </div>
513
+ )}
514
+ </div>
515
+ </div>
516
+ );
517
+ };
518
+
519
+ export default EmotionVerificationPage;
frontend/src/ManagementPage.jsx ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef } from 'react';
2
+ import './App.css';
3
+ import toWav from 'audiobuffer-to-wav';
4
+ import AudioVisualizer from './AudioVisualizer.jsx';
5
+ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
6
+ import { faMicrophone, faStop, faUserPlus, faArrowLeft, faCheck, faTimes, faPlus, faX } from '@fortawesome/free-solid-svg-icons';
7
+ import logo from './DualMind_Logo.png';
8
+
9
+ const ManagementPage = ({ verification, onBack, onOpenEmotion }) => {
10
+ // Seed subscribers: 5 Hat Sahibi + 5 Kullanıcı (same numbers, different names, same package)
11
+ const SEED_SUBSCRIBERS = [
12
+ { basePhone: '05327678989', role: 'owner', fullName: 'Mehmet Şimşek', packageName: 'GNC 30 GB' },
13
+ { basePhone: '05327678989', role: 'user', fullName: 'Derya Şimşek', packageName: 'GNC 30 GB' },
14
+ { basePhone: '05321234567', role: 'owner', fullName: 'Ayşe Yılmaz', packageName: 'GNC 20 GB' },
15
+ { basePhone: '05321234567', role: 'user', fullName: 'Ali Yılmaz', packageName: 'GNC 20 GB' },
16
+ { basePhone: '05339876543', role: 'owner', fullName: 'Can Demir', packageName: 'Platinum 40 GB' },
17
+ { basePhone: '05339876543', role: 'user', fullName: 'Elif Demir', packageName: 'Platinum 40 GB' },
18
+ { basePhone: '05325556677', role: 'owner', fullName: 'Fatma Kaya', packageName: 'Super 10 GB' },
19
+ { basePhone: '05325556677', role: 'user', fullName: 'Mert Kaya', packageName: 'Super 10 GB' },
20
+ { basePhone: '05329991122', role: 'owner', fullName: 'Zeynep Acar', packageName: 'GNC 8 GB' },
21
+ { basePhone: '05418065249', role: 'owner', fullName: 'İlayda Özdemir', packageName: 'GNC 30 GB' },
22
+ { basePhone: '05329991122', role: 'user', fullName: 'Burak Acar', packageName: 'GNC 8 GB' },
23
+ ].map(s => ({
24
+ ...s,
25
+ suffix: s.role === 'owner' ? 'HatSahibi' : 'Kullanici',
26
+ combinedName: `${s.basePhone}${s.role === 'owner' ? 'HatSahibi' : 'Kullanici'}`,
27
+ }));
28
+
29
+ const [status, setStatus] = useState('Hazır');
30
+ const [result, setResult] = useState(null);
31
+ const [showPopup, setShowPopup] = useState(false);
32
+ const [isRecording, setIsRecording] = useState(false);
33
+ const mediaRecorderRef = useRef(null);
34
+ const [audioData, setAudioData] = useState(null);
35
+ const [selectedFiles, setSelectedFiles] = useState([]);
36
+ const [formData, setFormData] = useState({
37
+ fullName: '',
38
+ phoneNumber: '',
39
+ role: 'owner',
40
+ packageName: 'GNC 30 GB'
41
+ });
42
+ const [subscribers, setSubscribers] = useState(() => {
43
+ // localStorage'dan kayıtlı aboneleri yükle
44
+ const saved = localStorage.getItem('subscribers');
45
+ return saved ? JSON.parse(saved) : [];
46
+ });
47
+ const API_URL = 'http://localhost:8000';
48
+
49
+ // Tüm aboneleri birleştir (SEED + Yeni eklenenler)
50
+ const allSubscribers = [
51
+ ...SEED_SUBSCRIBERS,
52
+ ...subscribers
53
+ ];
54
+ const currentCombined = verification?.expectedName;
55
+ const currentProfile = currentCombined
56
+ ? allSubscribers.find(s => s.combinedName === currentCombined)
57
+ : null;
58
+
59
+
60
+ const handleRecordStart = async () => {
61
+ if (isRecording) return;
62
+ try {
63
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
64
+ setAudioData(stream);
65
+ const chunks = [];
66
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/wav';
67
+ mediaRecorderRef.current = new MediaRecorder(stream, { mimeType });
68
+
69
+ mediaRecorderRef.current.ondataavailable = (event) => { chunks.push(event.data); };
70
+ mediaRecorderRef.current.onstop = async () => {
71
+ const audioBlob = new Blob(chunks, { type: mediaRecorderRef.current.mimeType });
72
+ const arrayBuffer = await audioBlob.arrayBuffer();
73
+ const audioCtx = new AudioContext();
74
+ const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
75
+ const wavBuffer = toWav(audioBuffer);
76
+ const wavBlob = new Blob([wavBuffer], { type: 'audio/wav' });
77
+ const wavFile = new File([wavBlob], 'recorded_audio.wav', { type: 'audio/wav' });
78
+ const tracks = stream.getTracks();
79
+ tracks.forEach(track => track.stop());
80
+ setAudioData(null);
81
+ setSelectedFiles(prev => [...prev, wavFile]);
82
+ setStatus('Kayıt eklendi. Göndermek için Kaydet butonunu kullanın.');
83
+ };
84
+
85
+ mediaRecorderRef.current.start();
86
+ setIsRecording(true);
87
+ setStatus('Kayıt başlatıldı...');
88
+ } catch (err) {
89
+ console.error('Mikrofon erişim hatası:', err);
90
+ setStatus('Mikrofon erişim hatası!');
91
+ }
92
+ };
93
+
94
+ const handleRecordStop = () => {
95
+ if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
96
+ mediaRecorderRef.current.stop();
97
+ setIsRecording(false);
98
+ setStatus('Kayıt durduruldu.');
99
+ }
100
+ };
101
+
102
+ const handleFileUpload = (event) => {
103
+ const files = Array.from(event.target.files || []);
104
+ if (files.length > 0) {
105
+ setSelectedFiles(prev => [...prev, ...files]);
106
+ setStatus(`${files.length} dosya eklendi.`);
107
+ }
108
+ };
109
+
110
+ const handleSave = async () => {
111
+ if (!formData.fullName || !formData.phoneNumber || selectedFiles.length === 0) {
112
+ setStatus('Lütfen tüm alanları doldurun ve ses kaydedin/yükleyin.');
113
+ return;
114
+ }
115
+ const suffix = formData.role === 'owner' ? 'HatSahibi' : 'Kullanici';
116
+ const combinedName = `${formData.phoneNumber}${suffix}`;
117
+ const apiFormData = new FormData();
118
+ apiFormData.append('name', combinedName);
119
+ apiFormData.append('role', formData.role);
120
+ selectedFiles.forEach((file, idx) => {
121
+ const ext = (file.type && file.type.split('/')[1]) || 'wav';
122
+ apiFormData.append('audio_files', file, `${formData.phoneNumber}_${idx}.${ext}`);
123
+ });
124
+
125
+ try {
126
+ const response = await fetch(`${API_URL}/register/?name=${combinedName}&role=${formData.role}`, { method: 'POST', body: apiFormData });
127
+ const data = await response.json();
128
+ if (response.ok) {
129
+ // Sözlük yapısına kaydet
130
+ const newSubscriber = {
131
+ basePhone: formData.phoneNumber,
132
+ role: formData.role,
133
+ fullName: formData.fullName,
134
+ packageName: formData.packageName,
135
+ suffix: suffix,
136
+ combinedName: combinedName
137
+ };
138
+
139
+ setSubscribers(prev => {
140
+ const updated = [...prev, newSubscriber];
141
+ // localStorage'a kaydet
142
+ localStorage.setItem('subscribers', JSON.stringify(updated));
143
+ console.log('Yeni Eklenen Aboneler:', updated);
144
+ console.log('Tüm Aboneler (SEED + Yeni):', [...SEED_SUBSCRIBERS, ...updated]);
145
+ return updated;
146
+ });
147
+
148
+ setStatus(`Konuşmacı '${combinedName}' başarıyla kaydedildi!`);
149
+ setResult({ type: 'success', message: `Konuşmacı '${combinedName}' başarıyla kaydedildi!` });
150
+ setShowPopup(false);
151
+ setSelectedFiles([]);
152
+ setFormData({ fullName: '', phoneNumber: '', role: 'owner', packageName: 'GNC 30 GB' });
153
+ } else {
154
+ setStatus('Kayıt işlemi başarısız oldu.');
155
+ setResult({ type: 'error', message: data.error || 'Bilinmeyen Hata' });
156
+ }
157
+ } catch (error) {
158
+ console.error('Kayıt API çağrısı sırasında hata:', error);
159
+ setStatus('Sunucuya bağlanırken hata oluştu.');
160
+ setResult({ type: 'error', message: 'Sunucuya bağlanırken hata oluştu.' });
161
+ }
162
+ };
163
+
164
+
165
+ return (
166
+ <div className="App">
167
+ <div className="container">
168
+ <img src={logo} alt="Sesli AI Logosu" className="logo" />
169
+ <h1>Konuşmacı Yönetimi(Müşteri Temsilcisi Sayfası)</h1>
170
+
171
+ {currentProfile && (
172
+ <div className="user-info">
173
+ <span><strong>Ad Soyad:</strong> {currentProfile.fullName}</span>
174
+ <span><strong>Telefon:</strong> {currentProfile.basePhone}</span>
175
+ <span><strong>Paket:</strong> {currentProfile.packageName}</span>
176
+ <span><strong>Rol:</strong> {currentProfile.role === 'owner' ? 'Hat Sahibi' : 'Kullanıcı'}</span>
177
+ </div>
178
+ )}
179
+
180
+ {verification && (
181
+ <div className={`result result-${verification.isVerified ? 'success' : 'error'}`}>
182
+ {verification.isVerified ? (
183
+ <>
184
+ <FontAwesomeIcon icon={faCheck} style={{ marginRight: '8px' }} />
185
+ {`Doğrulandı (%${verification.confidence})`}
186
+ </>
187
+ ) : (
188
+ <>
189
+ <FontAwesomeIcon icon={faTimes} style={{ marginRight: '8px' }} />
190
+ {`Doğrulanamadı (%${verification.confidence})`}
191
+ </>
192
+ )}
193
+ </div>
194
+ )}
195
+
196
+ <p className="subtitle">Yeni kayıt eklemek için aşağıdaki butona tıklayın.</p>
197
+
198
+ <div className="controls">
199
+ <button className="button" onClick={() => setShowPopup(true)}>
200
+ <FontAwesomeIcon icon={faPlus} style={{ marginRight: '8px' }} />Kayıt Ekle
201
+ </button>
202
+
203
+ <button className="button" onClick={onOpenEmotion}>
204
+ Duygu Doğrulama
205
+ </button>
206
+
207
+ <button className="button emotion-button" onClick={onBack}>
208
+ <FontAwesomeIcon icon={faArrowLeft} style={{ marginRight: '8px' }} />Doğrulamaya Dön
209
+ </button>
210
+ </div>
211
+
212
+ <div className="status">Durum: <span>{status}</span></div>
213
+ {result && (<div className={`result result-${result.type}`}>{result.message}</div>)}
214
+
215
+ {/* Popup Modal */}
216
+ {showPopup && (
217
+ <div className="popup-overlay">
218
+ <div className="popup-content">
219
+ <div className="popup-header">
220
+ <h2>Yeni Kayıt Ekle</h2>
221
+ <button className="close-button" onClick={() => setShowPopup(false)}>
222
+ <FontAwesomeIcon icon={faX} />
223
+ </button>
224
+ </div>
225
+
226
+ <div className="popup-body">
227
+ <div className="form-group">
228
+ <label>Ad Soyad:</label>
229
+ <input
230
+ type="text"
231
+ value={formData.fullName}
232
+ onChange={(e) => setFormData({...formData, fullName: e.target.value})}
233
+ placeholder="Ad Soyad girin"
234
+ />
235
+ </div>
236
+
237
+ <div className="form-group">
238
+ <label>Telefon Numarası:</label>
239
+ <input
240
+ type="text"
241
+ value={formData.phoneNumber}
242
+ onChange={(e) => setFormData({...formData, phoneNumber: e.target.value})}
243
+ placeholder="0532XXXXXXXX"
244
+ />
245
+ </div>
246
+
247
+ <div className="form-group">
248
+ <label>Rol:</label>
249
+ <select value={formData.role} onChange={(e) => setFormData({...formData, role: e.target.value})}>
250
+ <option value="owner">Hat Sahibi</option>
251
+ <option value="user">Kullanıcı</option>
252
+ </select>
253
+ </div>
254
+
255
+ <div className="form-group">
256
+ <label>Paket:</label>
257
+ <select value={formData.packageName} onChange={(e) => setFormData({...formData, packageName: e.target.value})}>
258
+ <option value="GNC 30 GB">GNC 30 GB</option>
259
+ <option value="GNC 20 GB">GNC 20 GB</option>
260
+ <option value="Platinum 40 GB">Platinum 40 GB</option>
261
+ <option value="Super 10 GB">Super 10 GB</option>
262
+ <option value="GNC 8 GB">GNC 8 GB</option>
263
+ </select>
264
+ </div>
265
+
266
+ <div className="audio-controls">
267
+ <div className="recording-controls">
268
+ {!isRecording && (
269
+ <button className="button small-button record-button" onClick={handleRecordStart}>
270
+ <FontAwesomeIcon icon={faMicrophone} />
271
+ Kayıt Başlat
272
+ </button>
273
+ )}
274
+ {isRecording && (
275
+ <button className="button small-button stop-button recording" onClick={handleRecordStop}>
276
+ <FontAwesomeIcon icon={faStop} />
277
+ Kayıt Durdur
278
+ </button>
279
+ )}
280
+ </div>
281
+
282
+ <input type="file" id="audio-upload-popup" accept="audio/*" multiple onChange={handleFileUpload} style={{ display: 'none' }} />
283
+ <label htmlFor="audio-upload-popup" className="button">Dosya Yükle</label>
284
+ </div>
285
+
286
+ {isRecording && audioData && <AudioVisualizer audioData={audioData} />}
287
+
288
+ {selectedFiles.length > 0 && (
289
+ <div className="file-info">
290
+ 🎵 Seçilen Dosyalar: <strong>{selectedFiles.map(f => f.name).join(', ')}</strong>
291
+ </div>
292
+ )}
293
+ </div>
294
+
295
+ <div className="popup-footer">
296
+ <button className="button" onClick={() => setShowPopup(false)}>
297
+ İptal
298
+ </button>
299
+ <button
300
+ className="button emotion-button"
301
+ onClick={handleSave}
302
+ disabled={!formData.fullName || !formData.phoneNumber || selectedFiles.length === 0}
303
+ >
304
+ <FontAwesomeIcon icon={faUserPlus} style={{ marginRight: '8px' }} />
305
+ Kaydet
306
+ </button>
307
+ </div>
308
+ </div>
309
+ </div>
310
+ )}
311
+ </div>
312
+ </div>
313
+ );
314
+ };
315
+
316
+ export default ManagementPage;
frontend/src/ThemeContext.jsx ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { createContext, useContext, useState, useEffect } from 'react';
2
+
3
+ const ThemeContext = createContext();
4
+
5
+ export const useTheme = () => {
6
+ const context = useContext(ThemeContext);
7
+ if (!context) {
8
+ throw new Error('useTheme must be used within a ThemeProvider');
9
+ }
10
+ return context;
11
+ };
12
+
13
+ export const ThemeProvider = ({ children }) => {
14
+ // localStorage'dan tema tercihini oku, varsayılan: 'light' (beyaz)
15
+ const [theme, setTheme] = useState(() => {
16
+ const savedTheme = localStorage.getItem('sesleai-theme');
17
+ return savedTheme || 'light';
18
+ });
19
+
20
+ useEffect(() => {
21
+ // HTML root elemanına tema attribute'u ekle
22
+ document.documentElement.setAttribute('data-theme', theme);
23
+ // localStorage'a kaydet
24
+ localStorage.setItem('sesleai-theme', theme);
25
+ }, [theme]);
26
+
27
+ const toggleTheme = () => {
28
+ setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
29
+ };
30
+
31
+ const value = {
32
+ theme,
33
+ toggleTheme,
34
+ isDark: theme === 'dark',
35
+ isLight: theme === 'light'
36
+ };
37
+
38
+ return (
39
+ <ThemeContext.Provider value={value}>
40
+ {children}
41
+ </ThemeContext.Provider>
42
+ );
43
+ };
44
+
45
+ export default ThemeContext;
frontend/src/ThemeToggle.css ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Theme Toggle Styles */
2
+ .theme-toggle {
3
+ position: fixed;
4
+ top: 20px;
5
+ right: 20px;
6
+ z-index: 1000;
7
+ background: none;
8
+ border: none;
9
+ cursor: pointer;
10
+ padding: 0;
11
+ outline: none;
12
+ }
13
+
14
+ .toggle-track {
15
+ width: 70px;
16
+ height: 36px;
17
+ border-radius: 18px;
18
+ position: relative;
19
+ overflow: hidden;
20
+ transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
21
+ box-shadow:
22
+ 0 4px 20px rgba(0, 0, 0, 0.2),
23
+ inset 0 -2px 10px rgba(0, 0, 0, 0.1),
24
+ inset 0 2px 10px rgba(255, 255, 255, 0.2);
25
+ }
26
+
27
+ /* Light mode track (sky blue gradient) */
28
+ .theme-toggle.light .toggle-track {
29
+ background: linear-gradient(180deg, #87CEEB 0%, #4FC3F7 50%, #81D4FA 100%);
30
+ border: 2px solid rgba(255, 255, 255, 0.4);
31
+ }
32
+
33
+ /* Dark mode track (night sky gradient) */
34
+ .theme-toggle.dark .toggle-track {
35
+ background: linear-gradient(180deg, #1a237e 0%, #0a0e35 50%, #121858 100%);
36
+ border: 2px solid rgba(255, 193, 7, 0.3);
37
+ }
38
+
39
+ .toggle-thumb {
40
+ position: absolute;
41
+ width: 28px;
42
+ height: 28px;
43
+ border-radius: 50%;
44
+ top: 4px;
45
+ z-index: 10;
46
+ /* Thumb always on top */
47
+ transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
48
+ display: flex;
49
+ align-items: center;
50
+ justify-content: center;
51
+ box-shadow:
52
+ 0 2px 10px rgba(0, 0, 0, 0.3),
53
+ 0 0 20px rgba(255, 193, 7, 0.2);
54
+ }
55
+
56
+ /* Light mode thumb (sun) */
57
+ .theme-toggle.light .toggle-thumb {
58
+ left: 4px;
59
+ background: linear-gradient(135deg, #FFF9C4 0%, #FFD54F 50%, #FFC107 100%);
60
+ box-shadow:
61
+ 0 0 20px rgba(255, 193, 7, 0.6),
62
+ 0 0 40px rgba(255, 193, 7, 0.3),
63
+ inset 0 -2px 5px rgba(255, 152, 0, 0.3);
64
+ }
65
+
66
+ /* Dark mode thumb (moon) */
67
+ .theme-toggle.dark .toggle-thumb {
68
+ left: 38px;
69
+ background: linear-gradient(135deg, #E8EAF6 0%, #C5CAE9 50%, #9FA8DA 100%);
70
+ box-shadow:
71
+ 0 0 15px rgba(197, 202, 233, 0.5),
72
+ 0 0 30px rgba(159, 168, 218, 0.3);
73
+ }
74
+
75
+ .toggle-icon {
76
+ font-size: 14px;
77
+ transition: all 0.4s ease;
78
+ }
79
+
80
+ .theme-toggle.light .toggle-icon {
81
+ color: #FF8F00;
82
+ }
83
+
84
+ .theme-toggle.dark .toggle-icon {
85
+ color: #5C6BC0;
86
+ }
87
+
88
+ /* Stars animation for dark mode */
89
+ .toggle-stars {
90
+ position: absolute;
91
+ width: 100%;
92
+ height: 100%;
93
+ pointer-events: none;
94
+ z-index: 5;
95
+ /* Stars behind thumb */
96
+ }
97
+
98
+ .star {
99
+ position: absolute;
100
+ color: #FFF9C4;
101
+ font-size: 8px;
102
+ opacity: 0;
103
+ animation: twinkle 1.5s infinite;
104
+ }
105
+
106
+ .theme-toggle.dark .star {
107
+ opacity: 1;
108
+ }
109
+
110
+ .star-1 {
111
+ top: 8px;
112
+ left: 10px;
113
+ /* Moved to left side */
114
+ animation-delay: 0s;
115
+ }
116
+
117
+ .star-2 {
118
+ top: 20px;
119
+ left: 18px;
120
+ /* Moved to left side */
121
+ animation-delay: 0.5s;
122
+ font-size: 6px;
123
+ }
124
+
125
+ .star-3 {
126
+ top: 12px;
127
+ left: 28px;
128
+ /* Moved to left side */
129
+ animation-delay: 1s;
130
+ font-size: 10px;
131
+ }
132
+
133
+ @keyframes twinkle {
134
+
135
+ 0%,
136
+ 100% {
137
+ opacity: 0.3;
138
+ transform: scale(1);
139
+ }
140
+
141
+ 50% {
142
+ opacity: 1;
143
+ transform: scale(1.2);
144
+ }
145
+ }
146
+
147
+ /* Clouds animation for light mode */
148
+ .toggle-clouds {
149
+ position: absolute;
150
+ width: 100%;
151
+ height: 100%;
152
+ pointer-events: none;
153
+ }
154
+
155
+ .cloud {
156
+ position: absolute;
157
+ color: rgba(255, 255, 255, 0.8);
158
+ font-size: 12px;
159
+ opacity: 0;
160
+ transition: opacity 0.3s ease;
161
+ }
162
+
163
+ .theme-toggle.light .cloud {
164
+ opacity: 1;
165
+ animation: float-cloud 3s infinite ease-in-out;
166
+ }
167
+
168
+ .cloud-1 {
169
+ top: 4px;
170
+ right: 8px;
171
+ animation-delay: 0s;
172
+ }
173
+
174
+ .cloud-2 {
175
+ top: 16px;
176
+ right: 16px;
177
+ font-size: 10px;
178
+ animation-delay: 1.5s;
179
+ }
180
+
181
+ @keyframes float-cloud {
182
+
183
+ 0%,
184
+ 100% {
185
+ transform: translateX(0);
186
+ }
187
+
188
+ 50% {
189
+ transform: translateX(3px);
190
+ }
191
+ }
192
+
193
+ /* Hover effect */
194
+ .theme-toggle:hover .toggle-track {
195
+ transform: scale(1.05);
196
+ box-shadow:
197
+ 0 6px 25px rgba(0, 0, 0, 0.3),
198
+ inset 0 -2px 10px rgba(0, 0, 0, 0.1),
199
+ inset 0 2px 10px rgba(255, 255, 255, 0.2);
200
+ }
201
+
202
+ .theme-toggle:hover .toggle-thumb {
203
+ transform: scale(1.1);
204
+ }
205
+
206
+ /* Focus state for accessibility */
207
+ .theme-toggle:focus-visible .toggle-track {
208
+ outline: 3px solid var(--turkcell-yellow);
209
+ outline-offset: 3px;
210
+ }
frontend/src/ThemeToggle.jsx ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTheme } from './ThemeContext';
3
+ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
4
+ import { faSun, faMoon } from '@fortawesome/free-solid-svg-icons';
5
+ import './ThemeToggle.css';
6
+
7
+ const ThemeToggle = () => {
8
+ const { theme, toggleTheme, isDark } = useTheme();
9
+
10
+ return (
11
+ <button
12
+ className={`theme-toggle ${isDark ? 'dark' : 'light'}`}
13
+ onClick={toggleTheme}
14
+ aria-label={`Switch to ${isDark ? 'light' : 'dark'} mode`}
15
+ title={isDark ? 'Açık Moda Geç' : 'Koyu Moda Geç'}
16
+ >
17
+ <div className="toggle-track">
18
+ <div className="toggle-thumb">
19
+ <FontAwesomeIcon
20
+ icon={isDark ? faMoon : faSun}
21
+ className="toggle-icon"
22
+ />
23
+ </div>
24
+ <div className="toggle-stars">
25
+ {isDark && (
26
+ <>
27
+ <span className="star star-1">✦</span>
28
+ <span className="star star-2">✦</span>
29
+ <span className="star star-3">✧</span>
30
+ </>
31
+ )}
32
+ </div>
33
+ <div className="toggle-clouds">
34
+ {!isDark && (
35
+ <>
36
+ <span className="cloud cloud-1">☁</span>
37
+ <span className="cloud cloud-2">☁</span>
38
+ </>
39
+ )}
40
+ </div>
41
+ </div>
42
+ </button>
43
+ );
44
+ };
45
+
46
+ export default ThemeToggle;
frontend/src/VerificationPage.jsx ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef } from 'react';
2
+ import './App.css';
3
+ import toWav from 'audiobuffer-to-wav';
4
+ import AudioVisualizer from './AudioVisualizer.jsx';
5
+ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
6
+ import { faMicrophone, faStop } from '@fortawesome/free-solid-svg-icons';
7
+ import logo from './DualMind_Logo.png';
8
+ import { API_CONFIG } from './config.js';
9
+
10
+ const VerificationPage = ({ onVerified }) => {
11
+ const [status, setStatus] = useState('Hazır');
12
+ const [isRecording, setIsRecording] = useState(false);
13
+ const mediaRecorderRef = useRef(null);
14
+ const [audioData, setAudioData] = useState(null);
15
+ const [speakerName, setSpeakerName] = useState('');
16
+ const [role, setRole] = useState('owner'); // 'owner' (Hat Sahibi) | 'user' (Kullanıcı)
17
+ const API_URL = API_CONFIG.SES_API;
18
+
19
+ const sendAudioToApi = async (audioBlob) => {
20
+ if (!speakerName) {
21
+ setStatus('Lütfen doğrulanacak numarayı girin.');
22
+ return;
23
+ }
24
+
25
+ setStatus('Ses analizi için API\'ye gönderiliyor...');
26
+ const formData = new FormData();
27
+ const fileExtension = audioBlob.type.split('/')[1] || 'wav';
28
+ formData.append('audio_file', audioBlob, `audio.${fileExtension}`);
29
+
30
+ try {
31
+ const response = await fetch(`${API_URL}/recognize/?role=${role}`, { method: 'POST', body: formData });
32
+ const data = await response.json();
33
+ const confidencePct = (data?.confidence ? (data.confidence * 100) : 0).toFixed(2);
34
+ const suffix = role === 'owner' ? 'HatSahibi' : 'Kullanici';
35
+ const expectedName = `${speakerName}${suffix}`;
36
+ const isVerified = response.ok && data?.speaker === expectedName;
37
+ onVerified({
38
+ inputName: speakerName,
39
+ apiSpeaker: data?.speaker || null,
40
+ confidence: confidencePct,
41
+ isVerified,
42
+ message: isVerified ? `Doğrulandı (%${confidencePct})` : `Doğrulanamadı (%${confidencePct})`,
43
+ role,
44
+ expectedName
45
+ });
46
+ } catch (error) {
47
+ console.error('API çağrısı sırasında hata:', error);
48
+ const suffix = role === 'owner' ? 'HatSahibi' : 'Kullanici';
49
+ const expectedName = `${speakerName}${suffix}`;
50
+ onVerified({ inputName: speakerName, apiSpeaker: null, confidence: '0.00', isVerified: false, message: 'Sunucu hatası', role, expectedName });
51
+ }
52
+ };
53
+
54
+ const handleRecordStart = async () => {
55
+ if (isRecording) return;
56
+ try {
57
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
58
+ setAudioData(stream);
59
+ const chunks = [];
60
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/wav';
61
+ mediaRecorderRef.current = new MediaRecorder(stream, { mimeType });
62
+
63
+ mediaRecorderRef.current.ondataavailable = (event) => { chunks.push(event.data); };
64
+ mediaRecorderRef.current.onstop = async () => {
65
+ const audioBlob = new Blob(chunks, { type: mediaRecorderRef.current.mimeType });
66
+ const arrayBuffer = await audioBlob.arrayBuffer();
67
+ const audioCtx = new AudioContext();
68
+ const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
69
+ const wavBuffer = toWav(audioBuffer);
70
+ const wavBlob = new Blob([wavBuffer], { type: 'audio/wav' });
71
+ const wavFile = new File([wavBlob], 'recorded_audio.wav', { type: 'audio/wav' });
72
+ stream.getTracks().forEach(track => track.stop());
73
+ setAudioData(null);
74
+ sendAudioToApi(wavFile);
75
+ };
76
+
77
+ mediaRecorderRef.current.start();
78
+ setIsRecording(true);
79
+ setStatus('Kayıt başlatıldı...');
80
+ } catch (err) {
81
+ console.error('Mikrofon erişim hatası:', err);
82
+ setStatus('Mikrofon erişim hatası!');
83
+ }
84
+ };
85
+
86
+ const handleRecordStop = () => {
87
+ if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
88
+ mediaRecorderRef.current.stop();
89
+ setIsRecording(false);
90
+ setStatus('Kayıt durduruldu.');
91
+ }
92
+ };
93
+
94
+ const handleFileUpload = (event) => {
95
+ const file = event.target.files[0];
96
+ if (file) {
97
+ sendAudioToApi(file);
98
+ }
99
+ };
100
+
101
+ return (
102
+ <div className="App">
103
+ <div className="container">
104
+ <img src={logo} alt="Sesli AI Logosu" className="logo" />
105
+ <h1>Kimlik Doğrulama</h1>
106
+ <p className="subtitle">Sadece numara girin ve ses yükleyin ya da kaydedin</p>
107
+
108
+ <div className="verification-form">
109
+ {/* Input Section */}
110
+ <div className="form-section">
111
+ <div className="input-group">
112
+ <label className="input-label">Telefon Numarası</label>
113
+ <input
114
+ type="text"
115
+ placeholder="0532 XXX XX XX"
116
+ value={speakerName}
117
+ onChange={(e) => setSpeakerName(e.target.value)}
118
+ className="speaker-input modern-input"
119
+ />
120
+ </div>
121
+
122
+ <div className="input-group">
123
+ <label className="input-label">Doğrulama Türü</label>
124
+ <div className="role-toggle">
125
+ <button
126
+ className={`role-option ${role === 'owner' ? 'active' : ''}`}
127
+ onClick={() => setRole('owner')}
128
+ type="button"
129
+ >
130
+ <span className="role-icon">👤</span>
131
+ Hat Sahibi
132
+ </button>
133
+ <button
134
+ className={`role-option ${role === 'user' ? 'active' : ''}`}
135
+ onClick={() => setRole('user')}
136
+ type="button"
137
+ >
138
+ <span className="role-icon">👥</span>
139
+ Kullanıcı
140
+ </button>
141
+ </div>
142
+ </div>
143
+ </div>
144
+
145
+ {/* Action Buttons */}
146
+ <div className="action-buttons">
147
+ {!isRecording ? (
148
+ <button className="button action-button record-btn" onClick={handleRecordStart}>
149
+ <FontAwesomeIcon icon={faMicrophone} />
150
+ <span>Ses Kaydet</span>
151
+ </button>
152
+ ) : (
153
+ <button className="button action-button stop-btn recording" onClick={handleRecordStop}>
154
+ <FontAwesomeIcon icon={faStop} />
155
+ <span>Kaydı Durdur</span>
156
+ </button>
157
+ )}
158
+
159
+ <div className="divider-text">veya</div>
160
+
161
+ <input type="file" id="audio-upload" accept="audio/*" onChange={handleFileUpload} style={{ display: 'none' }} />
162
+ <label htmlFor="audio-upload" className="button action-button upload-btn">
163
+ <span>📁</span>
164
+ <span>Dosya Yükle</span>
165
+ </label>
166
+ </div>
167
+ </div>
168
+
169
+ {isRecording && audioData && <AudioVisualizer audioData={audioData} />}
170
+
171
+ <div className="status">Durum: <span>{status}</span></div>
172
+ </div>
173
+ </div>
174
+ );
175
+ };
176
+
177
+ export default VerificationPage;
frontend/src/assets/react.svg ADDED
frontend/src/config.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // API Configuration for different environments
2
+ const isDev = import.meta.env.DEV;
3
+
4
+ export const API_CONFIG = {
5
+ // In development, use localhost URLs
6
+ // In production (HF Spaces), use relative paths (nginx proxies to backends)
7
+ SES_API: isDev ? 'http://localhost:8000' : '/api/ses',
8
+ DUYGU_API: isDev ? 'http://127.0.0.1:8001' : '/api/duygu'
9
+ };
frontend/src/index.css ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
3
+ line-height: 1.5;
4
+ font-weight: 400;
5
+
6
+ color-scheme: light dark;
7
+ color: rgba(255, 255, 255, 0.87);
8
+ background-color: #242424;
9
+
10
+ font-synthesis: none;
11
+ text-rendering: optimizeLegibility;
12
+ -webkit-font-smoothing: antialiased;
13
+ -moz-osx-font-smoothing: grayscale;
14
+ }
15
+
16
+ a {
17
+ font-weight: 500;
18
+ color: #646cff;
19
+ text-decoration: inherit;
20
+ }
21
+ a:hover {
22
+ color: #535bf2;
23
+ }
24
+
25
+ body {
26
+ margin: 0;
27
+ display: flex;
28
+ place-items: center;
29
+ min-width: 320px;
30
+ min-height: 100vh;
31
+ }
32
+
33
+ h1 {
34
+ font-size: 3.2em;
35
+ line-height: 1.1;
36
+ }
37
+
38
+ button {
39
+ border-radius: 8px;
40
+ border: 1px solid transparent;
41
+ padding: 0.6em 1.2em;
42
+ font-size: 1em;
43
+ font-weight: 500;
44
+ font-family: inherit;
45
+ background-color: #1a1a1a;
46
+ cursor: pointer;
47
+ transition: border-color 0.25s;
48
+ }
49
+ button:hover {
50
+ border-color: #646cff;
51
+ }
52
+ button:focus,
53
+ button:focus-visible {
54
+ outline: 4px auto -webkit-focus-ring-color;
55
+ }
56
+
57
+ @media (prefers-color-scheme: light) {
58
+ :root {
59
+ color: #213547;
60
+ background-color: #ffffff;
61
+ }
62
+ a:hover {
63
+ color: #747bff;
64
+ }
65
+ button {
66
+ background-color: #f9f9f9;
67
+ }
68
+ }
frontend/src/main.jsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.jsx'
5
+
6
+ createRoot(document.getElementById('root')).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
frontend/vite.config.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+
4
+ // https://vite.dev/config/
5
+ export default defineConfig({
6
+ plugins: [react()],
7
+ })
generate_mock.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import random
3
+
4
+ # Sample data pools
5
+ first_names = ["Ahmet", "Mehmet", "Ayşe", "Fatma", "Ali", "Zeynep", "Mustafa", "Elif", "Can", "Burak", "Cem", "Deniz", "Ece", "Gökhan", "Hakan", "İrem", "Kaan", "Leyla", "Mert", "Nil", "Ozan", "Pınar", "Rüzgar", "Selin", "Tolga", "Umut", "Volkan", "Yağmur", "Zehra"]
6
+ last_names = ["Yılmaz", "Kaya", "Demir", "Çelik", "Şahin", "Yıldız", "Yıldırım", "Öztürk", "Aydın", "Özdemir", "Arslan", "Doğan", "Kılıç", "Aslan", "Çetin", "Kara", "Koç", "Kurt", "Özkan", "Şimşek"]
7
+ packages = ["GNC 30 GB", "GNC 20 GB", "GNC 8 GB", "Platinum 40 GB", "Super 10 GB"]
8
+
9
+ def generate_phone():
10
+ prefixes = ["0530", "0531", "0532", "0533", "0534", "0535", "0536", "0537", "0538", "0539"]
11
+ return random.choice(prefixes) + str(random.randint(1000000, 9999999))
12
+
13
+ def generate_mock_data(count=50):
14
+ users = []
15
+
16
+ # Add specifically requested demo users first if any, or just ensure diversity
17
+ # Let's add the seed users from the frontend for consistency
18
+ seed_users = [
19
+ {"phone": "05327678989", "name": "Mehmet Şimşek", "role": "owner"},
20
+ {"phone": "05327678989", "name": "Derya Şimşek", "role": "user"},
21
+ {"phone": "05321234567", "name": "Ayşe Yılmaz", "role": "owner"},
22
+ {"phone": "05418065249", "name": "İlayda Özdemir", "role": "owner"},
23
+ ]
24
+
25
+ for seed in seed_users:
26
+ users.append({
27
+ "phone_number": seed["phone"],
28
+ "role": seed["role"],
29
+ "full_name": seed["name"],
30
+ "package_name": random.choice(packages),
31
+ "voice_embedding": None # No real voice data for mock users
32
+ })
33
+
34
+ for _ in range(count):
35
+ full_name = f"{random.choice(first_names)} {random.choice(last_names)}"
36
+ phone = generate_phone()
37
+ role = random.choice(["owner", "user"])
38
+ package = random.choice(packages)
39
+
40
+ users.append({
41
+ "phone_number": phone,
42
+ "role": role,
43
+ "full_name": full_name,
44
+ "package_name": package,
45
+ "voice_embedding": None
46
+ })
47
+
48
+ return users
49
+
50
+ if __name__ == "__main__":
51
+ data = generate_mock_data(50)
52
+
53
+ output_path = "backend/api/speakers_db.json"
54
+ with open(output_path, "w", encoding="utf-8") as f:
55
+ json.dump(data, f, ensure_ascii=False, indent=2)
56
+
57
+ print(f"✅ Generated {len(data)} mock users in {output_path}")
nginx.conf ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ events {
2
+ worker_connections 1024;
3
+ }
4
+
5
+ http {
6
+ include /etc/nginx/mime.types;
7
+ default_type application/octet-stream;
8
+
9
+ sendfile on;
10
+ keepalive_timeout 65;
11
+ client_max_body_size 50M;
12
+
13
+ # Upstream for APIs
14
+ upstream ses_api {
15
+ server 127.0.0.1:8000;
16
+ }
17
+
18
+ upstream duygu_api {
19
+ server 127.0.0.1:8001;
20
+ }
21
+
22
+ server {
23
+ listen 7860;
24
+ server_name _;
25
+
26
+ # Root endpoint - Health Check
27
+ location / {
28
+ default_type application/json;
29
+ return 200 '{"status": "running", "message": "SesleAI Backend API is active. Frontend is hosted separately."}';
30
+ }
31
+
32
+ # Speaker Verification API
33
+ location /api/ses/ {
34
+ proxy_pass http://ses_api/;
35
+ proxy_set_header Host $host;
36
+ proxy_set_header X-Real-IP $remote_addr;
37
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
38
+ proxy_set_header X-Forwarded-Proto $scheme;
39
+ proxy_read_timeout 300s;
40
+ proxy_connect_timeout 75s;
41
+ }
42
+
43
+ # Emotion Analysis API
44
+ location /api/duygu/ {
45
+ rewrite ^/api/duygu/(.*) /$1 break;
46
+ proxy_pass http://duygu_api;
47
+ proxy_http_version 1.1;
48
+ proxy_set_header Host $host;
49
+ proxy_set_header X-Real-IP $remote_addr;
50
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
51
+ proxy_set_header X-Forwarded-Proto $scheme;
52
+ proxy_read_timeout 300s;
53
+ proxy_connect_timeout 75s;
54
+ }
55
+
56
+ # Health check
57
+ location /health {
58
+ return 200 'OK';
59
+ add_header Content-Type text/plain;
60
+ }
61
+ }
62
+ }
push_error3.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Uploading LFS objects: 100% (4/4), 738 KB | 0 B/s, done.
2
+ git : remote: -------------------------------
3
+ ------------------------------------------
4
+
5
+ At line:1 char:1
6
+ + git push --force origin main 2>&1 | Out-File -Fi
7
+ lePath push_error3.tx ...
8
+ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9
+ + CategoryInfo : NotSpecified: (remo
10
+ te: --...--- :String) [], Rem
11
+ oteException
12
+ + FullyQualifiedErrorId : NativeCommandError
13
+
14
+ remote: Your push was rejected because it con
15
+ tains files larger than 10 MiB.
16
+ remote: Please use https://git-lfs.github.com
17
+ / to store large files.
18
+ remote: See also: https://hf.co/docs/hub/repo
19
+ sitories-getting-started#terminal
20
+ remote: 
21
+ remote: Offending files:
22
+ remote:  - backend/api/speakers_db.json (ref
23
+ : refs/heads/main)
24
+ remote: -------------------------------------
25
+ ------------------------------------
26
+ To https://huggingface.co/spaces/huseyinemretech/t
27
+ urkcell-proje
28
+ ! [remote rejected] main -> main (pre-receive hoo
29
+ k declined)
30
+ error: failed to push some refs to 'https://huggin
31
+ gface.co/spaces/huseyinemretech/turkcell-proje'
push_final.txt ADDED
Binary file (2.48 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Web Framework
2
+ fastapi>=0.104.0
3
+ uvicorn[standard]>=0.24.0
4
+ python-multipart>=0.0.6
5
+
6
+ # Audio Processing
7
+ librosa>=0.9.0
8
+ soundfile>=0.10.0
9
+ pydub>=0.25.0
10
+ torchaudio>=2.1.0
11
+
12
+ # Machine Learning
13
+ numpy>=1.21.0
14
+ scipy>=1.7.0
15
+ scikit-learn>=1.0.0
16
+
17
+ # Deep Learning
18
+ torch>=2.1.0
19
+ transformers>=4.35.0
20
+
21
+ # SpeechBrain (Speaker Recognition)
22
+ speechbrain>=0.5.0
supervisord.conf ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [supervisord]
2
+ nodaemon=true
3
+ user=root
4
+ logfile=/var/log/supervisor/supervisord.log
5
+ pidfile=/var/run/supervisord.pid
6
+
7
+ [program:nginx]
8
+ command=/usr/sbin/nginx -g "daemon off;"
9
+ autostart=true
10
+ autorestart=true
11
+ stderr_logfile=/var/log/nginx/error.log
12
+ stdout_logfile=/var/log/nginx/access.log
13
+
14
+ [program:ses_api]
15
+ command=python -m uvicorn backend.api.main:app --host 0.0.0.0 --port 8000
16
+ directory=/app
17
+ autostart=true
18
+ autorestart=true
19
+ stderr_logfile=/var/log/ses_api.err.log
20
+ stdout_logfile=/var/log/ses_api.out.log
21
+
22
+ [program:duygu_api]
23
+ command=python -m uvicorn emotion_api.main_w2v:app --host 0.0.0.0 --port 8001
24
+ directory=/app
25
+ autostart=true
26
+ autorestart=true
27
+ stderr_logfile=/var/log/duygu_api.err.log
28
+ stdout_logfile=/var/log/duygu_api.out.log