RobCaamano commited on
Commit
bb077a1
1 Parent(s): 8b4615f
Files changed (1) hide show
  1. video_to_text.py +99 -86
video_to_text.py CHANGED
@@ -1,86 +1,99 @@
1
- import argparse
2
- from moviepy.editor import VideoFileClip
3
- import whisper
4
- import os
5
- import re
6
-
7
- def extract_audio(video_path, audio_dir='./audio'):
8
- os.makedirs(audio_dir, exist_ok=True)
9
- base_filename = os.path.splitext(os.path.basename(video_path))[0]
10
- audio_filename = os.path.join(audio_dir, base_filename + '.wav')
11
- video_clip = VideoFileClip(video_path)
12
- video_clip.audio.write_audiofile(audio_filename)
13
- video_clip.close()
14
- return audio_filename
15
-
16
- def transcribe_audio(audio_path, model_type='base', transcribed_dir='./transcribed'):
17
- model = whisper.load_model(model_type)
18
- result = model.transcribe(audio_path)
19
-
20
- os.makedirs(transcribed_dir, exist_ok=True)
21
- base_filename = os.path.splitext(os.path.basename(audio_path))[0]
22
- transcribed_filename = os.path.join(transcribed_dir, base_filename + '.txt')
23
-
24
- with open(transcribed_filename, 'w') as file:
25
- for segment in result['segments']:
26
- start = segment['start']
27
- end = segment['end']
28
- text = segment['text']
29
- file.write(f"[{start:.2f}-{end:.2f}] {text}\n")
30
-
31
- return transcribed_filename, result['text']
32
-
33
- def merge_lines(file_path):
34
- timestamp_pattern = re.compile(r'\[(\d+\.\d+)-(\d+\.\d+)\]')
35
-
36
- with open(file_path, 'r') as file:
37
- lines = file.readlines()
38
-
39
- merged_lines = []
40
- i = 0
41
-
42
- while i < len(lines):
43
- line = lines[i].strip()
44
- match = timestamp_pattern.match(line)
45
-
46
- if match:
47
- start_time = float(match.group(1))
48
- text = line[match.end():].strip()
49
-
50
- if not (text.endswith('.') or text.endswith('?')):
51
- if i + 1 < len(lines):
52
- next_line = lines[i + 1].strip()
53
- next_match = timestamp_pattern.match(next_line)
54
-
55
- if next_match:
56
- end_time = float(next_match.group(2))
57
- next_text = next_line[next_match.end():].strip()
58
- merged_text = text + ' ' + next_text
59
- merged_line = f"[{start_time:.2f}-{end_time:.2f}] {merged_text}\n"
60
- merged_lines.append(merged_line)
61
- i += 1
62
- else:
63
- end_time = float(match.group(2))
64
- merged_lines.append(f"[{start_time:.2f}-{end_time:.2f}] {text}\n")
65
-
66
- i += 1
67
-
68
- with open(file_path, 'w') as file:
69
- file.writelines(merged_lines)
70
-
71
- return file_path
72
-
73
- def convert_video_to_text(video_file_path, model_type='base'):
74
- audio_path = extract_audio(video_file_path)
75
- transcribed_path, _ = transcribe_audio(audio_path, model_type)
76
- merge_lines(transcribed_path)
77
- return transcribed_path
78
-
79
-
80
- if __name__ == "__main__":
81
- parser = argparse.ArgumentParser(description="Transcribe audio from video")
82
- parser.add_argument("video_file", help="Path to the video file")
83
- parser.add_argument("--model", help="Size of the whisper model (e.g., tiny, base, small, medium, large, huge).", default="base")
84
- args = parser.parse_args()
85
-
86
- convert_video_to_text(args.video_file, args.model)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from moviepy.editor import VideoFileClip
3
+ import whisper
4
+ import os
5
+ import re
6
+
7
+ # Extracts audio from video
8
+ def extract_audio(video_path, audio_dir='./audio'):
9
+ os.makedirs(audio_dir, exist_ok=True)
10
+ base_filename = os.path.splitext(os.path.basename(video_path))[0]
11
+ audio_filename = os.path.join(audio_dir, base_filename + '.wav')
12
+ video_clip = VideoFileClip(video_path)
13
+ video_clip.audio.write_audiofile(audio_filename)
14
+ video_clip.close()
15
+ return audio_filename
16
+
17
+ # Transcribe audio .wav file
18
+ def transcribe_audio(audio_path, model_type='base', transcribed_dir='./transcribed'):
19
+ model = whisper.load_model(model_type)
20
+ result = model.transcribe(audio_path)
21
+
22
+ os.makedirs(transcribed_dir, exist_ok=True)
23
+ base_filename = os.path.splitext(os.path.basename(audio_path))[0]
24
+ transcribed_filename = os.path.join(transcribed_dir, base_filename + '.txt')
25
+
26
+ with open(transcribed_filename, 'w') as file:
27
+ for segment in result['segments']:
28
+ start = segment['start']
29
+ end = segment['end']
30
+ text = segment['text']
31
+ file.write(f"[{start:.2f}-{end:.2f}] {text}\n")
32
+
33
+ return transcribed_filename, result['text']
34
+
35
+ # Merge lines in file that are part of the same sentence
36
+ def merge_lines(file_path):
37
+ timestamp_pattern = re.compile(r'\[(\d+\.\d+)-(\d+\.\d+)\]')
38
+
39
+ with open(file_path, 'r') as file:
40
+ lines = file.readlines()
41
+
42
+ merged_lines = []
43
+ i = 0
44
+
45
+ while i < len(lines):
46
+ line = lines[i].strip()
47
+ match = timestamp_pattern.match(line)
48
+
49
+ if match:
50
+ start_time = float(match.group(1))
51
+ text = line[match.end():].strip()
52
+
53
+ # Check if line doesnt end
54
+ if not (text.endswith('.') or text.endswith('?')):
55
+ # Merge with the next line
56
+ if i + 1 < len(lines):
57
+ next_line = lines[i + 1].strip()
58
+ next_match = timestamp_pattern.match(next_line)
59
+
60
+ if next_match:
61
+ end_time = float(next_match.group(2))
62
+ next_text = next_line[next_match.end():].strip()
63
+ merged_text = text + ' ' + next_text
64
+ merged_line = f"[{start_time:.2f}-{end_time:.2f}] {merged_text}\n"
65
+ merged_lines.append(merged_line)
66
+ i += 1
67
+ else:
68
+ end_time = float(match.group(2))
69
+ merged_lines.append(f"[{start_time:.2f}-{end_time:.2f}] {text}\n")
70
+
71
+ i += 1
72
+
73
+ # Overwrite original file with merged lines
74
+ with open(file_path, 'w') as file:
75
+ file.writelines(merged_lines)
76
+
77
+ return file_path
78
+
79
+ # Driver function
80
+ def convert_video_to_text(video_file_path, model_type='base'):
81
+ # Extract audio
82
+ audio_path = extract_audio(video_file_path)
83
+
84
+ # Transcribe audio
85
+ transcribed_path, _ = transcribe_audio(audio_path, model_type)
86
+
87
+ # Merge lines
88
+ merge_lines(transcribed_path)
89
+
90
+ return transcribed_path
91
+
92
+
93
+ if __name__ == "__main__":
94
+ parser = argparse.ArgumentParser(description="Transcribe audio from video")
95
+ parser.add_argument("video_file", help="Path to the video file")
96
+ parser.add_argument("--model", help="Size of the whisper model (e.g., tiny, base, small, medium, large, huge).", default="base")
97
+ args = parser.parse_args()
98
+
99
+ convert_video_to_text(args.video_file, args.model)