-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroq.py
More file actions
155 lines (110 loc) · 3.42 KB
/
Groq.py
File metadata and controls
155 lines (110 loc) · 3.42 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
import os
import sys
import speech_recognition as sr
from gtts import gTTS
import pygame
from config import api_key
from langchain_groq import ChatGroq
from elevenlabs import ElevenLabs
# ===============================
# CONFIG INICIAL
# ===============================
os.environ["GROQ_API_KEY"] = api_key
client = ElevenLabs(api_key="")
AGENT_ID=""
chat = ChatGroq(model="llama-3.1-8b-instant")
os.makedirs("audios", exist_ok=True)
nome = input("Qual é seu nome? ").strip().title()
print(f"Bem-vindo senhor Verificado >>> {nome} <<<")
recognizer = sr.Recognizer()
# ===============================
# FUNÇÃO PARA GERAR ÁUDIO
# ===============================
def cria_audio(texto):
caminho = "audios/fala.mp3"
if os.path.exists(caminho):
try:
os.remove(caminho)
except PermissionError:
pygame.mixer.quit()
os.remove(caminho)
# gerar áudio com ElevenLabs
audio_bytes = client.text_to_speech.convert(
voice_id="pNInz6obpgDQGcFmaJgB",
text=texto,
model_id="eleven_multilingual_v2"
)
with open(caminho, "wb") as f:
for chunk in audio_bytes:
f.write(chunk)
pygame.mixer.init()
pygame.mixer.music.load(caminho)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pass
pygame.mixer.quit()
# ===============================
# OUVIR MICROFONE
# ===============================
def ouvir_microfone():
with sr.Microphone(device_index=0, sample_rate=48000) as mic:
recognizer.adjust_for_ambient_noise(mic, duration=1)
recognizer.energy_threshold = 25
recognizer.dynamic_energy_threshold = True
recognizer.pause_threshold = 1.5
recognizer.non_speaking_duration = 0.6
print(f"Ouvindo, {nome}...")
try:
audio = recognizer.listen(
mic,
timeout=15, #
phrase_time_limit=20
)
except sr.WaitTimeoutError:
print("Não ouvi nada...")
return ""
try:
frase = recognizer.recognize_google(audio, language="pt-BR")
return frase
except:
print("Não entendi.")
return ""
# ===============================
# INPUT VIA VOZ
# ===============================
def input_voz(prompt=""):
print(prompt)
frase = ouvir_microfone()
print(f"[entrada por voz]: {frase}")
return frase
# ===============================
# AÇÕES DE SISTEMA
# ===============================
def verificar_acao(frase):
f = frase.lower()
if "sair" in f or "encerrar" in f or "fechar" in f:
print("Desligando...")
cria_audio("Fechando o sistema. Até mais!")
sys.exit(0)
# ===============================
# BEM-VINDO (fala inicial)
# ===============================
cria_audio(f"Olá senhor {nome}, Versão de teste IA")
# ===============================
# LOOP PRINCIPAL
# ===============================
historico = []
while True:
pergunta = input_voz(f"{nome}: O que posso ajudar você? (ou diga Encerrar)")
if not pergunta:
continue
verificar_acao(pergunta)
mensagem = (
f"Usuário: {nome}\n"
f"Histórico:\n" + "\n".join(historico[-10:]) + "\n"
f"Pergunta atual: {pergunta}"
)
resposta = chat.invoke(mensagem).content
print("\nChatGroq:", resposta)
cria_audio(resposta)
historico.append(f"{nome}: {pergunta}")