Azdeen commited on
Commit
b6c0d96
·
verified ·
1 Parent(s): f806528

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -43
app.py CHANGED
@@ -1,48 +1,167 @@
1
-
2
- import gradio as gr
3
- import pandas as pd
4
- import numpy as np
5
- from df.enhance import enhance, init_df, load_audio, save_audio
6
- import time
7
  import os
8
- import gradio as gr
9
  import re
10
- from gradio.themes.base import Base
11
- from datasets import load_dataset
12
- from datasets import Dataset,DatasetDict
 
13
  import librosa
 
 
 
14
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- model_enhance, df_state, _ = init_df()
17
- def Read_DataSet(link):
18
- dataset = load_dataset(link,token=os.environ.get("auth_acess_data"))
19
- df = dataset["train"].to_pandas()
20
- return df
21
 
22
 
 
 
23
 
24
 
25
- def remove_nn(wav, sample_rate=16000):
26
-
27
- audio=librosa.resample(wav,orig_sr=sample_rate,target_sr=df_state.sr(),)
28
-
29
- audio=torch.tensor([audio])
30
- # audio, _ = load_audio('full_generation.wav', sr=df_state.sr())
31
- print(audio)
32
-
33
- enhanced = enhance(model_enhance, df_state, audio)
34
- print(enhanced)
35
- # save_audio("enhanced.wav", enhanced, df_state.sr())
36
- audiodata=librosa.resample(enhanced[0].numpy(),orig_sr=df_state.sr(),target_sr=sample_rate)
37
-
38
- return 16000, audiodata/np.max(audiodata)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
 
40
 
41
 
42
 
43
  class DataViewerApp:
44
  def __init__(self,df):
45
- #df=Read_DataSet(link)
46
  self.df=df
47
  # self.df1=df
48
  self.data =self.df[['text','speaker_id','secs','flag']]
@@ -93,7 +212,7 @@ class DataViewerApp:
93
  return self.get_page_data(self.current_page),len(v)
94
  def getdataset(self,link):
95
  self.link_dataset=link
96
- df=Read_DataSet(link)
97
  v=self.settt(df)
98
  return self.get_page_data(self.current_page),len(v),self.link_dataset
99
  def remove_hamza_from_alif_and_symbols(self,text):
@@ -111,7 +230,7 @@ class DataViewerApp:
111
  sr,audio=data_oudio
112
  if sr!=16000:
113
  audio=audio.astype(np.float32)
114
- audio/=np.max(np.abs(audio))
115
  audio=librosa.resample(audio,orig_sr=sr,target_sr=16000)
116
 
117
 
@@ -119,9 +238,9 @@ class DataViewerApp:
119
 
120
 
121
  self.sdata[self.current_selected] = audio
122
- self.df['text'][self.current_selected] =text
123
- self.df['audio'][self.current_selected] = audio
124
- self.df['flag'][self.current_selected] =1
125
  return self.get_page_data(self.current_page),None,""
126
  def GetDataset_2(self,filename,ds=1.5):
127
  audios_data = []
@@ -155,10 +274,10 @@ class DataViewerApp:
155
  audios_samplerate = []
156
  sr,audio=data_oudio
157
  audio=audio.astype(np.float32)
158
- audio/=np.max(np.abs(audio))
159
  audio=librosa.resample(audio,orig_sr=sr,target_sr=16000)
160
  audios_data.append(audio)
161
- secs=round(len(audios_data)/16000,2)
162
  audios_samplerate.append(16000)
163
  df = pd.DataFrame()
164
  df['secs'] = secs
@@ -198,7 +317,7 @@ class DataViewerApp:
198
  return self.get_page_data(self.current_page)
199
  def get_text_from_audio(self,audio):
200
  if len(audio)!=0:
201
- sf.write("temp.wav", audio, 16000,format='WAV')
202
 
