hivecorp commited on
Commit
d0b1d85
Β·
verified Β·
1 Parent(s): 224a44e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -53
app.py CHANGED
@@ -1,76 +1,94 @@
1
  from fastapi import FastAPI, Query
 
2
  import requests
3
  import os
4
- import uvicorn
5
- from uuid import uuid4
6
  from pydub import AudioSegment
 
7
 
8
  app = FastAPI()
9
 
10
- TTS_API_URL = "https://hivecorp-s8test.hf.space/generate" # Replace with your TTS API URL
11
- SAVE_DIR = "generated_audios"
 
12
 
13
- # Ensure save directory exists
14
- os.makedirs(SAVE_DIR, exist_ok=True)
15
 
 
 
16
  def split_text(text, max_length=500):
17
- """Splits text into smaller chunks without breaking words."""
18
  words = text.split()
19
- chunks, chunk = [], []
 
 
20
 
21
  for word in words:
22
- if len(" ".join(chunk) + " " + word) <= max_length:
23
- chunk.append(word)
24
- else:
25
- chunks.append(" ".join(chunk))
26
- chunk = [word]
27
-
28
- if chunk:
29
- chunks.append(" ".join(chunk))
30
-
 
31
  return chunks
32
 
 
 
33
  def call_tts_api(text, voice):
34
- """Sends text to TTS API and retries if it fails."""
35
- filename = f"{SAVE_DIR}/audio_{uuid4().hex}.mp3"
36
-
37
  try:
38
- response = requests.post(TTS_API_URL, json={"text": text, "voice": voice})
39
- response_data = response.json()
40
- print("TTS API Response:", response_data) # Log response
 
 
 
41
 
42
- if "audio_url" in response_data:
43
- audio_url = response_data["audio_url"]
44
- audio_data = requests.get(audio_url).content
45
-
46
- with open(filename, "wb") as f:
47
- f.write(audio_data)
 
 
 
 
 
 
 
 
48
 
49
- return filename
50
  else:
51
- print("Error: TTS API did not return an audio URL!")
52
  return None
53
-
54
  except Exception as e:
55
- print("Error calling TTS API:", str(e))
56
  return None
57
 
58
- def merge_audio(files):
59
- """Merges multiple MP3 files into one."""
60
- output_file = f"{SAVE_DIR}/final_audio_{uuid4().hex}.mp3"
61
-
62
- try:
63
- combined = AudioSegment.from_file(files[0])
64
-
65
- for file in files[1:]:
66
- combined += AudioSegment.from_file(file)
67
-
68
- combined.export(output_file, format="mp3")
69
- return output_file
70
- except Exception as e:
71
- print("Error merging audio files:", str(e))
72
  return None
73
 
 
 
 
 
 
 
 
 
 
 
 
74
  @app.post("/generate-audio")
75
  def generate_audio(text: str = Query(...), voice: str = Query(...)):
76
  """Splits text, calls TTS API, merges audio, and returns the final MP3."""
@@ -94,15 +112,17 @@ def generate_audio(text: str = Query(...), voice: str = Query(...)):
94
  else:
95
  return {"error": "Failed to merge audio files"}
96
 
 
 
97
  @app.get("/download/{filename}")
98
  def download_file(filename: str):
99
- """Serves the generated MP3 file."""
100
- file_path = os.path.join(SAVE_DIR, filename)
101
  if os.path.exists(file_path):
102
- return {"download_url": file_path}
103
- else:
104
- return {"error": "File not found"}
105
 
106
- # Ensure the app starts when running in Hugging Face Spaces
107
  if __name__ == "__main__":
108
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  from fastapi import FastAPI, Query
2
+ import uvicorn
3
  import requests
4
  import os
 
 
5
  from pydub import AudioSegment
6
+ from uuid import uuid4
7
 
8
  app = FastAPI()
9
 
10
+ # βœ… Create directory to store audio files
11
+ AUDIO_DIR = "audio_files"
12
+ os.makedirs(AUDIO_DIR, exist_ok=True)
13
 
