rein0421 commited on
Commit
5acb820
·
verified ·
1 Parent(s): 32e3b4a

Update transcription.py

Browse files
Files changed (1) hide show
  1. transcription.py +97 -92
transcription.py CHANGED
@@ -1,93 +1,98 @@
1
- import os
2
- from faster_whisper import WhisperModel
3
- from pydub import AudioSegment
4
-
5
- class TranscriptionMaker():
6
- #書き起こしファイルを吐き出すディレクトリを指定
7
- def __init__(self,output_dir="/tmp/data/transcriptions"):
8
- self.model = WhisperModel("base", device="cpu")
9
- self.output_dir = output_dir
10
- try:
11
- if not os.path.exists(self.output_dir):
12
- os.makedirs(self.output_dir)
13
- except OSError as e:
14
- print(f"Error creating directory {self.output_dir}: {e}")
15
- raise
16
-
17
- #音声ファイルのディレクトリを受け取り、書き起こしファイルを作成する
18
- def create_transcription(self,segments_directory):
19
- results = []
20
- #細切れ音声をくっつける
21
- audio_directory = self.merge_segments(segments_directory)
22
- #ディレクトリ内のファイルを全て取得
23
- if not os.path.isdir(audio_directory):
24
- raise ValueError(f"The specified path is not a valid directory: {audio_directory}")
25
- audio_files = os.listdir(audio_directory)
26
- for audio_file in audio_files:
27
- if os.path.splitext(audio_file)[-1].lower() != '.wav':
28
- continue
29
- audio_path = os.path.join(audio_directory, audio_file)
30
- try:
31
- segments,info = list(self.model.transcribe(audio_path))
32
- except Exception as e:
33
- print(f"Error transcripting file {audio_path}: {e}")
34
- raise
35
- for segment in segments:
36
- results.append({
37
- "start": segment.start,
38
- "end": segment.end,
39
- "text": segment.text
40
- })
41
- #ファイルの書き込み。ファイル名は"読み込みディレクトリ名_transcription.txt"
42
- output_file=os.path.join(self.output_dir,os.path.basename(audio_directory)+"_transcription.txt")
43
- try:
44
- with open(output_file,"w",encoding="utf-8") as f:
45
- for result in results:
46
- f.write(f"{result['text']}\n")
47
- except OSError as e:
48
- print(f"Error writing transcription file: {e}")
49
- raise
50
- return output_file
51
-
52
- #ファイル名が連続しているならくっつける
53
- def merge_segments(self,segments_dir,output_dir = "/tmp/data/merged_audio"):
54
- if not os.path.exists(output_dir):
55
- os.makedirs(output_dir, exist_ok=True)
56
-
57
- files = sorted([f for f in os.listdir(segments_dir) if f.endswith('.wav')])
58
-
59
- merged_files = []
60
- current_group = []
61
- previous_index = None
62
-
63
- for file in files:
64
- # ファイル名から番号を抽出(例: "0.wav" -> 0)
65
- file_index = int(file.split('.')[0])
66
-
67
- # 番号が連続していない場合、新しいグループを作成
68
- if previous_index is not None and file_index != previous_index + 1:
69
- # 現在のグループを結合して保存
70
- if current_group:
71
- merged_files.append(current_group)
72
- current_group = []
73
-
74
- # 現在のファイルをグループに追加
75
- current_group.append(file)
76
- previous_index = file_index
77
-
78
- # 最後のグループを追加
79
- if current_group:
80
- merged_files.append(current_group)
81
-
82
- # グループごとに結合して保存
83
- for i, group in enumerate(merged_files):
84
- combined_audio = AudioSegment.empty()
85
- for file in group:
86
- file_path = os.path.join(segments_dir, file)
87
- segment = AudioSegment.from_file(file_path)
88
- combined_audio += segment
89
- # 出力ファイル名を設定して保存
90
- output_file = os.path.join(output_dir, f'merged_{i}.wav')
91
- combined_audio.export(output_file, format='wav')
92
-
 
 
 
 
 
93
  return output_dir
 
