hivecorp commited on
Commit
9e1fa9a
·
verified ·
1 Parent(s): 42fcedf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -23
app.py CHANGED
@@ -11,9 +11,9 @@ from pydub import AudioSegment
11
  app = FastAPI()
12
 
13
  def split_text(text, max_chunk_size=500):
14
- """Split text into chunks only if it's longer than max_chunk_size."""
15
  if len(text) <= max_chunk_size:
16
- return [text] # No need to split if it's within the limit
17
 
18
  sentences = text.replace('।', '.').replace('؟', '?').split('.')
19
  chunks = []
@@ -38,8 +38,8 @@ def split_text(text, max_chunk_size=500):
38
  return chunks
39
 
40
  async def process_chunk(text, voice, temp_dir, chunk_index):
41
- """Process a single chunk of text into an MP3 file."""
42
- tmp_path = os.path.join(temp_dir, f"chunk_{chunk_index}_{int(time.time())}_{os.urandom(4).hex()}.mp3")
43
  communicate = edge_tts.Communicate(text, voice)
44
  await communicate.save(tmp_path)
45
  return tmp_path
@@ -56,7 +56,7 @@ async def combine_audio_files(chunk_files):
56
  combined.export(output, format="mp3")
57
  output.seek(0)
58
 
59
- # Clean up temp files
60
  for file in chunk_files:
61
  try:
62
  os.remove(file)
@@ -74,26 +74,34 @@ async def tts(text: str, voice: str = "en-US-AriaNeural"):
74
  if not text.strip():
75
  return {"error": "Text cannot be empty."}
76
 
77
- text_chunks = split_text(text) # Split only if necessary
78
 
79
- if len(text_chunks) == 1:
80
- # Process the entire text as a single request if it's within limit
81
- output_audio = io.BytesIO()
82
- communicate = edge_tts.Communicate(text_chunks[0], voice)
83
- await communicate.save(output_audio)
84
- output_audio.seek(0)
85
-
86
- return StreamingResponse(output_audio, media_type="audio/mpeg", headers={"Content-Disposition": "attachment; filename=speech.mp3"})
87
-
88
- # If text is split into chunks, process them individually
89
- with TemporaryDirectory() as temp_dir:
90
- chunk_files = await asyncio.gather(*[
91
- process_chunk(chunk, voice, temp_dir, i) for i, chunk in enumerate(text_chunks)
92
- ])
93
 
94
- output_audio = await combine_audio_files(chunk_files)
95
-
96
- return StreamingResponse(output_audio, media_type="audio/mpeg", headers={"Content-Disposition": "attachment; filename=speech.mp3"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
  import uvicorn
 
11
  app = FastAPI()
12
 
13
  def split_text(text, max_chunk_size=500):
14
+ """Split text into chunks if it exceeds max_chunk_size."""
15
  if len(text) <= max_chunk_size:
16
+ return [text]
17
 
18
  sentences = text.replace('।', '.').replace('؟', '?').split('.')
19
  chunks = []
 
38
  return chunks
39
 
40
  async def process_chunk(text, voice, temp_dir, chunk_index):
41
+ """Process a single chunk into an MP3 file."""
42
+ tmp_path = os.path.join(temp_dir, f"chunk_{chunk_index}_{int(time.time())}.mp3")
43
  communicate = edge_tts.Communicate(text, voice)
44
  await communicate.save(tmp_path)
45
  return tmp_path
 
56
  combined.export(output, format="mp3")
57
  output.seek(0)
58
 
59
+ # Cleanup chunk files
60
  for file in chunk_files:
61
  try:
62
  os.remove(file)
 
74
  if not text.strip():
75
  return {"error": "Text cannot be empty."}
76
 
77
+ text_chunks = split_text(text) # Only splits if text > 500 characters
78
 
79
+ async def event_stream():
80
+ """Send real-time status updates to the client while processing."""
81
+ yield "Processing started...\n"
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ if len(text_chunks) == 1:
84
+ # Single request processing
85
+ output_audio = io.BytesIO()
86
+ communicate = edge_tts.Communicate(text_chunks[0], voice)
87
+ await communicate.save(output_audio)
88
+ output_audio.seek(0)
89
+ yield "Processing completed. Downloading audio...\n"
90
+ yield output_audio.read()
91
+ return
92
+
93
+ with TemporaryDirectory() as temp_dir:
94
+ # Process all chunks concurrently
95
+ tasks = [process_chunk(chunk, voice, temp_dir, i) for i, chunk in enumerate(text_chunks)]
96
+ chunk_files = await asyncio.gather(*tasks)
97
+
98
+ yield f"Processing {len(text_chunks)} chunks completed. Merging audio...\n"
99
+ output_audio = await combine_audio_files(chunk_files)
100
+
101
+ yield "Merging completed. Downloading final audio...\n"
102
+ yield output_audio.read()
103
+
104
+ return StreamingResponse(event_stream(), media_type="audio/mpeg")
105
 
106
  if __name__ == "__main__":
107
  import uvicorn