import time
import re
import speech_recognition as sr
import pyttsx3
import yt_dlp as youtube_dl
import pygame
import imageio_ffmpeg as ffmpeg
from freeGPT import Client
from googletrans import Translator
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
import os
import logging
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.popup import Popup
from config import HUGGINGFACE_API_TOKEN
def speak(text, engine=None):
if not engine:
engine = initialize_tts_engine()
engine.say(text)
engine.runAndWait()
engine.stop()
Assistant
from kivy.uix.button import Button
def on_api_selection(instance):
commands = [
"https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta",
"https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium",
"https://api-inference.huggingface.co/models/microsoft/DialoGPT-large",
"https://api-inference.huggingface.co/models/gpt2",
"https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill"
]
print(f"Selected API: {instance.text}")
selected_api = commands[instance.index]
print(f"API URL: {selected_api}")
# Create the API selection button
api_button = Button(text="Выбрать API", size_hint=(0.2, 1))
api_button.bind(on_release=on_api_selection)
# Add the API selection button to the top left corner
top_layout.add_widget(api_button)
In the code above, I added a function on_api_selection that prints the selected API from the list when the button is clicked. Then, I created a new button for API selection, bind it to the on_api_selection function, and added it to the top left corner of the layout. When the user clicks this button, they can choose one of the available APIs which will be printed in the console for demonstration.
Selected API: Выбрать API
App crashed: 'Button' object has no attribute 'index'
Assistant
It seems like there was an error in the event binding where the index attribute was not available for the Button object directly. We can modify the code to capture the selected API index using a different approach. Here's an updated version to address this issue:
def get_hugginface_response(query, tts_engine=None):
import requests
selected_api = None
def on_api_selection(instance):
nonlocal selected_api
selected_api = instance.text
print(f"Selected API: {selected_api}")
def make_request(selected_api):
if selected_api:
headers = {"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}"}
response = requests.post(selected_api, headers=headers, json={"inputs": query})
if response.status_code == 200:
gpt_response = response.json()
translated_resp = translator.translate(gpt_response[0]['generated_text'], src='en', dest='ru').text
return translated_resp
else:
return "Произошла ошибка при выполнении запроса к API"
else:
return "Не выбран API для запроса"
# Create the API selection button
api_button = Button(text="Выбрать API", size_hint=(0.2, 1))
api_button.bind(on_release=on_api_selection)
# Make the request using the selected API
gpt_response = make_request(selected_api)
return gpt_response
User
при нажатии на Выбрать API на отображется список API
Assistant
To display a list of APIs when the "Выбрать API" button is clicked, we can utilize a DropDown widget in Kivy. This will allow us to show a dropdown menu with the available API options and select one from the list.
Here's an updated implementation with a dropdown menu for API selection:
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
def on_api_selection(instance):
dropdown = DropDown()
API_URLS = [
"https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta",
"https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium",
"https://api-inference.huggingface.co/models/microsoft/DialoGPT-large",
"https://api-inference.huggingface.co/models/gpt2",
"https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill"
]
for url in API_URLS:
btn = Button(text=url, size_hint_y=None, height=40)
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
dropdown.add_widget(btn)
dropdown.open(instance)
api_button.bind(on_release=on_api_selection)
Initialize speech recognizer
recognizer = sr.Recognizer()
def listen_command():
with sr.Microphone() as source:
safe_print(“Listening for command…”)
audio = recognizer.listen(source)
try:
command = recognizer.recognize_google(audio, language=“ru-RU”)
safe_print(f"Command heard: {command}“)
return command.lower()
except sr.UnknownValueError:
if os.path.exists(file_path):
speak(f"Файл уже существует. Проигрываю {sanitized_query}.“, tts_engine)
return file_path
with youtube_dl.YoutubeDL(youtube_dl_opts) as ydl:
info = ydl.extract_info(f"ytsearch1:{query}”, download=False)
video_info = info[‘entries’][0]
ydl.download([f"ytsearch1:{query}“])
while not os.path.exists(file_path):
time.sleep(1)
return file_path
except Exception as e:
logger.error(f"Error in search_youtube: {e}”)
speak(“Произошла ошибка при поиске песни”, tts_engine)
return None
def set_volume(level, tts_engine=None):
try:
level = int(level)
if 0 <= level <= 10:
pygame.mixer.music.set_volume(round(level / 10.0, 1)) # Округление и установка громкости
if tts_engine:
speak(f"Громкость установлена на {level}“, tts_engine)
else:
if tts_engine:
speak(“Пожалуйста, укажите уровень громкости от 0 до 10.”, tts_engine)
except ValueError:
if tts_engine:
speak(“Я не понял уровень громкости, укажите значение от 0 до 10.”, tts_engine)
speak(f"Громкость уменьшена до {new_volume}“, tts_engine)
def seek_forward(tts_engine):
if pygame.mixer.music.get_busy():
current_pos = pygame.mixer.music.get_pos()
new_pos = current_pos + 10000 # Skip forward by 10 seconds
pygame.mixer.music.set_pos(new_pos / 1000.0) # Set the new position
if tts_engine:
speak(“Перемотка на 10 секунд вперед”, tts_engine)
def seek_backward(tts_engine):
if pygame.mixer.music.get_busy():
current_pos = pygame.mixer.music.get_pos()
new_pos = max(0, current_pos - 10000) # Skip backward by 10 seconds, but not less than zero
pygame.mixer.music.set_pos(new_pos / 1000.0) # Set the new position
if tts_engine:
speak(“Перемотка на 10 секунд назад”, tts_engine)
commands = [
“найди песню - для поиска и воспроизведения песни”,
“проигрывание - для продолжения воспроизведения”,
“пауза - для паузы воспроизведения”,
“включи - для воспроизведения песни”,
“найди или найти - для поиска новой песни”,
“перестань слушать или не слушай - для прекращения слушать команды”,
“слушай - для возобновления слушания команд”,
“громкость - от нуля до десяти”,
“команды - для воспроизведения этого списка команд”,
“спасибо, выход или завершить - для завершения программы”
]
if response.status_code == 200:
gpt_response = response.json()
safe_print(f"GPT Response: {gpt_response}“)
Проверка и извлечение ответа
if gpt_response and isinstance(gpt_response, list) and len(gpt_response) > 0 and ‘generated_text’ in gpt_response[0]:
generated_text = gpt_response[0][‘generated_text’]
translated_resp = translator.translate(generated_text, src=‘en’, dest=‘ru’).text
return translated_resp
else:
return “Не удалось получить корректный ответ от API”
else:
print(f"Запрос не удался с кодом состояния: {response.status_code}”)
print(response.text)
return “Произошла ошибка при выполнении запроса к API”
except Exception as e:
return f"Произошла ошибка: {e}“
self.listen_button = Button(text=‘Голосовая команда’, size_hint=(1, 0.1))
self.listen_button.bind(on_release=self.listen_command_action)
self.layout.add_widget(self.listen_button)
self.result_output.text += “\nНажми ‘Голосовая команда’, доступные команды отображаются при нажатии на кнопку ‘команды’. " “\nЧтобы натйти песню нажми ‘Найти песню’. " “\nДля отправки запроса в ChatGPT - напиши запрос в поле и нажми кнопку отправить в ChatGPT-3.5.”
def process_text_query(self, instance):
query = self.command_input.text
self.result_output.text += f"\nВы: {query}“
self.command_input.text = ‘’ # clear the input after executing the command
self.execute_command(query)
def find_song_action(self, instance):
query = self.command_input.text
if query:
command = f"найди песню {query}”
self.result_output.text += f"\nВы (поиск песни): {query}“
self.command_input.text = ‘’ # clear the input after executing the command
self.execute_command(command)
else:
speak(“Какую песню вы хотите услышать?”, self.tts_engine)
search_query = listen_command()
safe_print(f"Search Query: {search_query}”)
if search_query:
song_path = search_youtube(search_query, self.tts_engine)
safe_print(f"Song Path: {song_path}“)
if song_path and os.path.exists(song_path):
self.current_song = song_path
self.current_position = 0 # Сбрасываем позицию
pygame.mixer.music.load(self.current_song)
pygame.mixer.music.play()
if self.tts_enabled:
speak(f"Проигрываю песню ‘{search_query}’”, self.tts_engine)
self.result_output.text += f"\nПроигрываю песню ‘{search_query}’“
else:
if self.tts_enabled:
speak(“Не удалось найти песню.”, self.tts_engine)
def execute_command(self, command):
if “перестань слушать” in command or “не слушай” in command:
speak(“Я перестаю слушать. Скажите ‘Слушай’, чтобы я снова начал слушать.”, self.tts_engine)
self.listening = False
return
if “слушай” in command:
speak(“Я снова слушаю.”, self.tts_engine)
self.listening = True
return
if “команды” in command:
list_commands(self.tts_engine)
self.result_output.text += “\nДоступные команды:\n”
for c in commands:
self.result_output.text += f”- {c}\n"
self.result_output.text += “\nДоступные команды перечислены.”
return
if “песню” in command or “песня” in command or “музыку” in command or “музыка” in command:
speak(“Какую песню вы хотите услышать?”, self.tts_engine)
search_query = listen_command()
safe_print(f"Search Query: {search_query}“)
if search_query:
song_path = search_youtube(search_query, self.tts_engine)
safe_print(f"Song Path: {song_path}”)
self.result_output.text += “\nЗагружаю файл…”
if song_path and os.path.exists(song_path):
if self.current_song:
pygame.mixer.music.stop()
while pygame.mixer.music.get_busy():
time.sleep(0.1)
if os.path.exists(self.current_song):
os.remove(self.current_song)
self.current_song = song_path
self.current_position = 0 # Сбрасываем позицию
pygame.mixer.music.load(self.current_song)
pygame.mixer.music.play()
speak(f"Проигрываю песню ‘{search_query}’“, self.tts_engine)
self.result_output.text += f”\nПроигрываю песню ‘{search_query}’“
else:
speak(“Не удалось найти песню.”, self.tts_engine)
return
if “проигрывание” in command:
if self.current_song and not pygame.mixer.music.get_busy() and self.current_position > 0:
pygame.mixer.music.load(self.current_song)
pygame.mixer.music.play(start=self.current_position / 1000) # Возобновить с сохраненной позиции
self.result_output.text += “\nВоспроизведение продолжено”
return
if “пауза” in command:
if self.current_song and pygame.mixer.music.get_busy():
self.current_position = pygame.mixer.music.get_pos()
pygame.mixer.music.stop()
self.result_output.text += “\nВоспроизведение приостановлено”
return
if “включи” in command:
if self.current_song:
if not pygame.mixer.music.get_busy():
pygame.mixer.music.play()
self.result_output.text += “\nПроигрывание начато”
else:
self.result_output.text += “\nПроигрывание уже идет”
return
if “найди” in command or “найти” in command:
self.stop_playback()
speak(“Что вы хотите найти?”, self.tts_engine)
search_query = listen_command()
safe_print(f"Search Query: {search_query}”)
if search_query:
song_path = search_youtube(search_query, self.tts_engine)
safe_print(f"Song Path: {song_path}“)
if song_path and os.path.exists(song_path):
self.current_song = song_path
self.current_position = 0 # Сбрасываем позицию
pygame.mixer.music.load(self.current_song)
pygame.mixer.music.play()
speak(f"Проигрываю песню ‘{search_query}’”, self.tts_engine)
self.result_output.text += f"\nПроигрываю песню ‘{search_query}’“
else:
speak(“Не удалось найти песню.”, self.tts_engine)
return
if “громкость” in command:
parts = command.split()
if len(parts) > 1:
number_word = parts[1]
level = get_number_from_text(number_word)
if level is not None:
set_volume(level, self.tts_engine)
self.result_output.text += f”\nГромкость установлена на {level}“
else:
speak(“Пожалуйста, укажите уровень громкости от 0 до 10.”, self.tts_engine)
else:
speak(“Пожалуйста, укажите уровень громкости от 0 до 10.”, self.tts_engine)
return
if “спасибо” in command or “выход” in command or “завершить” in command:
speak(“Завершаю работу. До свидания!”, self.tts_engine)
App.get_running_app().stop()
return
if name == “main”:
try:
MyApp().run()
except Exception as e:
print(f"App crashed: {e}”)
logger.error(f"App crashed: {e}")
finally:
pygame.quit()
In the modified get_hugginface_response function, I added the API selection logic inside the function. When the api_button is clicked, it will set the selected API for the request and send the query to that API endpoint. Based on the selected API, the response will be handled accordingly. This approach allows the user to choose the API dynamically before making the request.
In this updated code, I separated the API selection logic and making the request into separate functions. The on_api_selection function captures the selected API text, and the make_request function uses the selected API to make the POST request. Hopefully, this implementation resolves the issue with the Button object attribute error.
In this updated implementation, the on_api_selection function creates a DropDown widget and populates it with buttons corresponding to the available API URLs. When the "Выбрать API" button is clicked, the dropdown menu is displayed with the list of API options. Selecting an API from the dropdown will set the selected API appropriately.