1
+ import os
2
+ from faster_whisper import WhisperModel
3
+ from pydub import AudioSegment
4
+ # Matplotlibのキャッシュディレクトリを変更
5
+ os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
6
+
7
+ # Hugging Faceのキャッシュディレクトリを変更
8
+ os.environ["HF_HOME"] = "/tmp/huggingface"
9
+
10
+ class TranscriptionMaker():
11
+ #書き起こしファイルを吐き出すディレクトリを指定
12
+ def __init__(self,output_dir="/tmp/data/transcriptions"):
13
+ self.model = WhisperModel("base", device="cpu")
14
+ self.output_dir = output_dir
15
+ try:
16
+ if not os.path.exists(self.output_dir):
17
+ os.makedirs(self.output_dir)
18
+ except OSError as e:
19
+ print(f"Error creating directory {self.output_dir}: {e}")
20
+ raise
21
+
22
+ #音声ファイルのディレクトリを受け取り、書き起こしファイルを作成する
23
+ def create_transcription(self,segments_directory):
24
+ results = []
25
+ #細切れ音声をくっつける
26
+ audio_directory = self.merge_segments(segments_directory)
27
+ #ディレクトリ内のファイルを全て取得
28
+ if not os.path.isdir(audio_directory):
29
+ raise ValueError(f"The specified path is not a valid directory: {audio_directory}")
30
+ audio_files = os.listdir(audio_directory)
31
+ for audio_file in audio_files:
32
+ if os.path.splitext(audio_file)[-1].lower() != '.wav':
33
+ continue
34
+ audio_path = os.path.join(audio_directory, audio_file)
35
+ try:
36
+ segments,info = list(self.model.transcribe(audio_path))
37
+ except Exception as e:
38
+ print(f"Error transcripting file {audio_path}: {e}")
39
+ raise
40
+ for segment in segments:
41
+ results.append({
42
+ "start": segment.start,
43
+ "end": segment.end,
44
+ "text": segment.text
45
+ })
46
+ #ファイルの書き込み。ファイル名は"読み込みディレクトリ名_transcription.txt"
47
+ output_file=os.path.join(self.output_dir,os.path.basename(audio_directory)+"_transcription.txt")
48
+ try:
49
+ with open(output_file,"w",encoding="utf-8") as f:
50
+ for result in results:
51
+ f.write(f"{result['text']}\n")
52
+ except OSError as e:
53
+ print(f"Error writing transcription file: {e}")
54
+ raise
55
+ return output_file
56
+
57
+ #ファイル名が連続しているならくっつける
58
+ def merge_segments(self,segments_dir,output_dir = "/tmp/data/merged_audio"):
59
+ if not os.path.exists(output_dir):
60
+ os.makedirs(output_dir, exist_ok=True)
61
+
62
+ files = sorted([f for f in os.listdir(segments_dir) if f.endswith('.wav')])
63
+
64
+ merged_files = []
65
+ current_group = []
66
+ previous_index = None
67
+
68
+ for file in files:
69
+ # ファイル名から番号を抽出(例: "0.wav" -> 0)
70
+ file_index = int(file.split('.')[0])
71
+
72
+ # 番号が連続していない場合、新しいグループを作成
73
+ if previous_index is not None and file_index != previous_index + 1:
74
+ # 現在のグループを結合して保存
75
+ if current_group:
76
+ merged_files.append(current_group)
77
+ current_group = []
78
+
79
+ # 現在のファイルをグループに追加
80
+ current_group.append(file)
81
+ previous_index = file_index
82
+
83
+ # 最後のグループを追加
84
+ if current_group:
85
+ merged_files.append(current_group)
86
+
87
+ # グループごとに結合して保存
88
+ for i, group in enumerate(merged_files):
89
+ combined_audio = AudioSegment.empty()
90
+ for file in group:
91
+ file_path = os.path.join(segments_dir, file)
92
+ segment = AudioSegment.from_file(file_path)
93
+ combined_audio += segment
94
+ # 出力ファイル名を設定して保存
95
+ output_file = os.path.join(output_dir, f'merged_{i}.wav')
96
+ combined_audio.export(output_file, format='wav')
97
+
98
  return output_dir