AdarshJi commited on
Commit
040ed19
1 Parent(s): 371feb6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -13
app.py CHANGED
@@ -3,41 +3,45 @@ import base64
3
  import uvicorn
4
  import json
5
  from flask import Flask, request, jsonify
6
- from flask import Response, stream_with_context
7
  import edge_tts
8
  import asyncio
9
 
10
  app = Flask(__name__)
11
 
 
 
 
12
 
13
- async def TextToAudioFile(text:str,model:str) -> str:
14
-
15
-
16
- file_path = r"main.mp3"
17
-
18
  if os.path.exists(file_path):
19
  os.remove(file_path)
20
 
 
21
  communicate = edge_tts.Communicate(text, voice=model, pitch='+5Hz', rate='+10%')
22
  await communicate.save(file_path)
23
 
 
24
  with open(file_path, 'rb') as audio_file:
25
  audio_data = audio_file.read()
26
  audio_base64 = base64.b64encode(audio_data).decode('utf-8')
27
 
28
  return audio_base64
29
 
30
-
31
-
32
-
33
-
34
  @app.route('/tts', methods=['POST'])
35
  def tts():
 
36
  data = request.get_json()
37
- text = data.get('text')
38
- model = data.get('model',"en-GB-SoniaNeural")
 
 
 
 
 
39
  audio_base64 = asyncio.run(TextToAudioFile(text,model))
 
40
  return jsonify({'audio': audio_base64}), 200
41
 
42
  if __name__ == '__main__':
43
- app.run(app)
 
 
3
  import uvicorn
4
  import json
5
  from flask import Flask, request, jsonify
 
6
  import edge_tts
7
  import asyncio
8
 
9
  app = Flask(__name__)
10
 
11
+ async def TextToAudioFile(text: str, model: str) -> str:
12
+ """Converts text to an audio file and returns its base64 encoded string."""
13
+ file_path = "main.mp3"
14
 
15
+ # Remove existing file if it exists
 
 
 
 
16
  if os.path.exists(file_path):
17
  os.remove(file_path)
18
 
19
+ # Convert text to audio
20
  communicate = edge_tts.Communicate(text, voice=model, pitch='+5Hz', rate='+10%')
21
  await communicate.save(file_path)
22
 
23
+ # Read the audio file and encode it to base64
24
  with open(file_path, 'rb') as audio_file:
25
  audio_data = audio_file.read()
26
  audio_base64 = base64.b64encode(audio_data).decode('utf-8')
27
 
28
  return audio_base64
29
 
 
 
 
 
30
  @app.route('/tts', methods=['POST'])
31
  def tts():
32
+ """Handles POST requests for text-to-speech conversion."""
33
  data = request.get_json()
34
+ model = data.get('model', 'en-GB-SoniaNeural')
35
+ if not data or 'text' not in data:
36
+ return jsonify({'error': 'Text is required'}), 400
37
+
38
+ text = data['text']
39
+
40
+ # Run the async function in the event loop
41
  audio_base64 = asyncio.run(TextToAudioFile(text,model))
42
+
43
  return jsonify({'audio': audio_base64}), 200
44
 
45
  if __name__ == '__main__':
46
+ # Run the Flask app
47
+ app.run(debug=True, port=5000)