203
  client = Client("MohamedRashad/Arabic-Whisper-CodeSwitching-Edition")
204
  result = client.predict(
@@ -238,7 +357,7 @@ class DataViewerApp:
238
  row = self.data.iloc[self.current_selected]
239
  row_audio = self.sdata[self.current_selected]
240
  self.speaker_id=row['speaker_id']
241
- return (16000, row_audio), row['text']
242
  def finsh_data(self):
243
  self.df['audio'] = self.sdata
244
  self.df[['text','speaker_id','secs','flag']]=self.data
@@ -269,11 +388,11 @@ class DataViewerApp:
269
  }
270
 
271
  dataset = DatasetDict(ds)
272
- dataset.push_to_hub(namedata,token=os.environ.get("auth_acess_data"),private=True)
273
  return namedata
274
 
275
  def delete_row(self):
276
- if len(self.data)!=0 or self.current_selected != -1 :
277
  self.data.drop(self.current_selected, inplace=True)
278
  self.data.reset_index(drop=True, inplace=True)
279
  self.df.drop(self.current_selected, inplace=True)
@@ -286,7 +405,7 @@ class DataViewerApp:
286
  return self.get_page_data(self.current_page),None,""
287
  def login(self, token):
288
  # Your actual login logic here (e.g., database check)
289
- if token == os.environ.get("token_login") :
290
  return gr.update(visible=False),gr.update(visible=True),True
291
  else:
292
  return gr.update(visible=True), gr.update(visible=False),None
@@ -491,4 +610,4 @@ class DataViewerApp:
491
  dff=pd.DataFrame(columns=['text', 'audio', 'samplerate', 'secs', 'speaker_id', '_speaker_id','flag'])
492
  app=DataViewerApp(dff)
493
  s=app.start_tab1()
494
- s.launch()
 
1
+ from __future__ import annotations
2
+
3
+ import logging
 
 
 
4
  import os
 
5
  import re
6
+ from functools import lru_cache
7
+ from typing import Any
8
+
9
+ import gradio as gr
10
  import librosa
11
+ import numpy as np
12
+ import pandas as pd
13
+ import soundfile as sf
14
  import torch
