mr-don88 commited on
Commit
604e971
·
verified ·
1 Parent(s): ddcd17d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -43
app.py CHANGED
@@ -1701,90 +1701,108 @@ class AudioProcessor:
1701
  return combined
1702
 
1703
  class SubtitleGenerator:
1704
- @staticmethod
1705
- def clean_subtitle_text(text: str) -> str:
1706
- """Remove Q:/A:/CHARx: prefixes from subtitle text"""
1707
- # Remove all speaker prefixes and extra spaces
1708
- cleaned = re.sub(r'^(Q|A|CHAR\d+):\s*', '', text.strip())
1709
- return cleaned
1710
-
1711
  @staticmethod
1712
  def split_long_sentences(text: str, max_length: int = 120) -> List[str]:
1713
  """Split long sentences at punctuation marks while preserving meaning"""
 
 
 
1714
  sentences = []
1715
  current = ""
1716
 
1717
- # Split at punctuation first
1718
- parts = re.split(r'([.!?])', text)
1719
 
1720
  # Recombine with punctuation but check length
1721
- for i in range(0, len(parts)-1, 2):
1722
  part = parts[i] + (parts[i+1] if i+1 < len(parts) else "")
 
1723
  if len(current + part) <= max_length:
1724
  current += part
1725
  else:
1726
  if current:
1727
- sentences.append(current)
1728
  current = part
 
 
 
 
 
 
 
 
 
 
 
1729
 
1730
- if current:
1731
- sentences.append(current)
1732
 
1733
  return sentences
1734
 
1735
  @staticmethod
1736
- def generate_srt(self, audio_segments: List[AudioSegment], sentences: List[str], pause_settings: Dict[str, int]) -> str:
1737
- """Generate SRT format subtitles with precise timing information"""
 
 
 
 
 
 
1738
  subtitles = []
1739
- current_time = 150 # Start with initial silence (150ms)
1740
- max_subtitle_length = 120 # Maximum characters per subtitle line
1741
 
1742
  for i, (seg, sentence) in enumerate(zip(audio_segments, sentences)):
1743
- # Thêm dòng này để làm sạch câu trước khi xử lý
1744
- cleaned_sentence = self.text_processor.clean_text(sentence)
1745
-
1746
- # Split long sentences into smaller chunks at punctuation
1747
- sentence_chunks = SubtitleGenerator.split_long_sentences(cleaned_sentence, max_subtitle_length)
 
1748
 
1749
- # Calculate duration per chunk (equal division for simplicity)
1750
  chunk_duration = len(seg) / max(1, len(sentence_chunks))
1751
 
1752
  for j, chunk in enumerate(sentence_chunks):
1753
- start_time = current_time + (j * chunk_duration)
1754
- end_time = start_time + chunk_duration
1755
 
1756
- # Add subtitle entry
1757
  subtitles.append({
1758
- 'start': int(start_time),
1759
- 'end': int(end_time),
1760
- 'text': chunk.strip()
 
1761
  })
1762
 
1763
- # Update current time with segment duration
1764
  current_time += len(seg)
1765
 
1766
- # Add pause if not the last segment
1767
  if i < len(audio_segments) - 1:
1768
  pause = AudioProcessor.calculate_pause(sentence, pause_settings)
1769
- current_time += max(100, pause)
1770
 
1771
- # Convert to SRT format with precise timing
1772
- srt_content = []
1773
- for idx, sub in enumerate(subtitles, 1):
1774
- start_time = timedelta(milliseconds=sub['start'])
1775
- end_time = timedelta(milliseconds=sub['end'])
 
 
 
 
1776
 
1777
- # Format: 00:00:01,040 --> 00:00:09,760
1778
- start_str = f"{start_time.total_seconds() // 3600:02.0f}:{(start_time.total_seconds() % 3600) // 60:02.0f}:{start_time.total_seconds() % 60:06.3f}".replace('.', ',')
1779
- end_str = f"{end_time.total_seconds() // 3600:02.0f}:{(end_time.total_seconds() % 3600) // 60:02.0f}:{end_time.total_seconds() % 60:06.3f}".replace('.', ',')
1780
 
1781
- srt_content.append(
1782
- f"{idx}\n"
1783
  f"{start_str} --> {end_str}\n"
1784
  f"{sub['text']}\n"
1785
  )
1786
 
1787
- return "\n".join(srt_content)
1788
 
1789
  class TTSGenerator:
