Niansuh commited on
Commit
b0662ae
·
verified ·
1 Parent(s): 4119088

Update tts_script.py

Browse files
Files changed (1) hide show
  1. tts_script.py +35 -53
tts_script.py CHANGED
@@ -2,8 +2,8 @@ import time
2
  import requests
3
  import pathlib
4
  from io import BytesIO
5
- from flask import Flask, request, jsonify, send_file
6
- from concurrent.futures import ThreadPoolExecutor, as_completed
7
 
8
  # Flask App Setup
9
  app = Flask(__name__)
@@ -11,11 +11,9 @@ app = Flask(__name__)
11
  # ElevenLabs API Configuration
12
  ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"
13
  HEADERS = {"User-Agent": "TTSApp"}
14
- # Change cache directory to a writable location
15
  CACHE_DIR = pathlib.Path("/tmp/audio_cache")
16
  CACHE_DIR.mkdir(parents=True, exist_ok=True)
17
 
18
-
19
  # Available Voices
20
  ALL_VOICES = {
21
  "Brian": "nPczCjzI2devNBz1zQrb",
@@ -35,65 +33,49 @@ def generate_audio(text, voice):
35
  filename = CACHE_DIR / f"{int(time.time())}.mp3"
36
  sentences = split_sentences(text)
37
 
38
- def fetch_audio(sentence, part_number):
39
- try:
40
- response = requests.post(
41
- f"{ELEVENLABS_API_URL}/{ALL_VOICES[voice]}",
42
- headers=HEADERS,
43
- json={"text": sentence, "model_id": "eleven_multilingual_v2"},
44
- timeout=20
45
- )
46
- response.raise_for_status()
47
- return part_number, response.content
48
- except requests.RequestException:
49
- return part_number, None
50
-
51
- audio_chunks = {}
52
- with ThreadPoolExecutor() as executor:
53
- futures = {executor.submit(fetch_audio, sentence.strip(), i): i for i, sentence in enumerate(sentences)}
54
-
55
- for future in as_completed(futures):
56
- part_number, audio_data = future.result()
57
- if audio_data:
58
- audio_chunks[part_number] = audio_data
59
-
60
- combined_audio = BytesIO()
61
- for part_number in sorted(audio_chunks.keys()):
62
- combined_audio.write(audio_chunks[part_number])
63
-
64
- with open(filename, "wb") as f:
65
- f.write(combined_audio.getvalue())
66
-
67
  return filename.as_posix()
68
 
69
  # Flask Routes
70
- @app.route("/")
71
  def home():
72
- return '''
73
- <h1>Text-to-Speech API</h1>
74
- <form action="/tts" method="post">
75
- <label>Text:</label>
76
- <input type="text" name="text" required>
 
 
 
 
 
 
77
  <label>Voice:</label>
78
  <select name="voice">
79
  <option value="Brian">Brian</option>
80
  <option value="Alice">Alice</option>
81
  <option value="Will">Will</option>
82
- </select>
83
- <button type="submit">Generate</button>
84
  </form>
85
- '''
86
-
87
- @app.route("/tts", methods=["POST"])
88
- def tts():
89
- text = request.form.get("text")
90
- voice = request.form.get("voice", "Brian")
91
-
92
- if not text:
93
- return jsonify({"error": "Text is required!"})
94
-
95
- audio_file = generate_audio(text, voice)
96
- return send_file(audio_file, as_attachment=True)
97
 
98
  if __name__ == "__main__":
99
  app.run(debug=True, host="0.0.0.0", port=5000)
 
2
  import requests
3
  import pathlib
4
  from io import BytesIO
5
+ from flask import Flask, request, render_template, send_file
6
+ from pydub import AudioSegment
7
 
8
  # Flask App Setup
9
  app = Flask(__name__)
 
11
  # ElevenLabs API Configuration
12
  ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"
13
  HEADERS = {"User-Agent": "TTSApp"}
 
14
  CACHE_DIR = pathlib.Path("/tmp/audio_cache")
15
  CACHE_DIR.mkdir(parents=True, exist_ok=True)
16
 
 
17
  # Available Voices
18
  ALL_VOICES = {
19
  "Brian": "nPczCjzI2devNBz1zQrb",
 
33
  filename = CACHE_DIR / f"{int(time.time())}.mp3"
34
  sentences = split_sentences(text)
35
 
36
+ audio_chunks = []
37
+ for sentence in sentences:
38
+ response = requests.post(
39
+ f"{ELEVENLABS_API_URL}/{ALL_VOICES[voice]}",
40
+ headers=HEADERS,
41
+ json={"text": sentence, "model_id": "eleven_multilingual_v2"},
42
+ timeout=20
43
+ )
44
+ if response.ok:
45
+ audio_chunks.append(BytesIO(response.content))
46
+
47
+ # Combine all audio parts
48
+ combined_audio = AudioSegment.empty()
49
+ for chunk in audio_chunks:
50
+ chunk_audio = AudioSegment.from_file(chunk, format="mp3")
51
+ combined_audio += chunk_audio
52
+
53
+ combined_audio.export(filename, format="mp3")
 
 
 
 
 
 
 
 
 
 
 
54
  return filename.as_posix()
55
 
56
  # Flask Routes
57
+ @app.route("/", methods=["GET", "POST"])
58
  def home():
59
+ if request.method == "POST":
60
+ text = request.form["text"]
61
+ voice = request.form.get("voice", "Brian")
62
+ audio_file = generate_audio(text, voice)
63
+ return send_file(audio_file, as_attachment=True)
64
+
65
+ return """
66
+ <h1>Text-to-Speech Generator</h1>
67
+ <form method="post">
68
+ <label>Text:</label><br>
69
+ <textarea name="text" rows="4" cols="50" required></textarea><br>
70
  <label>Voice:</label>
71
  <select name="voice">
72
  <option value="Brian">Brian</option>
73
  <option value="Alice">Alice</option>
74
  <option value="Will">Will</option>
75
+ </select><br><br>
76
+ <button type="submit">Generate & Download</button>
77
  </form>
78
+ """
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  if __name__ == "__main__":
81
  app.run(debug=True, host="0.0.0.0", port=5000)