CORVO-AI commited on
Commit
202da86
·
verified ·
1 Parent(s): 7162885

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -37
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
  import requests
3
- from flask import Flask, request, jsonify, send_file
4
  import uuid
5
 
6
  app = Flask(__name__)
@@ -56,8 +56,8 @@ def get_speechify_auth_token(firebase_token):
56
  else:
57
  raise Exception(f"❌ Failed to retrieve Speechify token. Status code: {response.status_code}, Response: {response.text}")
58
 
59
- def synthesize_speech(token, text, voice_id, output_file):
60
- """Generate speech audio using Speechify API"""
61
  url = "https://audio.api.speechify.com/v3/synthesis/get"
62
 
63
  headers = {
@@ -73,55 +73,42 @@ def synthesize_speech(token, text, voice_id, output_file):
73
  "forcedAudioFormat": "mp3"
74
  }
75
 
76
- try:
77
- response = requests.post(url, headers=headers, json=payload)
78
-
79
  if response.status_code == 200:
80
- with open(output_file, "wb") as f:
81
- f.write(response.content)
82
- print(f"✅ MP3 file saved as {output_file}")
83
- return True
84
  else:
85
- print(f"Failed to generate audio. Status code: {response.status_code}")
86
- print(response.text)
87
- return False
88
- except Exception as e:
89
- print(f"❌ An error occurred during speech synthesis: {str(e)}")
90
- return False
91
-
92
- # Create output directory if it doesn't exist
93
- os.makedirs("output", exist_ok=True)
94
 
95
  @app.route('/synthesize', methods=['POST'])
96
  def api_synthesize_speech():
97
- """API endpoint to synthesize speech from text"""
98
  try:
99
- # Get parameters from request
100
  data = request.json
101
 
102
  if not data:
103
  return jsonify({"error": "No JSON data provided"}), 400
104
 
105
  text = data.get('text')
106
- voice_id = data.get('voice_id', 'PVL:4f4a27ef-2b17-424f-904c-30bd1ed60fb8') # Default voice if not provided
107
 
108
  if not text:
109
  return jsonify({"error": "No text provided"}), 400
110
 
111
- # Generate a unique filename
112
- filename = f"output/{uuid.uuid4()}.mp3"
113
-
114
- # Get tokens and synthesize speech
115
  firebase_token = get_firebase_token()
116
  speechify_token = get_speechify_auth_token(firebase_token)
117
 
118
- result = synthesize_speech(speechify_token, text, voice_id, filename)
119
-
120
- if result:
121
- # Return the audio file
122
- return send_file(filename, mimetype='audio/mpeg', as_attachment=True)
123
- else:
124
- return jsonify({"error": "Failed to synthesize speech"}), 500
 
 
125
 
126
  except Exception as e:
127
  return jsonify({"error": str(e)}), 500
@@ -140,8 +127,8 @@ def home():
140
  </style>
141
  </head>
142
  <body>
143
- <h1>Speechify Text-to-Speech API</h1>
144
- <p>Use this API to convert text to speech using Speechify.</p>
145
 
146
  <h2>Endpoint</h2>
147
  <code>POST /synthesize</code>
@@ -158,11 +145,19 @@ def home():
158
  <pre>
159
  curl -X POST http://localhost:7860/synthesize \\
160
  -H "Content-Type: application/json" \\
161
- -d '{"text": "Hello, this is a test", "voice_id": "PVL:4f4a27ef-2b17-424f-904c-30bd1ed60fb8"}'
 
 
 
 
 
 
 
 
162
  </pre>
163
 
164
  <h2>Response</h2>
165
- <p>The API returns an MP3 audio file if successful, or a JSON error message if there's a problem.</p>
166
  </body>
167
  </html>
168
  """
 
1
  import os
2
  import requests
3
+ from flask import Flask, request, jsonify, Response
4
  import uuid
5
 
6
  app = Flask(__name__)
 
56
  else:
57
  raise Exception(f"❌ Failed to retrieve Speechify token. Status code: {response.status_code}, Response: {response.text}")
58
 
59
+ def stream_speech(token, text, voice_id):
60
+ """Generate speech audio using Speechify API and yield chunks"""
61
  url = "https://audio.api.speechify.com/v3/synthesis/get"
62
 
63
  headers = {
 
73
  "forcedAudioFormat": "mp3"
74
  }
75
 
76
+ with requests.post(url, headers=headers, json=payload, stream=True) as response:
 
 
77
  if response.status_code == 200:
78
+ for chunk in response.iter_content(chunk_size=4096):
79
+ if chunk:
80
+ yield chunk
 
81
  else:
82
+ raise Exception(f"Failed to generate audio. Status code: {response.status_code}, Response: {response.text}")
 
 
 
 
 
 
 
 
83
 
84
  @app.route('/synthesize', methods=['POST'])
85
  def api_synthesize_speech():
86
+ """API endpoint to synthesize speech from text and stream the audio back"""
87
  try:
 
88
  data = request.json
89
 
90
  if not data:
91
  return jsonify({"error": "No JSON data provided"}), 400
92
 
93
  text = data.get('text')
94
+ voice_id = data.get('voice_id', 'PVL:4f4a27ef-2b17-424f-904c-30bd1ed60fb8')
95
 
96
  if not text:
97
  return jsonify({"error": "No text provided"}), 400
98
 
99
+ # Get tokens
 
 
 
100
  firebase_token = get_firebase_token()
101
  speechify_token = get_speechify_auth_token(firebase_token)
102
 
103
+ # Stream the audio response
104
+ return Response(
105
+ stream_speech(speechify_token, text, voice_id),
106
+ content_type='audio/mpeg',
107
+ headers={
108
+ 'Content-Disposition': f'attachment; filename="{uuid.uuid4()}.mp3"',
109
+ 'Transfer-Encoding': 'chunked'
110
+ }
111
+ )
112
 
113
  except Exception as e:
114
  return jsonify({"error": str(e)}), 500
 
127
  </style>
128
  </head>
129
  <body>
130
+ <h1>Speechify Text-to-Speech API (Streaming)</h1>
131
+ <p>Use this API to convert text to speech using Speechify. Audio is streamed back in real-time.</p>
132
 
133
  <h2>Endpoint</h2>
134
  <code>POST /synthesize</code>
 
145
  <pre>
146
  curl -X POST http://localhost:7860/synthesize \\
147
  -H "Content-Type: application/json" \\
148
+ -d '{"text": "Hello, this is a test"}' \\
149
+ --output speech.mp3
150
+ </pre>
151
+
152
+ <h2>Example: Stream directly to a media player</h2>
153
+ <pre>
154
+ curl -X POST http://localhost:7860/synthesize \\
155
+ -H "Content-Type: application/json" \\
156
+ -d '{"text": "Hello, this is a streaming test"}' | mpv -
157
  </pre>
158
 
159
  <h2>Response</h2>
160
+ <p>The API streams back an MP3 audio file using chunked transfer encoding. No file is saved on the server.</p>
161
  </body>
162
  </html>
163
  """