1790
  def __init__(self):
 
1701
  return combined
1702
 
1703
  class SubtitleGenerator:
 
 
 
 
 
 
 
1704
  @staticmethod
1705
  def split_long_sentences(text: str, max_length: int = 120) -> List[str]:
1706
  """Split long sentences at punctuation marks while preserving meaning"""
1707
+ if not text:
1708
+ return []
1709
+
1710
  sentences = []
1711
  current = ""
1712
 
1713
+ # Split at punctuation first (keeping the delimiters)
1714
+ parts = re.split(r'([.,!?;])', text)
1715
 
1716
  # Recombine with punctuation but check length
1717
+ for i in range(0, len(parts), 2):
1718
  part = parts[i] + (parts[i+1] if i+1 < len(parts) else "")
1719
+
1720
  if len(current + part) <= max_length:
1721
  current += part
1722
  else:
1723
  if current:
1724
+ sentences.append(current.strip())
1725
  current = part
1726
+ # If a single part is too long, force split by space
1727
+ if len(current) > max_length:
1728
+ words = current.split()
1729
+ current = ""
1730
+ for word in words:
1731
+ if len(current + word) <= max_length:
1732
+ current += word + " "
1733
+ else:
1734
+ if current:
1735
+ sentences.append(current.strip())
1736
+ current = word + " "
1737
 
1738
+ if current.strip():
1739
+ sentences.append(current.strip())
1740
 
1741
  return sentences
1742
 
1743
  @staticmethod
1744
+ def generate_srt(audio_segments: List[AudioSegment],
1745
+ sentences: List[str],
1746
+ pause_settings: Dict[str, int],
1747
+ text_processor) -> str:
1748
+ """Generate SRT format subtitles with precise timing"""
1749
+ if len(audio_segments) != len(sentences):
1750
+ raise ValueError("Audio segments and sentences must have same length")
1751
+
1752
  subtitles = []
1753
+ current_time = 150 # Initial silence (150ms)
 
1754
 
1755
  for i, (seg, sentence) in enumerate(zip(audio_segments, sentences)):
1756
+ # Clean and process text
1757
+ cleaned_sentence = text_processor.clean_text(sentence)
1758
+ sentence_chunks = SubtitleGenerator.split_long_sentences(
1759
+ cleaned_sentence,
1760
+ max_length=120
1761
+ )
1762
 
1763
+ # Calculate timing
1764
  chunk_duration = len(seg) / max(1, len(sentence_chunks))
1765
 
1766
  for j, chunk in enumerate(sentence_chunks):
1767
+ start_ms = current_time + (j * chunk_duration)
1768
+ end_ms = start_ms + chunk_duration
1769
 
 
1770
  subtitles.append({
1771
+ 'index': len(subtitles) + 1,
1772
+ 'start': start_ms,
1773
+ 'end': end_ms,
1774
+ 'text': chunk
1775
  })
1776
 
1777
+ # Update time with segment duration
1778
  current_time += len(seg)
1779
 
1780
+ # Add pause between segments
1781
  if i < len(audio_segments) - 1:
1782
  pause = AudioProcessor.calculate_pause(sentence, pause_settings)
1783
+ current_time += max(100, pause) # Minimum 100ms pause
1784
 
1785
+ # Format to SRT
1786
+ srt_lines = []
1787
+ for sub in subtitles:
1788
+ start_td = timedelta(milliseconds=sub['start'])
1789
+ end_td = timedelta(milliseconds=sub['end'])
1790
+
1791
+ start_str = f"{start_td.total_seconds() // 3600:02.0f}:" \
1792
+ f"{(start_td.total_seconds() % 3600) // 60:02.0f}:" \
1793
+ f"{start_td.total_seconds() % 60:06.3f}".replace('.', ',')
1794
 
1795
+ end_str = f"{end_td.total_seconds() // 3600:02.0f}:" \
1796
+ f"{(end_td.total_seconds() % 3600) // 60:02.0f}:" \
1797
+ f"{end_td.total_seconds() % 60:06.3f}".replace('.', ',')
1798
 
1799
+ srt_lines.append(
1800
+ f"{sub['index']}\n"
1801
  f"{start_str} --> {end_str}\n"
1802
  f"{sub['text']}\n"
1803
  )
1804
 
1805
+ return "\n".join(srt_lines)
1806
 
1807
  class TTSGenerator:
1808
  def __init__(self):