Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify, send_file
|
2 |
+
from flask_cors import CORS
|
3 |
+
from faster_whisper import WhisperModel
|
4 |
+
from transformers import pipeline
|
5 |
+
from TTS.api import TTS
|
6 |
+
import tempfile
|
7 |
+
import os
|
8 |
+
|
9 |
+
app = Flask(__name__)
|
10 |
+
CORS(app)
|
11 |
+
|
12 |
+
# Load models
|
13 |
+
whisper_model = WhisperModel("small", device="cpu", compute_type="int8")
|
14 |
+
llm = pipeline("text-generation", model="tiiuae/falcon-rw-1b", max_new_tokens=100)
|
15 |
+
tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC", progress_bar=False, gpu=False)
|
16 |
+
|
17 |
+
@app.route("/talk", methods=["POST"])
|
18 |
+
def talk():
|
19 |
+
if "audio" not in request.files:
|
20 |
+
return jsonify({"error": "No audio file"}), 400
|
21 |
+
|
22 |
+
# Save audio
|
23 |
+
audio_file = request.files["audio"]
|
24 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
|
25 |
+
audio_path = tmp.name
|
26 |
+
audio_file.save(audio_path)
|
27 |
+
|
28 |
+
# Transcribe
|
29 |
+
segments, _ = whisper_model.transcribe(audio_path)
|
30 |
+
transcription = "".join([seg.text for seg in segments])
|
31 |
+
|
32 |
+
# Generate response
|
33 |
+
response = llm(transcription)[0]["generated_text"]
|
34 |
+
|
35 |
+
# Synthesize speech
|
36 |
+
tts_audio_path = audio_path.replace(".wav", "_reply.wav")
|
37 |
+
tts.tts_to_file(text=response, file_path=tts_audio_path)
|
38 |
+
|
39 |
+
return send_file(tts_audio_path, mimetype="audio/wav")
|
40 |
+
|
41 |
+
@app.route("/")
|
42 |
+
def index():
|
43 |
+
return "Metaverse AI Character API running."
|
44 |
+
|
45 |
+
if __name__ == "__main__":
|
46 |
+
app.run(host="0.0.0.0", port=7860)
|