15
+ from datasets import Dataset, DatasetDict, load_dataset
16
+ from gradio.themes.base import Base
17
+ from gradio_client import Client, handle_file
18
+
19
+ LOGGER = logging.getLogger("audio-dataset-manager")
20
+ logging.basicConfig(
21
+ level=os.getenv("LOG_LEVEL", "INFO"),
22
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
23
+ )
24
+
25
+ TARGET_SAMPLE_RATE = 16_000
26
+ HF_TOKEN_ENV = "auth_acess_data"
27
+ LOGIN_TOKEN_ENV = "token_login"
28
+
29
+
30
+ class DeepFilterNetUnavailable(RuntimeError):
31
+ """Raised when DeepFilterNet is not installed or cannot be initialized."""
32
+
33
+
34
+ @lru_cache(maxsize=1)
35
+ def get_enhancer():
36
+ """
37
+ Load DeepFilterNet lazily.
38
+
39
+ Lazy loading prevents the whole Space from crashing during startup and
40
+ avoids loading the model until enhancement is actually requested.
41
+ """
42
+ try:
43
+ from df.enhance import enhance, init_df
44
+ except ModuleNotFoundError as exc:
45
+ raise DeepFilterNetUnavailable(
46
+ "DeepFilterNet is not installed. Add `deepfilternet==0.5.6` "
47
+ "to requirements.txt, then rebuild the Space."
48
+ ) from exc
49
+
50
+ try:
51
+ model, state, _ = init_df()
52
+ model.eval()
53
+ return enhance, model, state
54
+ except Exception as exc:
55
+ LOGGER.exception("DeepFilterNet initialization failed")
56
+ raise DeepFilterNetUnavailable(
57
+ f"DeepFilterNet could not be initialized: {exc}"
58
+ ) from exc
59
+
60
+
61
+ def _as_mono_float32(audio: Any) -> np.ndarray:
62
+ """Convert supported audio input to finite mono float32 samples."""
63
+ array = np.asarray(audio, dtype=np.float32)
64
+
65
+ if array.ndim == 2:
66
+ # Gradio may return (samples, channels).
67
+ array = array.mean(axis=1)
68
+ elif array.ndim != 1:
69
+ array = array.reshape(-1)
70
+
71
+ array = np.nan_to_num(array, nan=0.0, posinf=0.0, neginf=0.0)
72
+ peak = float(np.max(np.abs(array))) if array.size else 0.0
73
+ if peak > 1.0:
74
+ array = array / peak
75
+ return np.ascontiguousarray(array, dtype=np.float32)
76
+
77
+
78
+ def normalize_audio(audio: Any, eps: float = 1e-8) -> np.ndarray:
79
+ array = _as_mono_float32(audio)
80
+ if array.size == 0:
81
+ return array
82
+
83
+ peak = float(np.max(np.abs(array)))
84
+ return array if peak < eps else array / peak
85
+
86
+
87
+ def read_dataset(link: str) -> pd.DataFrame:
88
+ if not link or not link.strip():
89
+ raise gr.Error("أدخل رابط أو اسم Dataset صحيح.")
90
+
91
+ token = os.getenv(HF_TOKEN_ENV) or None
92
+ try:
93
+ dataset = load_dataset(link.strip(), token=token)
94
+ except Exception as exc:
95
+ LOGGER.exception("Dataset loading failed: %s", link)
96
+ raise gr.Error(f"تعذر تحميل Dataset: {exc}") from exc
97
+
98
+ split = "train" if "train" in dataset else next(iter(dataset.keys()))
99
+ frame = dataset[split].to_pandas()
100
+
101
+ required = {
102
+ "text": "",
103
+ "audio": None,
104
+ "samplerate": TARGET_SAMPLE_RATE,
105
+ "secs": 0.0,
106
+ "speaker_id": -1,
107
+ "_speaker_id": -1,
108
+ "flag": 0,
109
+ }
110
+ for column, default in required.items():
111
+ if column not in frame.columns:
112
+ frame[column] = default
113
 
114
+ return frame
 
 
 
 
115
 
116
 
117
+ # Backward-compatible name used by the original callbacks.
118
+ Read_DataSet = read_dataset
119
 
120
 
121
+ def remove_nn(wav: Any, sample_rate: int = TARGET_SAMPLE_RATE):
122
+ """
123
+ Enhance a waveform with DeepFilterNet and return a Gradio audio tuple.
124
+ """
125
+ if wav is None:
126
+ raise gr.Error("اختر ملفًا صوتيًا أولًا.")
127
+
128
+ audio = normalize_audio(wav)
129
+ if audio.size == 0:
130
+ raise gr.Error("الملف الصوتي فارغ.")
131
+
132
+ enhance_fn, model, state = get_enhancer()
133
+ model_sr = int(state.sr())
134
+
135
+ if sample_rate != model_sr:
136
+ audio = librosa.resample(
137
+ audio,
138
+ orig_sr=int(sample_rate),
139
+ target_sr=model_sr,
140
+ res_type="soxr_hq",
141
+ )
142
+
143
+ tensor = torch.from_numpy(audio).unsqueeze(0)
144
+
145
+ with torch.inference_mode():
146
+ enhanced = enhance_fn(model, state, tensor)
147
+
148
+ enhanced_np = enhanced.squeeze(0).detach().cpu().numpy()
149
+
150
+ if model_sr != TARGET_SAMPLE_RATE:
151
+ enhanced_np = librosa.resample(
152
+ enhanced_np,
153
+ orig_sr=model_sr,
154
+ target_sr=TARGET_SAMPLE_RATE,
155
+ res_type="soxr_hq",
156
+ )
157
 
