mounseflit commited on
Commit
f6278d8
·
verified ·
1 Parent(s): 7f83b5a

Upload 6 files

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. LICENSE +201 -0
  3. README.md +34 -0
  4. app.py +343 -0
  5. pip +0 -0
  6. requirements.txt +8 -0
  7. screenshot.png +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ screenshot.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YouTube Video Transcriber
2
+
3
+ A Streamlit app that transcribes YouTube videos using Whisper, with optional formatting using a large language model, audio download, and video download.
4
+
5
+ ## How it works
6
+
7
+ - Downloads audio from YouTube videos using `yt-dlp`.
8
+ - Splits audio into speech segments using Silero VAD.
9
+ - Transcribes segments in batches using OpenAI's Whisper model.
10
+ - Formats the transcription using a large language model (if selected).
11
+ - Displays transcribed text with timestamps.
12
+ - Provides options to download the raw transcription, formatted transcription, audio, or video.
13
+
14
+ ## Requirements
15
+
16
+ Listed in `requirements.txt`
17
+
18
+ ## Usage
19
+
20
+ 1. Install dependencies: `pip install -r requirements.txt`
21
+ 2. Run the app: `streamlit run app.py`
22
+ 3. Enter a YouTube video URL.
23
+ 4. Choose options: Transcribe, Download Audio, Download Video, Format Text.
24
+ 5. Select a language or use auto-detect (under "Advanced Settings").
25
+ 6. Click "Process".
26
+
27
+ ## Screenshot
28
+
29
+ ![Screenshot](screenshot.png)
30
+
31
+ ## License
32
+
33
+ MIT
34
+ "# YouTube-Transcriber"
app.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import gradio as gr
3
+ import io
4
+ import os
5
+
6
+ from transformers import pipeline
7
+ import torch
8
+ import yt_dlp
9
+ from silero_vad import load_silero_vad, get_speech_timestamps
10
+ import numpy as np
11
+ import pydub
12
+ from litellm import completion
13
+
14
+ # --- Language List ---
15
+ LANGUAGES = ['english', 'chinese', 'german', 'spanish', 'russian', 'korean', 'french', 'japanese', 'portuguese', 'turkish', 'polish', 'catalan', 'dutch', 'arabic', 'swedish', 'italian', 'indonesian', 'hindi', 'finnish', 'vietnamese', 'hebrew', 'ukrainian', 'greek', 'malay', 'czech', 'romanian', 'danish', 'hungarian', 'tamil', 'norwegian', 'thai', 'urdu', 'croatian', 'bulgarian', 'lithuanian', 'latin', 'maori', 'malayalam', 'welsh', 'slovak', 'telugu', 'persian', 'latvian', 'bengali', 'serbian', 'azerbaijani', 'slovenian', 'kannada', 'estonian', 'macedonian', 'breton', 'basque', 'icelandic', 'armenian', 'nepali', 'mongolian', 'bosnian', 'kazakh', 'albanian', 'swahili', 'galician', 'marathi', 'punjabi', 'sinhala', 'khmer', 'shona', 'yoruba', 'somali', 'afrikaans', 'occitan', 'georgian', 'belarusian', 'tajik', 'sindhi', 'gujarati', 'amharic', 'yiddish', 'lao', 'uzbek', 'faroese', 'haitian creole', 'pashto', 'turkmen', 'nynorsk', 'maltese', 'sanskrit', 'luxembourgish', 'myanmar', 'tibetan', 'tagalog', 'malagasy', 'assamese', 'tatar', 'hawaiian', 'lingala', 'hausa', 'bashkir', 'javanese', 'sundanese', 'cantonese', 'burmese', 'valencian', 'flemish', 'haitian', 'letzeburgesch', 'pushto', 'panjabi', 'moldavian', 'moldovan', 'sinhalese', 'castilian', 'mandarin']
16
+
17
+ # --- Model Loading and Caching ---
18
+ def load_transcriber(_device):
19
+ """Loads the Whisper transcription model."""
20
+ transcriber = pipeline(model="openai/whisper-large-v3-turbo", device=_device)
21
+ return transcriber
22
+
23
+ def load_vad_model():
24
+ """Loads the Silero VAD model."""
25
+ return load_silero_vad()
26
+
27
+ # --- Audio Processing Functions ---
28
+ def download_and_convert_audio(video_url, audio_format="wav"):
29
+ """Downloads and converts audio from a YouTube video.
30
+
31
+ Args:
32
+ video_url (str): The URL of the YouTube video.
33
+ audio_format (str): The desired audio format (e.g., "wav", "mp3").
34
+
35
+ Returns:
36
+ tuple: (audio_bytes, audio_format, info_dict) or (None, None, None) on error.
37
+ """
38
+ try:
39
+ ydl_opts = {
40
+ 'format': f'bestaudio/best',
41
+ 'postprocessors': [{
42
+ 'key': 'FFmpegExtractAudio',
43
+ 'preferredcodec': audio_format,
44
+ }],
45
+ 'outtmpl': '%(id)s.%(ext)s',
46
+ 'noplaylist': True,
47
+ }
48
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
49
+ info = ydl.extract_info(video_url, download=False)
50
+ if 'entries' in info:
51
+ info = info['entries'][0]
52
+ video_id = info['id']
53
+ filename = f"{video_id}.{audio_format}"
54
+
55
+ audio_formats = [f for f in info.get('formats', []) if f.get('acodec') != 'none' and f.get('vcodec') == 'none']
56
+ if not audio_formats:
57
+ print(f"No audio-only format found. Downloading and converting from best video format to {audio_format}.")
58
+ ydl_opts['format'] = 'best'
59
+
60
+ ydl.download([video_url])
61
+ print(f"Audio downloaded and converted to {audio_format}.")
62
+
63
+ with open(filename, 'rb') as audio_file:
64
+ audio_bytes = audio_file.read()
65
+
66
+ os.remove(filename)
67
+ return audio_bytes, audio_format, info
68
+ except Exception as e:
69
+ print(f"Error during download or conversion: {e}")
70
+ return None, None, None
71
+
72
+ def split_audio_by_vad(audio_data: bytes, ext: str, _vad_model, sensitivity: float, max_duration: int = 30, return_seconds: bool = True):
73
+ """Splits audio into chunks based on voice activity detection (VAD).
74
+
75
+ Args:
76
+ audio_data (bytes): The audio data as bytes.
77
+ ext (str): The audio file extension.
78
+ _vad_model: The VAD model.
79
+ sensitivity (float): The VAD sensitivity (0.0 to 1.0).
80
+ max_duration (int): The maximum duration of each chunk in seconds.
81
+ return_seconds (bool): Whether to return timestamps in seconds.
82
+
83
+ Returns:
84
+ list: A list of dictionaries, where each dictionary represents an audio chunk.
85
+ Returns an empty list if no speech segments are detected or an error occurs.
86
+ """
87
+
88
+ if not audio_data:
89
+ print("No audio data received.")
90
+ return []
91
+
92
+ try:
93
+ audio = pydub.AudioSegment.from_file(io.BytesIO(audio_data), format=ext)
94
+ rate = audio.frame_rate
95
+
96
+ # Convert to mono if stereo for compatibility with VAD
97
+ if audio.channels > 1:
98
+ audio = audio.set_channels(1)
99
+
100
+ # Calculate dynamic VAD parameters based on sensitivity
101
+ window_size_samples = int(512 + (1536 - 512) * (1 - sensitivity))
102
+ speech_threshold = 0.5 + (0.95 - 0.5) * sensitivity
103
+
104
+ samples = np.array(audio.get_array_of_samples())
105
+
106
+ speech_timestamps = get_speech_timestamps(
107
+ samples,
108
+ _vad_model,
109
+ sampling_rate=rate,
110
+ return_seconds=return_seconds,
111
+ window_size_samples=window_size_samples,
112
+ threshold=speech_threshold,
113
+ )
114
+
115
+ if not speech_timestamps:
116
+ print("No speech segments detected.")
117
+ return []
118
+
119
+ speech_timestamps[0]["start"] = 0.
120
+ speech_timestamps[-1]['end'] = audio.duration_seconds
121
+ for i, chunk in enumerate(speech_timestamps[1:], start=1):
122
+ chunk["start"] = speech_timestamps[i - 1]['end']
123
+
124
+ aggregated_segments = []
125
+ if speech_timestamps:
126
+ current_segment_start = speech_timestamps[0]['start']
127
+ current_segment_end = speech_timestamps[0]['end']
128
+ for segment in speech_timestamps[1:]:
129
+ if segment['start'] - current_segment_start >= max_duration:
130
+ aggregated_segments.append({'start': current_segment_start, 'end': current_segment_end})
131
+ current_segment_start = segment['start']
132
+ current_segment_end = segment['end']
133
+ else:
134
+ current_segment_end = segment['end']
135
+ aggregated_segments.append({'start': current_segment_start, 'end': current_segment_end})
136
+
137
+ if not aggregated_segments:
138
+ return []
139
+
140
+ chunks = []
141
+ for segment in aggregated_segments:
142
+ start_ms = int(segment['start'] * 1000)
143
+ end_ms = int(segment['end'] * 1000)
144
+ chunk = audio[start_ms:end_ms]
145
+ chunk_io = io.BytesIO()
146
+ chunk.export(chunk_io, format=ext)
147
+ chunks.append({
148
+ 'data': chunk_io.getvalue(),
149
+ 'start': segment['start'],
150
+ 'end': segment['end']
151
+ })
152
+ chunk_io.close()
153
+ return chunks
154
+ except Exception as e:
155
+ print(f"Error processing audio in split_audio_by_vad: {str(e)}")
156
+ return []
157
+ finally:
158
+ if 'audio' in locals():
159
+ del audio
160
+ if 'samples' in locals():
161
+ del samples
162
+
163
+ def transcribe_batch(batch, _transcriber, language=None):
164
+ """Transcribes a batch of audio chunks.
165
+
166
+ Args:
167
+ batch (list): A list of audio chunk dictionaries.
168
+ _transcriber: The transcription model.
169
+ language (str, optional): The language of the audio (e.g., "en", "es"). Defaults to None (auto-detection).
170
+
171
+ Returns:
172
+ list: A list of dictionaries, each containing the transcription, start, and end time of a chunk.
173
+ Returns an empty list if an error occurs.
174
+ """
175
+ transcriptions = []
176
+ for i, chunk_data in enumerate(batch):
177
+ try:
178
+ generate_kwargs = {
179
+ "task": "transcribe",
180
+ "return_timestamps": True,
181
+ "language": language
182
+ }
183
+
184
+ transcription = _transcriber(
185
+ chunk_data['data'],
186
+ generate_kwargs=generate_kwargs
187
+ )
188
+ transcriptions.append({
189
+ 'text': transcription["text"],
190
+ 'start': chunk_data['start'],
191
+ 'end': chunk_data['end']}
192
+ )
193
+ except Exception as e:
194
+ print(f"Error transcribing chunk {i}: {str(e)}")
195
+ return []
196
+ return transcriptions
197
+
198
+ def format_seconds(seconds):
199
+ """Formats seconds into HH:MM:SS string."""
200
+ minutes, seconds = divmod(seconds, 60)
201
+ hours, minutes = divmod(minutes, 60)
202
+ return f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
203
+
204
+ def download_video(video_url, video_format):
205
+ """Downloads video from YouTube using yt-dlp."""
206
+ try:
207
+ ydl_opts = {
208
+ 'format': f'bestvideo[ext={video_format}]+bestaudio[ext=m4a]/best[ext={video_format}]/best',
209
+ 'outtmpl': '%(title)s.%(ext)s',
210
+ 'noplaylist': True,
211
+ }
212
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
213
+ info_dict = ydl.extract_info(video_url, download=True)
214
+ video_filename = ydl.prepare_filename(info_dict)
215
+ video_title = info_dict.get("title", "video")
216
+ print(f"Video downloaded: {video_title}")
217
+
218
+ with open(video_filename, 'rb') as video_file:
219
+ video_bytes = video_file.read()
220
+
221
+ os.remove(video_filename)
222
+
223
+ return video_bytes, video_filename, info_dict
224
+ except Exception as e:
225
+ print(f"Error during video download: {e}")
226
+ return None, None, None
227
+
228
+ def format_transcript(input_transcription):
229
+ """Formats the transcription using the Gemini large language model."""
230
+
231
+ os.environ["GEMINI_API_KEY"] = "AIzaSyBWmOE2XMVpiHuUI4YzgOVzUoENfDeXe8s"
232
+
233
+ sys_prompt = """
234
+ * Format the provided video transcription as a polished piece of written text.
235
+ * **The output must be in the same language as the input; do not translate it.**
236
+ * Focus on clarity, readability, and consistency, adhering to the conventions of that specific language.
237
+ * Restructure sentences for improved flow and correct grammatical errors.
238
+ * **Edits should strictly enhance readability without altering the original meaning or nuances of the raw transcription.**
239
+ * Italicize or quote any text that is read aloud, clearly distinguishing it from the surrounding explanations.
240
+ * Eliminate unnecessary repetitions unless they are used for emphasis.
241
+ * **Do not add any information not present in the original transcript.**
242
+ * **Do not remove timestamps.**
243
+ * **Output only the formatted transcription.**
244
+ """.strip()
245
+ messages = [{"content": sys_prompt, "role": "system"},
246
+ {"content": f"Format the following video transcription: {input_transcription}", "role": "user"}]
247
+
248
+ response = completion(model="gemini/gemini-2.0-flash-exp", messages=messages)
249
+ formatted_text = response.choices[0].message.content
250
+ return formatted_text
251
+
252
+ def process_transcription(video_url, vad_sensitivity, batch_size, transcriber, vad_model, audio_format, language=None):
253
+ """Downloads, processes, and transcribes the audio from a YouTube video.
254
+
255
+ Args:
256
+ video_url (str): The URL of the YouTube video.
257
+ vad_sensitivity (float): The VAD sensitivity.
258
+ batch_size (int): The batch size for transcription.
259
+ transcriber: The transcription model.
260
+ vad_model: The VAD model.
261
+ language (str, optional): The language of the audio. Defaults to None.
262
+
263
+ Returns:
264
+ tuple: (full_transcription, audio_data, audio_format, info) or (None, None, None, None) on error.
265
+ """
266
+ audio_data, audio_format, info = download_and_convert_audio(video_url, audio_format)
267
+ if not audio_data:
268
+ return None, None, None, None
269
+
270
+ chunks = split_audio_by_vad(audio_data, audio_format, vad_model, vad_sensitivity)
271
+ if not chunks:
272
+ return None, None, None, None
273
+
274
+ total_chunks = len(chunks)
275
+ transcriptions = []
276
+ for i in range(0, total_chunks, batch_size):
277
+ batch = chunks[i:i + batch_size]
278
+ batch_transcriptions = transcribe_batch(batch, transcriber, language)
279
+ transcriptions.extend(batch_transcriptions)
280
+
281
+ full_transcription = ""
282
+ for chunk in transcriptions:
283
+ start_time = format_seconds(chunk['start'])
284
+ end_time = format_seconds(chunk['end'])
285
+ full_transcription += f"[{start_time} - {end_time}]: {chunk['text'].strip()}\n\n"
286
+
287
+ return full_transcription, audio_data, audio_format, info
288
+
289
+ def main(video_url, language, batch_size, transcribe_option, download_audio_option, download_video_option, vad_sensitivity, audio_format, video_format, format_option):
290
+ device = "cuda" if torch.cuda.is_available() else "cpu"
291
+ transcriber = load_transcriber(device)
292
+ vad_model = load_vad_model()
293
+
294
+ selected_language = language.lower() if language != "Auto-Detect" else None
295
+
296
+ full_transcription = None
297
+ formatted_transcription = None
298
+ audio_data = None
299
+ info = None
300
+ video_data = None
301
+ video_filename = None
302
+
303
+ if transcribe_option:
304
+ full_transcription, audio_data, audio_format, info = process_transcription(video_url, vad_sensitivity, batch_size, transcriber, vad_model, audio_format, selected_language)
305
+ if full_transcription and format_option:
306
+ formatted_transcription = format_transcript(full_transcription)
307
+
308
+ if download_audio_option:
309
+ if audio_data is None or audio_format is None:
310
+ audio_data, audio_format, info = download_and_convert_audio(video_url, audio_format)
311
+
312
+ if download_video_option:
313
+ video_data, video_filename, info = download_video(video_url, video_format)
314
+
315
+ return full_transcription, formatted_transcription, audio_data, audio_format, video_data, video_filename
316
+
317
+ iface = gr.Interface(
318
+ fn=main,
319
+ inputs=[
320
+ gr.Textbox(label="YouTube Video Link"),
321
+ gr.Dropdown(["Auto-Detect"] + LANGUAGES, label="Language", default="Auto-Detect"),
322
+ gr.Number(label="Batch Size", value=2, precision=0),
323
+ gr.Checkbox(label="Transcribe", value=True),
324
+ gr.Checkbox(label="Download Audio", value=False),
325
+ gr.Checkbox(label="Download Video", value=False),
326
+ gr.Slider(label="VAD Sensitivity", minimum=0.0, maximum=1.0, value=0.1, step=0.05),
327
+ gr.Dropdown(["wav", "mp3", "ogg", "flac"], label="Audio Format", default="wav"),
328
+ gr.Dropdown(["mp4", "webm"], label="Video Format", default="mp4"),
329
+ gr.Checkbox(label="Format Text", value=True)
330
+ ],
331
+ outputs=[
332
+ gr.Textbox(label="Transcription"),
333
+ gr.Textbox(label="Formatted Transcription"),
334
+ gr.File(label="Audio File"),
335
+ gr.Textbox(label="Audio Format"),
336
+ gr.File(label="Video File"),
337
+ gr.Textbox(label="Video Filename")
338
+ ],
339
+ title="YouTube Video Transcriber",
340
+ description="This app allows you to transcribe YouTube videos and format the transcription using a large language model. You can also download the audio and video."
341
+ )
342
+
343
+ iface.launch()
pip ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pydub
3
+ silero_vad
4
+ gradio
5
+ torch
6
+ transformers
7
+ yt_dlp
8
+ litellm
screenshot.png ADDED

Git LFS Details

  • SHA256: 7f13ab61c807c43fd88c62c715dbed8f937a5d94e8cd9a6126f1053b1daff433
  • Pointer size: 131 Bytes
  • Size of remote file: 162 kB