-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
238 lines (195 loc) · 8.53 KB
/
main.py
File metadata and controls
238 lines (195 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import asyncio
import base64
import io
import os
import traceback
from dotenv import load_dotenv
import pyaudio
import argparse
import math
import struct
import time
import sys
import warnings
import logging
# ==========================================
# AYARLAR
# ==========================================
DEFAULT_MODE = "none" # <--- "none" DEMEK KAMERA YOK, SADECE SES DEMEK
# ==========================================
# --- GÜRÜLTÜ ENGELLEME ---
warnings.filterwarnings("ignore")
logging.getLogger().setLevel(logging.ERROR)
os.environ["GRPC_VERBOSITY"] = "ERROR"
os.environ["GLOG_minloglevel"] = "2"
from google import genai
from google.genai import types
# --- SES AYARLARI ---
FORMAT = pyaudio.paInt16
CHANNELS = 1
SEND_SAMPLE_RATE = 16000
RECEIVE_SAMPLE_RATE = 24000
CHUNK_SIZE = 1024
MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
# Renk Kodları
CYAN = "\033[96m"
YELLOW = "\033[93m"
RESET = "\033[0m"
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
print("HATA: .env dosyasında GEMINI_API_KEY bulunamadı!")
sys.exit(1)
client = genai.Client(http_options={"api_version": "v1beta"}, api_key=api_key)
# Gemini Talimatları
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
system_instruction="Your name is Ada. You are a helpful, witty AI assistant. "
"Interact naturally and concisely. You can be interrupted.",
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name="Kore"
)
)
)
)
pya = pyaudio.PyAudio()
class AudioLoop:
def __init__(self, video_mode=DEFAULT_MODE, input_device_name=None):
self.video_mode = "none" # Zorla "none" yapıyoruz
self.input_device_name = input_device_name
self.audio_in_queue = None
self.out_queue = None
self.session = None
self.stop_event = asyncio.Event()
self._is_speaking = False
self._silence_start_time = None
self._last_input_transcription = ""
self.ada_has_spoken = False
print(f"{YELLOW}[ADA] Kamera Modu KAPALI. Sadece sesli sohbet aktif.{RESET}")
async def send_realtime(self):
while True:
msg = await self.out_queue.get()
await self.session.send(input=msg, end_of_turn=False)
async def listen_audio(self):
mic_info = pya.get_default_input_device_info()
resolved_input_device_index = mic_info["index"]
if self.input_device_name:
count = pya.get_device_count()
for i in range(count):
try:
info = pya.get_device_info_by_index(i)
if info['maxInputChannels'] > 0 and self.input_device_name.lower() in info.get('name', '').lower():
resolved_input_device_index = i
print(f"[ADA] Mikrofon seçildi: {info.get('name')}")
break
except Exception:
continue
try:
self.audio_stream = await asyncio.to_thread(
pya.open, format=FORMAT, channels=CHANNELS, rate=SEND_SAMPLE_RATE, input=True,
input_device_index=resolved_input_device_index, frames_per_buffer=CHUNK_SIZE,
)
except OSError as e:
print(f"[ADA] [HATA] Mikrofon açılamadı: {e}")
return
kwargs = {"exception_on_overflow": False} if __debug__ else {}
VAD_THRESHOLD = 800
SILENCE_DURATION = 0.5
print(f"{CYAN}[ADA] Dinliyor... (Konuşabilirsin){RESET}")
while True:
try:
data = await asyncio.to_thread(self.audio_stream.read, CHUNK_SIZE, **kwargs)
if self.out_queue:
await self.out_queue.put({"data": data, "mime_type": "audio/pcm"})
count = len(data) // 2
rms = 0
if count > 0:
shorts = struct.unpack(f"<{count}h", data)
sum_squares = sum(s**2 for s in shorts)
rms = int(math.sqrt(sum_squares / count))
if rms > VAD_THRESHOLD:
self._silence_start_time = None
if not self._is_speaking:
self._is_speaking = True
else:
if self._is_speaking:
if self._silence_start_time is None:
self._silence_start_time = time.time()
elif time.time() - self._silence_start_time > SILENCE_DURATION:
self._is_speaking = False
self._silence_start_time = None
except Exception as e:
await asyncio.sleep(0.1)
async def receive_audio(self):
try:
while True:
turn = self.session.receive()
async for response in turn:
if data := response.data:
self.audio_in_queue.put_nowait(data)
if response.server_content:
if response.server_content.input_transcription:
transcript = response.server_content.input_transcription.text
if transcript:
if self.ada_has_spoken:
print()
self.ada_has_spoken = False
self._last_input_transcription = ""
if transcript != self._last_input_transcription:
delta = transcript[len(self._last_input_transcription):] if transcript.startswith(self._last_input_transcription) else transcript
self._last_input_transcription = transcript
if delta:
while not self.audio_in_queue.empty():
self.audio_in_queue.get_nowait()
print(f"\r{CYAN}Sen: {transcript}{RESET}", end="", flush=True)
if response.server_content.output_transcription:
self.ada_has_spoken = True
while not self.audio_in_queue.empty():
self.audio_in_queue.get_nowait()
except asyncio.CancelledError:
pass
except Exception as e:
pass
async def play_audio(self):
stream = await asyncio.to_thread(
pya.open, format=FORMAT, channels=CHANNELS, rate=RECEIVE_SAMPLE_RATE, output=True
)
while True:
bytestream = await self.audio_in_queue.get()
await asyncio.to_thread(stream.write, bytestream)
async def run(self):
retry_delay = 1
while not self.stop_event.is_set():
try:
print(f"\n{CYAN}[ADA] Gemini'ye bağlanılıyor...{RESET}")
async with client.aio.live.connect(model=MODEL, config=config) as session:
self.session = session
self.audio_in_queue = asyncio.Queue()
self.out_queue = asyncio.Queue(maxsize=10)
tasks = []
tasks.append(asyncio.create_task(self.send_realtime()))
tasks.append(asyncio.create_task(self.listen_audio()))
# tasks.append(asyncio.create_task(self.get_frames()))
tasks.append(asyncio.create_task(self.receive_audio()))
tasks.append(asyncio.create_task(self.play_audio()))
print(f"{CYAN}[ADA] Bağlantı Hazır! Sadece Ses Modu.{RESET}")
await asyncio.gather(*tasks)
except asyncio.CancelledError:
break
except Exception as e:
print(f"Hata oluştu: {e}")
if self.stop_event.is_set(): break
await asyncio.sleep(retry_delay)
retry_delay = min(retry_delay * 2, 10)
finally:
if hasattr(self, 'audio_stream') and self.audio_stream:
try: self.audio_stream.close()
except: pass
if __name__ == "__main__":
main = AudioLoop(video_mode="none")
try:
asyncio.run(main.run())
except KeyboardInterrupt:
print("\n[ADA] Kapatılıyor...")