waxz commited on
Commit
367e4d1
·
1 Parent(s): 2b57786

improve text preprocess

Browse files
Files changed (1) hide show
  1. app.py +69 -38
app.py CHANGED
@@ -56,51 +56,77 @@ async def verify_api_key(credentials: HTTPAuthorizationCredentials = Security(se
56
  # 2. Text & Audio Utilities
57
  # -----------------------------------------------------------------------------
58
 
59
- def preprocess_text(text: str) -> str:
60
- if not text: return ""
61
- text = re.sub(r'\*.*?\*', '', text) # Remove actions
62
- # Remove Emojis/Symbols (Fixed SyntaxError from before)
63
- text = re.sub(r"[^\w\s,.:;?!'\"\-\u00C0-\u00FF]", '', text)
64
- text = re.sub(r'\s+', ' ', text).strip()
65
- return text
66
-
67
- def split_text_into_sentences(text: str):
68
  """
69
- Splits text by Newlines first, then by Punctuation (. ? ! : ;).
 
 
 
 
 
 
70
  """
71
- if not text: return []
 
 
 
 
 
 
 
 
 
 
72
 
73
- # 1. Split by physical lines (handles Headers/Lists)
74
- raw_lines = text.splitlines()
75
- final_chunks = []
76
 
77
- for line in raw_lines:
78
- line = re.sub(r'\s+', ' ', line).strip()
79
- if not line: continue
80
-
81
- # 2. Split by punctuation followed by space/end
82
- # Capture punctuation to re-attach it later
83
- parts = re.split(r'([.?!:;]+)(?=\s|$)', line)
84
-
85
- current_chunk = ""
86
- for part in parts:
87
- if not part: continue
88
 
89
- # If part is punctuation, attach to previous text and flush
90
- if re.match(r'^[.?!:;]+$', part):
91
- current_chunk += part
92
- if current_chunk.strip():
93
- final_chunks.append(current_chunk.strip())
94
- current_chunk = ""
95
- else:
96
- current_chunk += part
97
-
98
- # Flush remainder of the line
99
- if current_chunk.strip():
100
- final_chunks.append(current_chunk.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  return final_chunks
103
 
 
104
  # -----------------------------------------------------------------------------
105
  # 1. Utility Functions
106
  # -----------------------------------------------------------------------------
@@ -208,7 +234,12 @@ class StreamingEngine:
208
 
209
  yield create_wav_header(self.sample_rate)
210
 
211
- chunks = split_text_into_sentences(text)
 
 
 
 
 
212
  print(f"Streaming '{text[:20]}...' using voice: {resolved_name}")
213
 
214
  loop = asyncio.get_event_loop()
 
56
  # 2. Text & Audio Utilities
57
  # -----------------------------------------------------------------------------
58
 
59
+ def split_text_into_sentences(text: str, min_chunk_size: int = 150):
 
 
 
 
 
 
 
 
60
  """
61
+ Smart splitting for low-latency streaming.
62
+
63
+ Logic:
64
+ 1. Split text into "atomic" sentences (preserving punctuation).
65
+ 2. ALWAYS yield the first sentence immediately (fastest time-to-first-byte).
66
+ 3. For subsequent text, combine small sentences into larger chunks
67
+ (up to min_chunk_size) to improve GPU efficiency and sentence flow.
68
  """
69
+ if not text:
70
+ return []
71
+
72
+ # 1. Clean up extra whitespace (newlines become spaces for flow)
73
+ # We want a continuous stream of text for better merging
74
+ text = re.sub(r'\s+', ' ', text).strip()
75
+
76
+ # 2. Split into atomic sentences
77
+ # Pattern: Split by [.?!:;] but keep the delimiter.
78
+ # We look for punctuation followed by a space or end of string.
79
+ raw_parts = re.split(r'([.?!:;]+)(?=\s|$)', text)
80
 
81
+ atomic_sentences = []
82
+ current_atomic = ""
 
83
 
84
+ # Re-assemble the split parts (e.g. "Hello" + "." -> "Hello.")
85
+ for part in raw_parts:
86
+ if re.match(r'^[.?!:;]+$', part):
87
+ current_atomic += part
88
+ if current_atomic.strip():
89
+ atomic_sentences.append(current_atomic.strip())
90
+ current_atomic = ""
91
+ else:
92
+ current_atomic += part
 
 
93
 
94
+ if current_atomic.strip():
95
+ atomic_sentences.append(current_atomic.strip())
96
+
97
+ # 3. Batching Logic
98
+ final_chunks = []
99
+ current_buffer = ""
100
+ first_sentence_sent = False
101
+
102
+ for sentence in atomic_sentences:
103
+ # CASE A: The very first sentence.
104
+ # Send it immediately, no matter how short, to start audio playback.
105
+ if not first_sentence_sent:
106
+ final_chunks.append(sentence)
107
+ first_sentence_sent = True
108
+ continue
109
+
110
+ # CASE B: Subsequent sentences.
111
+ # Add to buffer.
112
+ if current_buffer:
113
+ current_buffer += " " + sentence
114
+ else:
115
+ current_buffer = sentence
116
+
117
+ # If buffer is long enough, flush it.
118
+ # This prevents generating audio for tiny fragments like "No." or "Ok."
119
+ if len(current_buffer) >= min_chunk_size:
120
+ final_chunks.append(current_buffer)
121
+ current_buffer = ""
122
+
123
+ # Flush any remaining text in the buffer
124
+ if current_buffer:
125
+ final_chunks.append(current_buffer)
126
 
127
  return final_chunks
128
 
129
+
130
  # -----------------------------------------------------------------------------
131
  # 1. Utility Functions
132
  # -----------------------------------------------------------------------------
 
234
 
235
  yield create_wav_header(self.sample_rate)
236
 
237
+ #chunks = split_text_into_sentences(text)
238
+ chunks = split_text_into_sentences(text, min_chunk_size=150)
239
+
240
+
241
+
242
+
243
  print(f"Streaming '{text[:20]}...' using voice: {resolved_name}")
244
 
245
  loop = asyncio.get_event_loop()