areksmyk commited on
Commit
4a434ae
verified
1 Parent(s): 4387559

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -49
app.py CHANGED
@@ -19,6 +19,7 @@ class TranscriptionService:
19
  """Klasa do zarz膮dzania modelami ASR na r贸偶nych urz膮dzeniach."""
20
 
21
  def __init__(self):
 
22
  self.models = {
23
  'mps': None,
24
  'cuda': None,
@@ -31,25 +32,15 @@ class TranscriptionService:
31
  def _get_optimal_device(self, audio_length_minutes: float) -> str:
32
  """
33
  Wybiera optymalne urz膮dzenie na podstawie d艂ugo艣ci audio i dost臋pno艣ci sprz臋tu.
34
-
35
- Args:
36
- audio_length_minutes: D艂ugo艣膰 audio w minutach
37
-
38
- Returns:
39
- str: Nazwa urz膮dzenia ('mps', 'cuda' lub 'cpu')
40
  """
41
- # Sprawd藕 CUDA jako pierwszy wyb贸r dla wszystkich d艂ugo艣ci
42
  if torch.cuda.is_available():
43
  logger.info("U偶ywam CUDA (GPU) - najlepsza wydajno艣膰")
44
  return "cuda"
45
 
46
-
47
- # MPS tylko dla kr贸tszych plik贸w
48
  if torch.backends.mps.is_available() and audio_length_minutes <= 8:
49
  logger.info(f"Plik kr贸tki ({audio_length_minutes:.2f} min) - u偶ywam MPS")
50
  return "mps"
51
 
52
- # CPU jako fallback
53
  if torch.backends.mps.is_available() and audio_length_minutes > 8:
54
  logger.info(f"Plik d艂ugi ({audio_length_minutes:.2f} min) - u偶ywam CPU zamiast MPS")
55
  else:
@@ -60,12 +51,6 @@ class TranscriptionService:
60
  def _load_model(self, device: str) -> nemo_asr.models.ASRModel:
61
  """
62
  艁aduje model na okre艣lonym urz膮dzeniu (z cache'owaniem).
63
-
64
- Args:
65
- device: Urz膮dzenie docelowe
66
-
67
- Returns:
68
- Za艂adowany model ASR
69
  """
70
  if self.models[device] is None:
71
  logger.info(f"艁adowanie modelu na {device.upper()}...")
@@ -84,13 +69,6 @@ class TranscriptionService:
84
  def _split_audio(self, audio_file_path: str, chunk_length_ms: int) -> list:
85
  """
86
  Dzieli d艂ugi plik audio na mniejsze fragmenty.
87
-
88
- Args:
89
- audio_file_path: 艢cie偶ka do pliku audio
90
- chunk_length_ms: D艂ugo艣膰 fragmentu w milisekundach
91
-
92
- Returns:
93
- list: Lista 艣cie偶ek do plik贸w tymczasowych
94
  """
95
  audio = AudioSegment.from_file(audio_file_path)
96
  chunks = []
@@ -105,19 +83,14 @@ class TranscriptionService:
105
  def _transcribe_with_timeout(self, audio_file_path: str, device: str) -> str:
106
  """
107
  Wykonuje transkrypcj臋 z timeoutem.
108
-
109
- Args:
110
- audio_file_path: 艢cie偶ka do pliku audio
111
- device: Urz膮dzenie do transkrypcji
112
-
113
- Returns:
114
- str: Transkrypcja
115
  """
 
 
 
116
  result = {"text": None, "error": None}
117
 
118
  def transcribe_worker():
119
  try:
120
- model = self._load_model(device)
121
  transcriptions = model.transcribe([audio_file_path])
122
  if transcriptions and len(transcriptions) > 0:
123
  result["text"] = transcriptions[0].text
@@ -141,31 +114,20 @@ class TranscriptionService:
141
  def transcribe(self, audio_file_path: str, progress=None) -> str:
142
  """
143
  G艂贸wna funkcja transkrypcji.
144
-
145
- Args:
146
- audio_file_path: 艢cie偶ka do pliku audio
147
- progress: Obiekt progress Gradio (opcjonalnie)
148
-
149
- Returns:
150
- str: Transkrypcja lub komunikat b艂臋du
151
  """
152
- # Walidacja pliku
153
  if not audio_file_path or not os.path.exists(audio_file_path):
154
  return "B艂膮d: Nie wybrano pliku audio lub plik nie istnieje."
155
 
156
  temp_files = []
157
 
158
  try:
159
- # Analiza d艂ugo艣ci pliku
160
  logger.info(f"Analizuj臋 plik: {os.path.basename(audio_file_path)}")
161
  audio = AudioSegment.from_file(audio_file_path)
162
  length_minutes = len(audio) / (1000 * 60)
163
  logger.info(f"D艂ugo艣膰 pliku: {length_minutes:.2f} minut")
164
 
165
- # Wyb贸r optymalnego urz膮dzenia
166
  device = self._get_optimal_device(length_minutes)
167
 
168
- # Dziel d艂ugie pliki na fragmenty
169
  if length_minutes > self.chunk_length_minutes:
170
  if progress:
171
  progress(0.1, desc="Dziel臋 plik na fragmenty...")
@@ -190,7 +152,6 @@ class TranscriptionService:
190
 
191
  result_text = " ".join(all_transcriptions)
192
  else:
193
- # Kr贸tkie pliki - transkrypcja ca艂o艣ci
194
  if progress:
195
  progress(0.5, desc="Rozpoczynam transkrypcj臋...")
196
 
@@ -213,7 +174,6 @@ class TranscriptionService:
213
  logger.error(error_msg)
214
  return error_msg
215
  finally:
216
- # Sprz膮tanie plik贸w tymczasowych
217
  for temp_file in temp_files:
218
  try:
219
  os.remove(temp_file)
@@ -248,12 +208,13 @@ def create_interface() -> gr.Interface:
248
  **Obs艂ugiwane formaty:** WAV, MP3, FLAC, M4A i inne
249
  **Optymalizacja urz膮dzenia:** Automatyczny wyb贸r GPU/CPU
250
  """,
 
 
251
  flagging_options=None,
252
  allow_flagging="never"
253
  )
254
 
255
  if __name__ == "__main__":
256
- # Informacje o dost臋pnych urz膮dzeniach
257
  logger.info("=== Informacje o systemie ===")
258
  logger.info(f"CUDA dost臋pne: {torch.cuda.is_available()}")
259
  logger.info(f"MPS dost臋pne: {torch.backends.mps.is_available()}")
@@ -261,12 +222,11 @@ if __name__ == "__main__":
261
  if torch.cuda.is_available():
262
  logger.info(f"GPU: {torch.cuda.get_device_name(0)}")
263
 
264
- # Uruchomienie interfejsu
265
  interface = create_interface()
266
  interface.launch(
267
- server_name="127.0.0.1", # Bezpieczniejsze ni偶 domy艣lne
268
  server_port=7860,
269
- share=False, # Nie udost臋pniaj publicznie
270
- debug=False, # Wy艂膮cz w produkcji
271
  show_error=True
272
  )
 
19
  """Klasa do zarz膮dzania modelami ASR na r贸偶nych urz膮dzeniach."""
20
 
21
  def __init__(self):
22
+ # Usuni臋cie wst臋pnego 艂adowania. Modele b臋d膮 艂adowane dynamicznie
23
  self.models = {
24
  'mps': None,
25
  'cuda': None,
 
32
  def _get_optimal_device(self, audio_length_minutes: float) -> str:
33
  """
34
  Wybiera optymalne urz膮dzenie na podstawie d艂ugo艣ci audio i dost臋pno艣ci sprz臋tu.
 
 
 
 
 
 
35
  """
 
36
  if torch.cuda.is_available():
37
  logger.info("U偶ywam CUDA (GPU) - najlepsza wydajno艣膰")
38
  return "cuda"
39
 
 
 
40
  if torch.backends.mps.is_available() and audio_length_minutes <= 8:
41
  logger.info(f"Plik kr贸tki ({audio_length_minutes:.2f} min) - u偶ywam MPS")
42
  return "mps"
43
 
 
44
  if torch.backends.mps.is_available() and audio_length_minutes > 8:
45
  logger.info(f"Plik d艂ugi ({audio_length_minutes:.2f} min) - u偶ywam CPU zamiast MPS")
46
  else:
 
51
  def _load_model(self, device: str) -> nemo_asr.models.ASRModel:
52
  """
53
  艁aduje model na okre艣lonym urz膮dzeniu (z cache'owaniem).
 
 
 
 
 
 
54
  """
55
  if self.models[device] is None:
56
  logger.info(f"艁adowanie modelu na {device.upper()}...")
 
69
  def _split_audio(self, audio_file_path: str, chunk_length_ms: int) -> list:
70
  """
71
  Dzieli d艂ugi plik audio na mniejsze fragmenty.
 
 
 
 
 
 
 
72
  """
73
  audio = AudioSegment.from_file(audio_file_path)
74
  chunks = []
 
83
  def _transcribe_with_timeout(self, audio_file_path: str, device: str) -> str:
84
  """
85
  Wykonuje transkrypcj臋 z timeoutem.
 
 
 
 
 
 
 
86
  """
87
+ # 艁adowanie modelu przeniesione tutaj
88
+ model = self._load_model(device)
89
+
90
  result = {"text": None, "error": None}
91
 
92
  def transcribe_worker():
93
  try:
 
94
  transcriptions = model.transcribe([audio_file_path])
95
  if transcriptions and len(transcriptions) > 0:
96
  result["text"] = transcriptions[0].text
 
114
  def transcribe(self, audio_file_path: str, progress=None) -> str:
115
  """
116
  G艂贸wna funkcja transkrypcji.
 
 
 
 
 
 
 
117
  """
 
118
  if not audio_file_path or not os.path.exists(audio_file_path):
119
  return "B艂膮d: Nie wybrano pliku audio lub plik nie istnieje."
120
 
121
  temp_files = []
122
 
123
  try:
 
124
  logger.info(f"Analizuj臋 plik: {os.path.basename(audio_file_path)}")
125
  audio = AudioSegment.from_file(audio_file_path)
126
  length_minutes = len(audio) / (1000 * 60)
127
  logger.info(f"D艂ugo艣膰 pliku: {length_minutes:.2f} minut")
128
 
 
129
  device = self._get_optimal_device(length_minutes)
130
 
 
131
  if length_minutes > self.chunk_length_minutes:
132
  if progress:
133
  progress(0.1, desc="Dziel臋 plik na fragmenty...")
 
152
 
153
  result_text = " ".join(all_transcriptions)
154
  else:
 
155
  if progress:
156
  progress(0.5, desc="Rozpoczynam transkrypcj臋...")
157
 
 
174
  logger.error(error_msg)
175
  return error_msg
176
  finally:
 
177
  for temp_file in temp_files:
178
  try:
179
  os.remove(temp_file)
 
208
  **Obs艂ugiwane formaty:** WAV, MP3, FLAC, M4A i inne
209
  **Optymalizacja urz膮dzenia:** Automatyczny wyb贸r GPU/CPU
210
  """,
211
+ examples=None,
212
+ cache_examples=False,
213
  flagging_options=None,
214
  allow_flagging="never"
215
  )
216
 
217
  if __name__ == "__main__":
 
218
  logger.info("=== Informacje o systemie ===")
219
  logger.info(f"CUDA dost臋pne: {torch.cuda.is_available()}")
220
  logger.info(f"MPS dost臋pne: {torch.backends.mps.is_available()}")
 
222
  if torch.cuda.is_available():
223
  logger.info(f"GPU: {torch.cuda.get_device_name(0)}")
224
 
 
225
  interface = create_interface()
226
  interface.launch(
227
+ server_name="0.0.0.0", # Zmieniono z 127.0.0.1
228
  server_port=7860,
229
+ share=False,
230
+ debug=False,
231
  show_error=True
232
  )