A-yum1 commited on
Commit
c43f92d
·
verified ·
1 Parent(s): f53414f

Upload transcription.py

Browse files
Files changed (1) hide show
  1. transcription.py +47 -0
transcription.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from faster_whisper import WhisperModel
3
+
4
+ class TranscriptionMaker():
5
+ #書き起こしファイル(ファイル名_transcription.txt)を吐き出すディレクトリを指定
6
+ def __init__(self,output_dir=os.path.abspath("/tmp/data/transcriptions")):
7
+ self.model = WhisperModel("base", device="cpu")
8
+ self.output_dir = output_dir
9
+ try:
10
+ if not os.path.exists(self.output_dir):
11
+ os.makedirs(self.output_dir)
12
+ except OSError as e:
13
+ print(f"Error creating directory {self.output_dir}: {e}")
14
+ raise
15
+
16
+ #音声ファイルのパスを受け取り、書き起こしファイルを作成する
17
+ def create_transcription(self,audio_path):
18
+ try:
19
+ if not os.path.isfile(audio_path):
20
+ raise FileNotFoundError(f"The specified audio file does not exist: {audio_path}")
21
+
22
+ segments, info = self.model.transcribe(audio_path)
23
+ results = []
24
+
25
+ for segment in segments:
26
+ results.append({
27
+ "start": segment.start,
28
+ "end": segment.end,
29
+ "text": segment.text
30
+ })
31
+
32
+ #ファイルの書き込み
33
+ output_file=os.path.join(self.output_dir,os.path.basename(audio_path)+"_transcription.txt")
34
+ try:
35
+ with open(output_file,"w",encoding="utf-8") as f:
36
+ for result in results:
37
+ f.write(f"[{result['start']:.2f}s - {result['end']:.2f}s] {result['text']}\n")
38
+ except OSError as e:
39
+ print(f"Error writing transcription file: {e}")
40
+ raise
41
+ return output_file
42
+ except FileNotFoundError as e:
43
+ print(f"Error: {e}")
44
+ raise
45
+ except Exception as e:
46
+ print(f"An unexpected error occurred: {e}")
47
+ raise