14
+ # βœ… Replace with your actual TTS API URL
15
+ TTS_API_URL = "https://your-tts-api.com/generate" # Change this
16
 
17
+
18
+ # πŸ”Ή Function: Splitting long text into smaller chunks
19
  def split_text(text, max_length=500):
20
+ """Splits text into chunks of max_length characters"""
21
  words = text.split()
22
+ chunks = []
23
+ current_chunk = []
24
+ current_length = 0
25
 
26
  for word in words:
27
+ if current_length + len(word) + 1 > max_length:
28
+ chunks.append(" ".join(current_chunk))
29
+ current_chunk = []
30
+ current_length = 0
31
+ current_chunk.append(word)
32
+ current_length += len(word) + 1
33
+
34
+ if current_chunk:
35
+ chunks.append(" ".join(current_chunk))
36
+
37
  return chunks
38
 
39
+
40
+ # πŸ”Ή Function: Call external TTS API
41
  def call_tts_api(text, voice):
42
+ """Calls external TTS API and returns the saved MP3 filename."""
 
 
43
  try:
44
+ response = requests.post(
45
+ TTS_API_URL,
46
+ json={"text": text, "voice": voice},
47
+ headers={"Content-Type": "application/json"}
48
+ )
49
+ data = response.json()
50
 
51
+ # βœ… Log response for debugging
52
+ print("TTS API Response:", data)
53
+
54
+ if "audio_url" in data:
55
+ audio_url = data["audio_url"]
56
+ filename = f"audio_{uuid4().hex}.mp3"
57
+ audio_path = os.path.join(AUDIO_DIR, filename)
58
+
59
+ # βœ… Download the MP3 file
60
+ with requests.get(audio_url, stream=True) as r:
61
+ r.raise_for_status()
62
+ with open(audio_path, "wb") as f:
63
+ for chunk in r.iter_content(chunk_size=8192):
64
+ f.write(chunk)
65
 
66
+ return audio_path # βœ… Return saved file path
67
  else:
68
+ print("Error: Invalid TTS API response", data)
69
  return None
 
70
  except Exception as e:
71
+ print("TTS API Error:", e)
72
  return None
73
 
74
+
75
+ # πŸ”Ή Function: Merge multiple MP3s into one
76
+ def merge_audio(audio_files):
77
+ """Merges multiple MP3 files into one final MP3."""
78
+ if not audio_files:
 
 
 
 
 
 
 
 
 
79
  return None
80
 
81
+ final_audio = AudioSegment.empty()
82
+ for file in audio_files:
83
+ final_audio += AudioSegment.from_mp3(file)
84
+
85
+ final_filename = f"{AUDIO_DIR}/final_{uuid4().hex}.mp3"
86
+ final_audio.export(final_filename, format="mp3")
87
+
88
+ return final_filename
89
+
90
+
91
+ # βœ… API Endpoint: Generate Audio from Text
92
  @app.post("/generate-audio")
93
  def generate_audio(text: str = Query(...), voice: str = Query(...)):
94
  """Splits text, calls TTS API, merges audio, and returns the final MP3."""
 
112
  else:
113
  return {"error": "Failed to merge audio files"}
114
 
115
+
116
+ # βœ… API Endpoint: Download the generated MP3
117
  @app.get("/download/{filename}")
118
  def download_file(filename: str):
119
+ """Allows users to download the generated MP3 file."""
120
+ file_path = os.path.join(AUDIO_DIR, filename)
121
  if os.path.exists(file_path):
122
+ return {"download_url": f"https://hivecorp-manager1.hf.space/audio_files/{filename}"}
123
+ return {"error": "File not found"}
124
+
125
 
126
+ # βœ… Ensure the app starts when running in Hugging Face Spaces
127
  if __name__ == "__main__":
128
  uvicorn.run(app, host="0.0.0.0", port=7860)