Загрузка данных


import json
import os
import webbrowser
import speech_recognition as sr
from gtts import gTTS
import pygame
from google import genai

# Ваш API-ключ встроен сюда
client = genai.Client(api_key="AQ.Ab8RN6I6Y9j9sE5GH8dPNYMtp13I4DGqzthmFvvjJ17UIVZ6fA")

def speak(text):
    print(f"Нова: {text}")
    try:
        tts = gTTS(text=text, lang='ru')
        audio_file = "temp_voice.mp3"
        tts.save(audio_file)
        
        pygame.mixer.init()
        pygame.mixer.music.load(audio_file)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        pygame.mixer.quit()
        
        if os.path.exists(audio_file):
            os.remove(audio_file)
    except Exception as e:
        print(f"Ошибка озвучки: {e}")

def listen():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("\nСлушаю...")
        r.adjust_for_ambient_noise(source, duration=0.5)
        try:
            audio = r.listen(source, timeout=5, phrase_time_limit=10)
        except sr.WaitTimeoutError:
            return ""
            
    try:
        command = r.recognize_google(audio, language="ru-RU")
        print(f"Вы сказали: {command}")
        return command
    except sr.UnknownValueError:
        return ""
    except sr.RequestError:
        print("Ошибка соединения с сервисом распознавания речи.")
        return ""

def parse_intent_with_ai(user_speech):
    prompt = f"""
    Проанализируй фразу и верни СТРОГО JSON без markdown-оформления (без ```json):
    {{
      "action": "open_youtube" или "google_search" или "open_app" или "exit" или "chat",
      "query": "поисковый запрос если нужен",
      "app_name": "название программы (steam, calc, discord, telegram, chrome)",
      "text": "ответ пользователю если это chat"
    }}
    Фраза: "{user_speech}"
    """
    try:
        response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
        clean_text = response.text.replace("```json", "").replace("```", "").strip()
        return json.loads(clean_text)
    except Exception as e:
        print(f"Ошибка ИИ: {e}")
        return {"action": "chat", "text": "Произошла ошибка при обращении к нейросети."}

def execute_action(intent):
    action = intent.get("action")
    if action == "open_youtube":
        q = intent.get("query", "")
        webbrowser.open(f"[https://www.youtube.com/results?search_query=](https://www.youtube.com/results?search_query=){q}")
        speak(f"Ищу на ютубе: {q}")
    elif action == "google_search":
        q = intent.get("query", "")
        webbrowser.open(f"[https://www.google.com/search?q=](https://www.google.com/search?q=){q}")
        speak("Ищу в интернете.")
    elif action == "open_app":
        app = intent.get("app_name", "").lower()
        if "steam" in app: os.system("start steam://")
        elif "calc" in app or "калькулятор" in app: os.system("calc")
        elif "discord" in app: os.system("start discord")
        elif "telegram" in app: os.system("start telegram")
        elif "chrome" in app or "браузер" in app: os.system("start chrome")
        speak("Готово.")
    elif action == "exit":
        speak("До свидания!")
        exit()
    elif action == "chat":
        speak(intent.get("text", "Слушаю."))

if __name__ == "__main__":
    speak("Система Нова активирована. Я жду команды.")
    while True:
        cmd = listen()
        if cmd:
            intent_data = parse_intent_with_ai(cmd)
            execute_action(intent_data)