Update app.py
Browse files
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 |
-
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
|
|
|
|
|
|
|
| 16 |
def split_text(text, max_length=500):
|
| 17 |
-
"""Splits text into
|
| 18 |
words = text.split()
|
| 19 |
-
chunks
|
|
|
|
|
|
|
| 20 |
|
| 21 |
for word in words:
|
| 22 |
-
if len(
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 31 |
return chunks
|
| 32 |
|
|
|
|
|
|
|
| 33 |
def call_tts_api(text, voice):
|
| 34 |
-
"""
|
| 35 |
-
filename = f"{SAVE_DIR}/audio_{uuid4().hex}.mp3"
|
| 36 |
-
|
| 37 |
try:
|
| 38 |
-
response = requests.post(
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
return
|
| 50 |
else:
|
| 51 |
-
print("Error: TTS API
|
| 52 |
return None
|
| 53 |
-
|
| 54 |
except Exception as e:
|
| 55 |
-
print("
|
| 56 |
return None
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 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 |
-
"""
|
| 100 |
-
file_path = os.path.join(
|
| 101 |
if os.path.exists(file_path):
|
| 102 |
-
return {"download_url":
|
| 103 |
-
|
| 104 |
-
|
| 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)
|