Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- Dockerfile +11 -5
- app.py +136 -300
- download_model.py +3 -2
- index.html +38 -9
- requirements.txt +4 -4
Dockerfile
CHANGED
@@ -8,13 +8,19 @@ WORKDIR /code
|
|
8 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
9 |
build-essential \
|
10 |
pkg-config \
|
11 |
-
ffmpeg
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
rm -rf /var/lib/apt/lists/*
|
13 |
|
14 |
# Atualiza o pip para a versão mais recente.
|
15 |
RUN pip install --no-cache-dir --upgrade pip
|
16 |
|
17 |
-
# Copia e instala todas as dependências do Python.
|
18 |
COPY ./requirements.txt /code/requirements.txt
|
19 |
RUN pip install --no-cache-dir -r /code/requirements.txt
|
20 |
|
@@ -35,6 +41,6 @@ RUN chown -R 1000:1000 /code/models_cache
|
|
35 |
# Expõe a porta que a aplicação irá usar.
|
36 |
EXPOSE 7860
|
37 |
|
38 |
-
# ---
|
39 |
-
#
|
40 |
-
CMD ["
|
|
|
8 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
9 |
build-essential \
|
10 |
pkg-config \
|
11 |
+
ffmpeg \
|
12 |
+
libavcodec-dev \
|
13 |
+
libavformat-dev \
|
14 |
+
libswscale-dev \
|
15 |
+
libavdevice-dev \
|
16 |
+
libavfilter-dev \
|
17 |
+
libswresample-dev && \
|
18 |
rm -rf /var/lib/apt/lists/*
|
19 |
|
20 |
# Atualiza o pip para a versão mais recente.
|
21 |
RUN pip install --no-cache-dir --upgrade pip
|
22 |
|
23 |
+
# Copia e instala todas as dependências do Python de uma só vez.
|
24 |
COPY ./requirements.txt /code/requirements.txt
|
25 |
RUN pip install --no-cache-dir -r /code/requirements.txt
|
26 |
|
|
|
41 |
# Expõe a porta que a aplicação irá usar.
|
42 |
EXPOSE 7860
|
43 |
|
44 |
+
# --- CORREÇÃO DEFINITIVA ---
|
45 |
+
# Comando para iniciar a aplicação com Gunicorn, apontando para o adaptador asgi_app.
|
46 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--worker-class", "uvicorn.workers.UvicornWorker", "app:asgi_app"]
|
app.py
CHANGED
@@ -1,306 +1,142 @@
|
|
1 |
import os, io, base64, tempfile, logging, json, asyncio
|
2 |
-
|
3 |
-
|
4 |
-
from
|
5 |
-
dotenv
|
6 |
-
_
|
7 |
-
from faster
|
8 |
-
_
|
9 |
-
whisper import WhisperModel
|
10 |
import google.generativeai as genai
|
11 |
-
import
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
14 |
# ---------- Configuração Inicial ----------
|
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 |
-
KEY = os.getenv("GOOGLE
|
43 |
-
_
|
44 |
-
_
|
45 |
-
PASSWORDS")
|
46 |
-
API
|
47 |
-
KEY")
|
48 |
-
# ---------- Aplicação FastAPI ----------
|
49 |
-
app = FastAPI()
|
50 |
-
logging.basicConfig(level=logging.INFO, format=
|
51 |
-
"%(asctime)s - %(levelname)s -
|
52 |
-
%(message)s")
|
53 |
-
# ---------- Carregamento de Modelos (no arranque) ----------
|
54 |
-
whisper
|
55 |
-
model = None
|
56 |
-
_
|
57 |
-
gemini
|
58 |
-
model = None
|
59 |
-
_
|
60 |
-
@app.on
|
61 |
-
_
|
62 |
-
event("startup")
|
63 |
-
def load
|
64 |
-
models():
|
65 |
-
_
|
66 |
-
global whisper
|
67 |
-
_
|
68 |
-
model, gemini
|
69 |
-
model
|
70 |
-
_
|
71 |
-
logging.info("A carregar modelos e clientes de API...
|
72 |
-
")
|
73 |
try:
|
74 |
-
|
75 |
-
|
76 |
-
"
|
77 |
-
_
|
78 |
-
whisper
|
79 |
-
_
|
80 |
-
model = WhisperModel(model
|
81 |
-
name, device=
|
82 |
-
_
|
83 |
-
"cpu"
|
84 |
-
,
|
85 |
-
compute
|
86 |
-
_
|
87 |
-
type=
|
88 |
-
"int8")
|
89 |
-
logging.info(f"Modelo faster-whisper '{model
|
90 |
-
_
|
91 |
-
name}' (int8) pronto.
|
92 |
-
")
|
93 |
except Exception as e:
|
94 |
-
logging.error(
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
logging.info("Gemini pronto.
|
114 |
-
")
|
115 |
-
except Exception as e:
|
116 |
-
logging.error(f"Falha ao iniciar Gemini: {e}")
|
117 |
-
raise RuntimeError("Não foi possível carregar o modelo Gemini.
|
118 |
-
") from e
|
119 |
-
logging.info("Modelos carregados com sucesso.
|
120 |
-
")
|
121 |
-
# ---------- Utilidades ----------
|
122 |
-
def ask
|
123 |
-
_gemini(question: str) -> str:
|
124 |
-
if not gemini
|
125 |
-
model:
|
126 |
-
_
|
127 |
-
raise HTTPException(status
|
128 |
-
code=503, detail=
|
129 |
-
_
|
130 |
-
"Modelo de linguagem não está
|
131 |
-
disponível.
|
132 |
-
")
|
133 |
-
prompt = ("Você é 'SintonIA'
|
134 |
-
, um assistente de IA por voz para saúde bucal.
|
135 |
-
"
|
136 |
-
"Responda de forma empática, clara e segura, em 2-3 frases.
|
137 |
-
"
|
138 |
-
"NUNCA dê diagnóstico e sempre recomende consulta presencial a um
|
139 |
-
dentista.
|
140 |
-
")
|
141 |
-
try:
|
142 |
-
response = gemini
|
143 |
-
_
|
144 |
-
model.generate
|
145 |
-
_
|
146 |
-
content([prompt, question])
|
147 |
-
return response.text
|
148 |
-
except Exception as e:
|
149 |
-
logging.error(f"Erro no Gemini: {e}")
|
150 |
-
raise HTTPException(status
|
151 |
-
code=500, detail=
|
152 |
-
_
|
153 |
-
"Erro ao gerar a resposta de IA.
|
154 |
-
")
|
155 |
-
VOICE =
|
156 |
-
"pt-BR-AntonioNeural"
|
157 |
async def synthesize(text: str) -> bytes | None:
|
158 |
-
try:
|
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 |
-
if
|
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 |
-
content = await audio.read()
|
236 |
-
tmp_
|
237 |
-
file.write(content)
|
238 |
-
tmp_
|
239 |
-
file.seek(0)
|
240 |
-
if os.path.getsize(tmp_
|
241 |
-
file.name) > 1000:
|
242 |
-
segments,
|
243 |
-
_
|
244 |
-
= whisper
|
245 |
-
_
|
246 |
-
model.transcribe(tmp_
|
247 |
-
file.name, language=
|
248 |
-
"pt")
|
249 |
-
transcribed
|
250 |
-
_parts = [segment.text for segment in segments]
|
251 |
-
text =
|
252 |
-
""
|
253 |
-
.join(transcribed
|
254 |
-
_parts).strip()
|
255 |
-
logging.info(f"Texto transcrito: '{text}'")
|
256 |
-
else:
|
257 |
-
text =
|
258 |
-
""
|
259 |
-
except Exception as e:
|
260 |
-
logging.error(f"Erro na transcrição do faster-whisper: {e}")
|
261 |
-
text =
|
262 |
-
""
|
263 |
-
if not text:
|
264 |
-
ai
|
265 |
-
_
|
266 |
-
else:
|
267 |
-
ai
|
268 |
-
text =
|
269 |
-
_
|
270 |
-
"Desculpe, não entendi o que foi dito. Você poderia repetir, por favor?"
|
271 |
-
text = ask
|
272 |
-
_gemini(text)
|
273 |
-
audio
|
274 |
-
_
|
275 |
-
if ai
|
276 |
-
text:
|
277 |
-
_
|
278 |
-
audio
|
279 |
-
bytes = None
|
280 |
-
_
|
281 |
-
bytes = await synthesize(ai
|
282 |
-
text)
|
283 |
-
_
|
284 |
-
# --- LÓGICA FINAL: Retorna um JSON com todos os dados ---
|
285 |
-
return JSONResponse(content={
|
286 |
-
"user
|
287 |
-
_question": text,
|
288 |
-
"ai
|
289 |
-
answer": ai
|
290 |
-
text,
|
291 |
-
_
|
292 |
-
_
|
293 |
-
"audio
|
294 |
-
base64": base64.b64encode(audio
|
295 |
-
_
|
296 |
-
_
|
297 |
-
bytes).decode('utf-8') if audio
|
298 |
-
_
|
299 |
-
else None
|
300 |
-
bytes
|
301 |
-
})
|
302 |
-
@app.get("/healthz")
|
303 |
-
async def health
|
304 |
-
check():
|
305 |
-
_
|
306 |
-
return {"status": "OK"}
|
|
|
1 |
import os, io, base64, tempfile, logging, json, asyncio
|
2 |
+
|
3 |
+
# Importa WhisperModel de faster_whisper
|
4 |
+
from faster_whisper import WhisperModel
|
|
|
|
|
|
|
|
|
|
|
5 |
import google.generativeai as genai
|
6 |
+
from flask import Flask, request, jsonify, send_from_directory
|
7 |
+
from flask_cors import CORS
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
import edge_tts
|
10 |
+
# --- NOVA IMPORTAÇÃO PARA O ADAPTADOR ---
|
11 |
+
from asgiref.wsgi import WsgiToAsgi
|
12 |
+
|
13 |
# ---------- Configuração Inicial ----------
|
14 |
+
load_dotenv()
|
15 |
+
|
16 |
+
CACHE_DIR = os.getenv("HF_HUB_CACHE", "./models_cache")
|
17 |
+
os.environ["MPLCONFIGDIR"] = os.path.join(CACHE_DIR, "matplotlib")
|
18 |
+
|
19 |
+
LOGIN_PASSWORDS = os.getenv("LOGIN_PASSWORDS")
|
20 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
21 |
+
|
22 |
+
# ---------- servidor ----------
|
23 |
+
app = Flask(__name__)
|
24 |
+
CORS(app)
|
25 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
26 |
+
logging.info("A carregar modelos e clientes de API...")
|
27 |
+
|
28 |
+
# ---------- Modelos e Clientes de API ----------
|
29 |
+
# --- Modelo Gemini ---
|
30 |
+
gemini_model = None
|
31 |
+
if GOOGLE_API_KEY:
|
32 |
+
try:
|
33 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
34 |
+
gemini_model = genai.GenerativeModel("gemini-1.5-flash")
|
35 |
+
logging.info("Gemini pronto.")
|
36 |
+
except Exception as e:
|
37 |
+
logging.error("Falha ao iniciar Gemini: %s", e)
|
38 |
+
|
39 |
+
# --- Modelo Whisper (usando faster-whisper) ---
|
40 |
+
whisper_model = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
try:
|
42 |
+
model_name = "small"
|
43 |
+
whisper_model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
44 |
+
logging.info(f"Modelo faster-whisper '{model_name}' (int8) pronto.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
except Exception as e:
|
46 |
+
logging.error("Falha ao iniciar o modelo faster-whisper: %s", e)
|
47 |
+
|
48 |
+
# ---------- utilidades ----------
|
49 |
+
def ask_gemini(question: str) -> str:
|
50 |
+
if not gemini_model:
|
51 |
+
return "Desculpe, o modelo Gemini não está acessível no momento."
|
52 |
+
prompt = ("Você é 'SintonIA', um assistente de IA por voz para saúde bucal. "
|
53 |
+
"Responda de forma empática, clara e segura, em 2-3 frases. "
|
54 |
+
"NUNCA dê diagnóstico e sempre recomende consulta presencial a um dentista.")
|
55 |
+
try:
|
56 |
+
response = gemini_model.generate_content([prompt, question])
|
57 |
+
return response.text
|
58 |
+
except Exception as e:
|
59 |
+
logging.error("Erro no Gemini: %s", e)
|
60 |
+
return "Desculpe, ocorreu um erro ao gerar a resposta."
|
61 |
+
|
62 |
+
# --- NOVA FUNÇÃO DE SÍNTESE COM EDGE TTS ---
|
63 |
+
VOICE = "pt-BR-AntonioNeural"
|
64 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
async def synthesize(text: str) -> bytes | None:
|
66 |
+
try:
|
67 |
+
audio_bytes = b""
|
68 |
+
communicate = edge_tts.Communicate(text, VOICE)
|
69 |
+
async for chunk in communicate.stream():
|
70 |
+
if chunk["type"] == "audio":
|
71 |
+
audio_bytes += chunk["data"]
|
72 |
+
|
73 |
+
logging.info(f"Áudio sintetizado com sucesso usando a voz: {VOICE}")
|
74 |
+
return audio_bytes
|
75 |
+
except Exception as e:
|
76 |
+
logging.error(f"Erro ao sintetizar áudio com Edge TTS: {e}")
|
77 |
+
return None
|
78 |
+
|
79 |
+
# ---------- rotas ----------
|
80 |
+
@app.route("/")
|
81 |
+
def index():
|
82 |
+
return send_from_directory(".", "index.html")
|
83 |
+
|
84 |
+
@app.route("/login", methods=["POST"])
|
85 |
+
def login():
|
86 |
+
if not LOGIN_PASSWORDS:
|
87 |
+
return jsonify(success=True)
|
88 |
+
|
89 |
+
valid_passwords = [p.strip() for p in LOGIN_PASSWORDS.split(',')]
|
90 |
+
pwd_received = (request.json or {}).get("password", "")
|
91 |
+
is_ok = pwd_received in valid_passwords
|
92 |
+
|
93 |
+
return jsonify(success=is_ok), (200 if is_ok else 401)
|
94 |
+
|
95 |
+
@app.route("/process-audio", methods=["POST"])
|
96 |
+
async def process_audio():
|
97 |
+
if "audio" not in request.files:
|
98 |
+
return jsonify(error="Nenhum ficheiro de áudio enviado."), 400
|
99 |
+
if not all([whisper_model, gemini_model]):
|
100 |
+
return jsonify(error="Erro interno: um serviço de IA não está disponível."), 500
|
101 |
+
|
102 |
+
audio_file = request.files["audio"]
|
103 |
+
text = ""
|
104 |
+
with tempfile.NamedTemporaryFile(delete=True, suffix=".webm") as tmp_file:
|
105 |
+
audio_file.save(tmp_file.name)
|
106 |
+
try:
|
107 |
+
if os.path.getsize(tmp_file.name) > 1000:
|
108 |
+
segments, info = whisper_model.transcribe(tmp_file.name, language="pt")
|
109 |
+
transcribed_parts = [segment.text for segment in segments]
|
110 |
+
text = "".join(transcribed_parts).strip()
|
111 |
+
logging.info(f"Texto transcrito: '{text}'")
|
112 |
+
else:
|
113 |
+
text = ""
|
114 |
+
except Exception as e:
|
115 |
+
logging.error(f"Erro na transcrição do faster-whisper: {e}")
|
116 |
+
text = ""
|
117 |
+
|
118 |
+
ai_text = ""
|
119 |
+
audio_bytes = None
|
120 |
+
|
121 |
+
if not text:
|
122 |
+
ai_text = "Desculpe, não entendi o que foi dito. Você poderia repetir, por favor?"
|
123 |
+
else:
|
124 |
+
ai_text = ask_gemini(text)
|
125 |
+
|
126 |
+
if ai_text:
|
127 |
+
audio_bytes = await synthesize(ai_text)
|
128 |
+
|
129 |
+
return jsonify(
|
130 |
+
user_question=text,
|
131 |
+
ai_answer=ai_text,
|
132 |
+
audio_base64=base64.b64encode(audio_bytes).decode() if audio_bytes else None
|
133 |
+
)
|
134 |
+
|
135 |
+
@app.route("/healthz")
|
136 |
+
def health_check():
|
137 |
+
return "OK", 200
|
138 |
+
|
139 |
+
# --- ADAPTADOR ASGI/WSGI PARA PRODUÇÃO ---
|
140 |
+
# Esta linha cria uma versão "traduzida" da sua aplicação Flask
|
141 |
+
# que é totalmente compatível com o servidor de produção ASGI.
|
142 |
+
asgi_app = WsgiToAsgi(app)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
download_model.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
# download_model.py
|
2 |
from faster_whisper import WhisperModel
|
3 |
|
4 |
-
#
|
5 |
-
MODEL_NAME = "
|
6 |
|
7 |
print(f"A descarregar e a fazer cache do modelo Whisper '{MODEL_NAME}' no formato CTranslate2...")
|
8 |
|
@@ -10,6 +10,7 @@ try:
|
|
10 |
# Esta chamada é suficiente para descarregar o modelo, convertê-lo
|
11 |
# para o formato CTranslate2 e salvá-lo no diretório de cache
|
12 |
# definido pela variável de ambiente HF_HUB_CACHE.
|
|
|
13 |
WhisperModel(
|
14 |
MODEL_NAME,
|
15 |
device="cpu",
|
|
|
1 |
# download_model.py
|
2 |
from faster_whisper import WhisperModel
|
3 |
|
4 |
+
# Este script descarrega e converte o modelo durante o 'build' do Docker.
|
5 |
+
MODEL_NAME = "small"
|
6 |
|
7 |
print(f"A descarregar e a fazer cache do modelo Whisper '{MODEL_NAME}' no formato CTranslate2...")
|
8 |
|
|
|
10 |
# Esta chamada é suficiente para descarregar o modelo, convertê-lo
|
11 |
# para o formato CTranslate2 e salvá-lo no diretório de cache
|
12 |
# definido pela variável de ambiente HF_HUB_CACHE.
|
13 |
+
# O teste de transcrição foi removido para tornar o build mais robusto.
|
14 |
WhisperModel(
|
15 |
MODEL_NAME,
|
16 |
device="cpu",
|
index.html
CHANGED
@@ -109,21 +109,25 @@
|
|
109 |
let audioChunks = [];
|
110 |
let isRecording = false;
|
111 |
let audioPlayer = new Audio();
|
112 |
-
let isAudioContextUnlocked = false;
|
113 |
|
114 |
// --- Inicialização ---
|
115 |
lucide.createIcons();
|
116 |
|
117 |
-
// --- Lógica para "destravar" o áudio ---
|
118 |
function primeAudioContext() {
|
119 |
if (isAudioContextUnlocked) return;
|
|
|
120 |
audioPlayer.src = "data:audio/mpeg;base64,SUQzBAAAAAABEVRYWFgAAAAtAAADY29tbWVudABCaXRyYXRlIHN1cHBseSBieSBiaXRyYXRlLmNvbQAAAABUY29uAAAAAABQaG9uZQAAAAA=";
|
121 |
const playPromise = audioPlayer.play();
|
122 |
if (playPromise !== undefined) {
|
123 |
playPromise.then(() => {
|
124 |
audioPlayer.pause();
|
125 |
isAudioContextUnlocked = true;
|
126 |
-
|
|
|
|
|
|
|
127 |
}
|
128 |
}
|
129 |
|
@@ -134,7 +138,9 @@
|
|
134 |
});
|
135 |
|
136 |
async function handleLogin() {
|
|
|
137 |
primeAudioContext();
|
|
|
138 |
const password = passwordInput.value;
|
139 |
errorMessage.textContent = '';
|
140 |
try {
|
@@ -151,6 +157,7 @@
|
|
151 |
errorMessage.textContent = 'Senha incorreta. Tente novamente.';
|
152 |
}
|
153 |
} catch (error) {
|
|
|
154 |
errorMessage.textContent = 'Não foi possível conectar ao servidor.';
|
155 |
}
|
156 |
}
|
@@ -168,15 +175,29 @@
|
|
168 |
audioChunks = [];
|
169 |
try {
|
170 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
|
171 |
const mimeType = MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : 'audio/mp4';
|
172 |
mediaRecorder = new MediaRecorder(stream, { mimeType });
|
173 |
-
|
|
|
|
|
|
|
|
|
174 |
mediaRecorder.onstop = sendAudioToServer;
|
|
|
175 |
mediaRecorder.start();
|
176 |
isRecording = true;
|
177 |
setButtonState('recording');
|
|
|
178 |
} catch (error) {
|
179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
180 |
setButtonState('idle');
|
181 |
}
|
182 |
}
|
@@ -189,9 +210,10 @@
|
|
189 |
setButtonState('processing');
|
190 |
}
|
191 |
|
192 |
-
// ---
|
193 |
async function sendAudioToServer() {
|
194 |
const audioBlob = new Blob(audioChunks, { type: mediaRecorder.mimeType });
|
|
|
195 |
if (audioBlob.size < 1000) {
|
196 |
setButtonState('idle');
|
197 |
addMessageToChat('A gravação foi muito curta. Tente novamente.', 'error');
|
@@ -208,8 +230,8 @@
|
|
208 |
body: formData
|
209 |
});
|
210 |
if (!response.ok) {
|
211 |
-
const errorData = await response.json()
|
212 |
-
throw new Error(errorData.
|
213 |
}
|
214 |
const data = await response.json();
|
215 |
|
@@ -238,6 +260,7 @@
|
|
238 |
if (audioPlayer.src && audioPlayer.src.startsWith('blob:')) {
|
239 |
URL.revokeObjectURL(audioPlayer.src);
|
240 |
}
|
|
|
241 |
audioPlayer.src = URL.createObjectURL(audioBlob);
|
242 |
|
243 |
const playPromise = audioPlayer.play();
|
@@ -245,12 +268,18 @@
|
|
245 |
playPromise.then(() => {
|
246 |
setButtonState('speaking');
|
247 |
}).catch(error => {
|
|
|
248 |
addMessageToChat("Não foi possível reproduzir o áudio automaticamente.", 'error');
|
249 |
setButtonState('idle');
|
250 |
});
|
251 |
}
|
252 |
-
|
|
|
|
|
|
|
|
|
253 |
} catch (error) {
|
|
|
254 |
addMessageToChat("Falha ao processar o áudio.", "error");
|
255 |
setButtonState('idle');
|
256 |
}
|
|
|
109 |
let audioChunks = [];
|
110 |
let isRecording = false;
|
111 |
let audioPlayer = new Audio();
|
112 |
+
let isAudioContextUnlocked = false; // --- CORREÇÃO: Variável de controle re-adicionada
|
113 |
|
114 |
// --- Inicialização ---
|
115 |
lucide.createIcons();
|
116 |
|
117 |
+
// --- CORREÇÃO: Lógica para "destravar" o áudio re-adicionada ---
|
118 |
function primeAudioContext() {
|
119 |
if (isAudioContextUnlocked) return;
|
120 |
+
// Toca um som silencioso para "acordar" o player de áudio do navegador.
|
121 |
audioPlayer.src = "data:audio/mpeg;base64,SUQzBAAAAAABEVRYWFgAAAAtAAADY29tbWVudABCaXRyYXRlIHN1cHBseSBieSBiaXRyYXRlLmNvbQAAAABUY29uAAAAAABQaG9uZQAAAAA=";
|
122 |
const playPromise = audioPlayer.play();
|
123 |
if (playPromise !== undefined) {
|
124 |
playPromise.then(() => {
|
125 |
audioPlayer.pause();
|
126 |
isAudioContextUnlocked = true;
|
127 |
+
console.log("Contexto de áudio desbloqueado e preparado.");
|
128 |
+
}).catch(error => {
|
129 |
+
console.error("Falha ao preparar o contexto de áudio:", error);
|
130 |
+
});
|
131 |
}
|
132 |
}
|
133 |
|
|
|
138 |
});
|
139 |
|
140 |
async function handleLogin() {
|
141 |
+
// --- CORREÇÃO: Prepara o áudio no primeiro clique do usuário ---
|
142 |
primeAudioContext();
|
143 |
+
|
144 |
const password = passwordInput.value;
|
145 |
errorMessage.textContent = '';
|
146 |
try {
|
|
|
157 |
errorMessage.textContent = 'Senha incorreta. Tente novamente.';
|
158 |
}
|
159 |
} catch (error) {
|
160 |
+
console.error('Erro de conexão:', error);
|
161 |
errorMessage.textContent = 'Não foi possível conectar ao servidor.';
|
162 |
}
|
163 |
}
|
|
|
175 |
audioChunks = [];
|
176 |
try {
|
177 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
178 |
+
|
179 |
const mimeType = MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : 'audio/mp4';
|
180 |
mediaRecorder = new MediaRecorder(stream, { mimeType });
|
181 |
+
|
182 |
+
mediaRecorder.ondataavailable = event => {
|
183 |
+
audioChunks.push(event.data);
|
184 |
+
};
|
185 |
+
|
186 |
mediaRecorder.onstop = sendAudioToServer;
|
187 |
+
|
188 |
mediaRecorder.start();
|
189 |
isRecording = true;
|
190 |
setButtonState('recording');
|
191 |
+
|
192 |
} catch (error) {
|
193 |
+
console.error("ERRO AO INICIAR GRAVAÇÃO:", error.name, error.message);
|
194 |
+
let userMessage = 'Ocorreu um erro ao tentar aceder ao microfone. Verifique as permissões.';
|
195 |
+
if (error.name === 'NotAllowedError') {
|
196 |
+
userMessage = 'A permissão para usar o microfone foi negada. Por favor, habilite nas configurações do seu navegador.';
|
197 |
+
} else if (error.name === 'NotFoundError') {
|
198 |
+
userMessage = 'Nenhum microfone foi encontrado no seu dispositivo.';
|
199 |
+
}
|
200 |
+
addMessageToChat(userMessage, "error");
|
201 |
setButtonState('idle');
|
202 |
}
|
203 |
}
|
|
|
210 |
setButtonState('processing');
|
211 |
}
|
212 |
|
213 |
+
// --- Comunicação com o Servidor ---
|
214 |
async function sendAudioToServer() {
|
215 |
const audioBlob = new Blob(audioChunks, { type: mediaRecorder.mimeType });
|
216 |
+
|
217 |
if (audioBlob.size < 1000) {
|
218 |
setButtonState('idle');
|
219 |
addMessageToChat('A gravação foi muito curta. Tente novamente.', 'error');
|
|
|
230 |
body: formData
|
231 |
});
|
232 |
if (!response.ok) {
|
233 |
+
const errorData = await response.json();
|
234 |
+
throw new Error(errorData.error || `Erro do servidor: ${response.statusText}`);
|
235 |
}
|
236 |
const data = await response.json();
|
237 |
|
|
|
260 |
if (audioPlayer.src && audioPlayer.src.startsWith('blob:')) {
|
261 |
URL.revokeObjectURL(audioPlayer.src);
|
262 |
}
|
263 |
+
|
264 |
audioPlayer.src = URL.createObjectURL(audioBlob);
|
265 |
|
266 |
const playPromise = audioPlayer.play();
|
|
|
268 |
playPromise.then(() => {
|
269 |
setButtonState('speaking');
|
270 |
}).catch(error => {
|
271 |
+
console.error("Falha na reprodução automática:", error);
|
272 |
addMessageToChat("Não foi possível reproduzir o áudio automaticamente.", 'error');
|
273 |
setButtonState('idle');
|
274 |
});
|
275 |
}
|
276 |
+
|
277 |
+
audioPlayer.onended = () => {
|
278 |
+
setButtonState('idle');
|
279 |
+
};
|
280 |
+
|
281 |
} catch (error) {
|
282 |
+
console.error("Erro ao decodificar o áudio:", error);
|
283 |
addMessageToChat("Falha ao processar o áudio.", "error");
|
284 |
setButtonState('idle');
|
285 |
}
|
requirements.txt
CHANGED
@@ -1,9 +1,9 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
python-multipart
|
4 |
python-dotenv
|
5 |
faster-whisper
|
6 |
ctranslate2
|
7 |
google-generativeai
|
|
|
8 |
edge-tts
|
9 |
-
|
|
|
1 |
+
Flask[async]
|
2 |
+
Flask-Cors
|
|
|
3 |
python-dotenv
|
4 |
faster-whisper
|
5 |
ctranslate2
|
6 |
google-generativeai
|
7 |
+
gunicorn
|
8 |
edge-tts
|
9 |
+
uvicorn
|