158
+ return TARGET_SAMPLE_RATE, normalize_audio(enhanced_np)
159
 
160
 
161
 
162
  class DataViewerApp:
163
  def __init__(self,df):
164
+ #df=read_dataset(link)
165
  self.df=df
166
  # self.df1=df
167
  self.data =self.df[['text','speaker_id','secs','flag']]
 
212
  return self.get_page_data(self.current_page),len(v)
213
  def getdataset(self,link):
214
  self.link_dataset=link
215
+ df=read_dataset(link)
216
  v=self.settt(df)
217
  return self.get_page_data(self.current_page),len(v),self.link_dataset
218
  def remove_hamza_from_alif_and_symbols(self,text):
 
230
  sr,audio=data_oudio
231
  if sr!=16000:
232
  audio=audio.astype(np.float32)
233
+ audio=normalize_audio(audio)
234
  audio=librosa.resample(audio,orig_sr=sr,target_sr=16000)
235
 
236
 
 
238
 
239
 
240
  self.sdata[self.current_selected] = audio
241
+ self.df.loc[self.current_selected, 'text'] = text
242
+ self.df.at[self.current_selected, 'audio'] = audio
243
+ self.df.loc[self.current_selected, 'flag'] = 1
244
  return self.get_page_data(self.current_page),None,""
245
  def GetDataset_2(self,filename,ds=1.5):
246
  audios_data = []
 
274
  audios_samplerate = []
275
  sr,audio=data_oudio
276
  audio=audio.astype(np.float32)
277
+ audio=normalize_audio(audio)
278
  audio=librosa.resample(audio,orig_sr=sr,target_sr=16000)
279
  audios_data.append(audio)
280
+ secs=round(len(audio)/TARGET_SAMPLE_RATE, 2)
281
  audios_samplerate.append(16000)
282
  df = pd.DataFrame()
283
  df['secs'] = secs
 
317
  return self.get_page_data(self.current_page)
318
  def get_text_from_audio(self,audio):
319
  if len(audio)!=0:
320
+ sf.write("temp.wav", normalize_audio(audio), TARGET_SAMPLE_RATE, format='WAV')
321
 
322
  client = Client("MohamedRashad/Arabic-Whisper-CodeSwitching-Edition")
323
  result = client.predict(
 
357
  row = self.data.iloc[self.current_selected]
358
  row_audio = self.sdata[self.current_selected]
359
  self.speaker_id=row['speaker_id']
360
+ return (TARGET_SAMPLE_RATE, row_audio), row['text']
361
  def finsh_data(self):
362
  self.df['audio'] = self.sdata
363
  self.df[['text','speaker_id','secs','flag']]=self.data
 
388
  }
389
 
390
  dataset = DatasetDict(ds)
391
+ dataset.push_to_hub(namedata, token=os.environ.get(HF_TOKEN_ENV), private=True)
392
  return namedata
393
 
394
  def delete_row(self):
395
+ if len(self.data) != 0 and self.current_selected != -1:
396
  self.data.drop(self.current_selected, inplace=True)
397
  self.data.reset_index(drop=True, inplace=True)
398
  self.df.drop(self.current_selected, inplace=True)
 
405
  return self.get_page_data(self.current_page),None,""
406
  def login(self, token):
407
  # Your actual login logic here (e.g., database check)
408
+ if token and token == os.environ.get(LOGIN_TOKEN_ENV):
409
  return gr.update(visible=False),gr.update(visible=True),True
410
  else:
411
  return gr.update(visible=True), gr.update(visible=False),None
 
610
  dff=pd.DataFrame(columns=['text', 'audio', 'samplerate', 'secs', 'speaker_id', '_speaker_id','flag'])
611
  app=DataViewerApp(dff)
612
  s=app.start_tab1()
613
+ s.queue(default_concurrency_limit=2).launch(show_error=True)