-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.py
More file actions
264 lines (240 loc) · 8.86 KB
/
extract.py
File metadata and controls
264 lines (240 loc) · 8.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import joblib
# import moviepy.editor as moviepy
import os, sys
from utils import data_utils
data_utils.add_path()
from torch import nn
import pydub
import numpy as np
import pandas as pd
from pydub import AudioSegment
from clf.mfcc_data import mfcc_loader
from kospeech.infer_ import pred_sentence
import subprocess
from tqdm import tqdm
packages = ['clf','kospeech','hanspell','utils']
for package in packages:
sys.path.append(package)
import re
from collections import Counter
try:
import tensorflow # required in Colab to avoid protobuf compatibility issues
except ImportError:
pass
import torch
import whisper
import torchaudio
from tqdm.notebook import tqdm
import requests
import json
import re
from konlpy.tag import Okt
# from clf.mfcc_data import mfcc_loader\
# model_path = os.path.join('clf','model.joblib')
# mfcc_pipe = joblib.load('clf/model.joblib')
class replace_str():
'''
usage
doc ='아부지가 그렇게 갈카주도 와그리 재그람이 없노? 그것도 하나 몬하나?'
test = replace()
test.replace_str(doc)
return (replace_str, replace words list)
'''
def __init__(self):
self.okt = Okt()
self.url = 'https://opendict.korean.go.kr/api/search'
self.params = {
'key':'AE47DFEE516CF24C06F80B9E6A4183DB',
'q':None,
'req_type':'json'
}
def get_words(self, word):
self.params['q'] = word
res = requests.get(self.url, params=self.params, verify=False)
try:
js = json.loads(res.content)['channel']['item']
except:
return -1
# print(js)
outs = []
for w in js:
if w['word']==word:
out = [v['definition'] for v in w['sense']]
out_v = [s for s in out if ('방언' in s)or('사투리' in s)]
if len(out_v) != 0:
out_v = [re.match("‘.+’",s) for s in out]
out_v = [s.string[s.start()+1:s.end()-1] for s in out_v]
else:
out_v = -1
if out_v != -1:
outs.append(*out_v)
return outs
def replace_str(self, sentence):
replaces = sentence
token = self.okt.pos(sentence)
words = [v[0] for v in token if v[1]=='Noun']
words_re = [(word,self.get_words(word)) for word in words]
words_re = [word for word in words_re if len(word[1]) >0]
for word_o, word_r in [list(v) for v in words_re]:
if len(word_r) == 0:
continue
replaces = replaces.replace(word_o,word_r[0])
return replaces, words_re
class feature_extract():
def __init__(self, model_path='model_ds2.pt', use_whisper=True):
self.mfcc_pipe = joblib.load('clf/model.joblib')
self.device = torch.device('cpu')
self.use_whisper = use_whisper
if self.use_whisper:
self.model = whisper.load_model("base")
else:
self.model_path = model_path
self.model = torch.load(model_path, map_location=lambda storage, loc: storage).to(self.device)
if isinstance(self.model, nn.DataParallel):
self.model = self.model.module
self.model.eval()
self.sr = 16000
self.dialectCount = 0
self.intonation = 0.
self.speechRate = 0.
self.word = []
def predict(self, audio_path):
if self.use_whisper:
audio = whisper.load_audio(audio_path)
audio = whisper.pad_or_trim(audio)
# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio).to(self.model.device)
# detect the spoken language
_, probs = self.model.detect_language(mel)
print(f"Detected language: {max(probs, key=probs.get)}")
# decode the audio
options = whisper.DecodingOptions(fp16=False)
result = whisper.decode(self.model, mel, options)
sentence = result.text
else:
sentence = pred_sentence(audio_path, self.model, self.device)[0]
return sentence
# is_dialect = self.mfcc_pipe(audio_path) # {1:True, 0:False}
# time = np.memmap(audio_path, dtype='h', mode='r').astype('float32')/self.sr
# return {'sentence':sentence,
# 'is_dialect':is_dialect,
# 'time':time}
def convert_wave_to_pcm(self, filename):
file = open(filename, 'rb')
byteBuffer = bytearray(file.read())
file.close()
fn_ext = os.path.splitext(filename)
if fn_ext[1] == '.wav':
out_filename = fn_ext[0] + '.pcm'
else:
out_filename = fn_ext[0] + fn_ext[1] + '.pcm'
out_file = open(out_filename, 'wb')
out_file.write(byteBuffer[44:])
out_file.close()
return out_filename
def webm_to_wav(self,webm,wav):
clip = moviepy.VideoFileClip(webm)
clip.audio.write_audiofile(wav)
return wav
def convert_webm_to_wav(self,file):
command = ['ffmpeg', '-i', file, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', file[:-5] + '.wav']
subprocess.run(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
return file[:-5] + '.wav'
def audio(self, path, min_silence_length=150, duration=3500):
'''
input: wav file path
return: filename_start_end.pcm
'''
if path.endswith('.webm'):
path = self.convert_webm_to_wav(path)
dir = os.path.split(path)[0]
file = os.path.split(path)[-1]
print(dir)
print(file)
csv = []
audio = AudioSegment.from_file(file=path,
format='wav')
times = pydub.silence.detect_nonsilent(audio,
min_silence_len=min_silence_length,
silence_thresh=-32.64)
t = []
st = times[0][0]
sums = 0
file_name = file.split('.')[0]
folder = os.path.join(dir, file_name)
os.makedirs(folder, exist_ok=True)
for [start, end] in times:
sums += (end - start)
if sums >= duration:
t.append([st, end])
st = end
sums = 0
if len(t) < 1:
t = [[times[0][0],times[-1][-1]]]
for idx, time in enumerate(t):
dic = {}
os.makedirs(os.path.join(folder,'wav'), exist_ok=True)
file_path = os.path.join(folder,'wav',str(idx)+'.wav')
newAudio = audio[time[0]:time[1]]
newAudio.export(file_path,format='wav')
dic['file_path'] =file_path
dic['start'] = time[0]
dic['end'] = time[1]
csv.append(dic)
self.df = pd.DataFrame(csv)
# self.csv = os.path.join(folder,'train.csv')
# self.df.to_csv(self.csv, index=False)
return self.df
def extract(self, create_path, csv_path=None):
text = []
n_dialect = []
speechRates = []
detail = []
if csv_path ==None:
# csv_path = self.csv
df = self.df
else:
df = pd.read_csv(csv_path)
# save_path = os.path.join(os.path.split(csv_path)[0],'total.csv')
for idx, rows in tqdm(df.iterrows()):
file_path = rows['file_path']
start = rows['start']
end = rows['end']
pcm = self.convert_wave_to_pcm(file_path)
# sentence = self.predict(pcm,self.model,self.device)
sentence = self.predict(file_path)
isDialect = self.mfcc_pipe.predict(pcm)
speechRate = ((end-start)/1000)/ len(sentence[0])
text.append(sentence[0])
n_dialect.append(isDialect[0])
speechRates.append(speechRate)
if isDialect > 0:
dic = {}
dic['dialect_time'] = start
dic['dialect_string'] = sentence
detail.append(dic)
df['text'] = text
df['isDialect'] = n_dialect
df['speechRate'] = speechRates
df.to_csv(create_path,encoding='utf-8-sig',index = None)
texts = (' '.join(df.text.to_list()))
texts = re.sub(' +', ' ', texts).split(' ')
count = Counter(texts)
count = count.most_common()
dialectCount = df.isDialect.sum()
speechRate = df.speechRate.mean()
word = count[:5]
out = {
'detail':detail,
'speed':speechRate,
'words':[w[0] for w in count],
'words_count':[w[1] for w in count]
}
return out
# return {'dialectCount' : dialectCount,
# 'intonation' : self.intonation,
# 'speechRate' : speechRate,
# 'word' : word}
# def get_word_frequency(self,df):
# text =
fe = feature_extract()