Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,249 +1,21 @@
|
|
1 |
-
from
|
2 |
-
from pytubefix.cli import on_progress
|
3 |
-
import time
|
4 |
import math
|
5 |
import gradio as gr
|
6 |
-
import
|
7 |
-
from faster_whisper import WhisperModel
|
8 |
import requests
|
9 |
-
import json
|
10 |
-
import arabic_reshaper # pip install arabic-reshaper
|
11 |
-
from bidi.algorithm import get_display # pip install python-bidi
|
12 |
-
from moviepy import VideoFileClip, TextClip, CompositeVideoClip, AudioFileClip, ImageClip
|
13 |
-
import pysrt
|
14 |
-
import instaloader
|
15 |
-
import time
|
16 |
-
import concurrent.futures
|
17 |
-
import re
|
18 |
-
from io import BytesIO
|
19 |
-
from PIL import Image
|
20 |
-
api_key = "268976:66f4f58a2a905"
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
def fetch_data(url):
|
26 |
-
try:
|
27 |
-
response = requests.get(url)
|
28 |
-
response.raise_for_status()
|
29 |
-
return response.json()
|
30 |
-
except requests.exceptions.RequestException as e:
|
31 |
-
print(f"An error occurred: {e}")
|
32 |
-
return None
|
33 |
-
|
34 |
-
def download_file(url):
|
35 |
-
try:
|
36 |
-
response = requests.get(url.split("#")[0], stream=True)
|
37 |
-
response.raise_for_status()
|
38 |
-
print(url.split("#")[1])
|
39 |
-
with open(url.split("#")[1], 'wb') as file:
|
40 |
-
for chunk in response.iter_content(chunk_size=8192):
|
41 |
-
if chunk:
|
42 |
-
file.write(chunk)
|
43 |
-
file.close()
|
44 |
-
print(f"Downloaded successfully: {url.split('#')[1]}")
|
45 |
-
except requests.exceptions.RequestException as e:
|
46 |
-
print(f"An error occurred: {e}")
|
47 |
-
|
48 |
-
def download_chunk(url, start, end, filename, index):
|
49 |
-
headers = {'Range': f'bytes={start}-{end}'}
|
50 |
-
response = requests.get(url, headers=headers, stream=True)
|
51 |
-
response.raise_for_status()
|
52 |
-
chunk_filename = f'{filename}.part{index}'
|
53 |
-
with open(chunk_filename, 'wb') as file:
|
54 |
-
for chunk in response.iter_content(chunk_size=8192):
|
55 |
-
if chunk:
|
56 |
-
file.write(chunk)
|
57 |
-
file.close()
|
58 |
-
return chunk_filename
|
59 |
-
|
60 |
-
def merge_files(filename, num_parts):
|
61 |
-
with open(filename, 'wb') as output_file:
|
62 |
-
for i in range(num_parts):
|
63 |
-
part_filename = f'{filename}.part{i}'
|
64 |
-
with open(part_filename, 'rb') as part_file:
|
65 |
-
output_file.write(part_file.read())
|
66 |
-
# Optionally, delete the part file after merging
|
67 |
-
# os.remove(part_filename)
|
68 |
-
part_file.close()
|
69 |
-
|
70 |
-
def download_file_in_parallel(link, size, num_threads=4):
|
71 |
-
url = link.split("#")[0]
|
72 |
-
filename = link.split("#")[1]
|
73 |
-
print(url+" filename: "+filename)
|
74 |
-
response = requests.head(url)
|
75 |
-
#file_size = int(response.headers['Content-Length'])
|
76 |
-
chunk_size = size // num_threads
|
77 |
-
|
78 |
-
ranges = [(i * chunk_size, (i + 1) * chunk_size - 1) for i in range(num_threads)]
|
79 |
-
ranges[-1] = (ranges[-1][0], size - 1) # Adjust the last range to the end of the file
|
80 |
-
|
81 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
|
82 |
-
futures = [
|
83 |
-
executor.submit(download_chunk, url, start, end, filename, i)
|
84 |
-
for i, (start, end) in enumerate(ranges)
|
85 |
-
]
|
86 |
-
for future in concurrent.futures.as_completed(futures):
|
87 |
-
future.result() # Ensure all threads complete
|
88 |
-
|
89 |
-
merge_files(filename, num_threads)
|
90 |
-
print(f'Downloaded successfully: {filename}')
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
def one_youtube(link, api_key):
|
95 |
-
|
96 |
-
# Fetch video ID
|
97 |
-
video_id_url = f"https://one-api.ir/youtube/?token={api_key}&action=getvideoid&link={link}"
|
98 |
-
video_data = fetch_data(video_id_url)
|
99 |
-
if not video_data:
|
100 |
-
return None, None
|
101 |
-
|
102 |
-
video_id = video_data["result"]
|
103 |
-
|
104 |
-
# Fetch video data
|
105 |
-
filter_option = "" # Replace with your filter option
|
106 |
-
video_data_url = f"https://youtube.one-api.ir/?token={api_key}&action=fullvideo&id={video_id}&filter={filter_option}"
|
107 |
-
video_data_2 = fetch_data(video_data_url)
|
108 |
-
if not video_data_2:
|
109 |
-
return None, None
|
110 |
-
|
111 |
-
formats_list = video_data_2["result"]["formats"]
|
112 |
-
file_name = video_data_2["result"]["title"]
|
113 |
-
video_name = f'{file_name}.mp4'
|
114 |
-
audio_name = f'{file_name}.mp3'
|
115 |
-
|
116 |
-
for f in formats_list:
|
117 |
-
if f["format_note"] == "360p":
|
118 |
-
download_id = f["id"]
|
119 |
-
video_size = f["filesize"]
|
120 |
-
for f in formats_list:
|
121 |
-
if f["format_note"] == "medium":
|
122 |
-
audio_id = f["id"]
|
123 |
-
audio_size = f["filesize"]
|
124 |
-
|
125 |
-
if not download_id or not audio_id:
|
126 |
-
return None, None
|
127 |
-
|
128 |
-
# Fetch video and audio links
|
129 |
-
video_link_url = f"https://youtube.one-api.ir/?token={api_key}&action=download&id={download_id}"
|
130 |
-
audio_link_url = f"https://youtube.one-api.ir/?token={api_key}&action=download&id={audio_id}"
|
131 |
-
video_link_data = fetch_data(video_link_url)
|
132 |
-
audio_link_data = fetch_data(audio_link_url)
|
133 |
-
if not video_link_data or not audio_link_data:
|
134 |
-
return None, None
|
135 |
-
|
136 |
-
video_link = video_link_data["result"]["link"]
|
137 |
-
audio_link = audio_link_data["result"]["link"]
|
138 |
-
vid_str=video_link+"#"+video_name
|
139 |
-
audio_str=audio_link+"#"+audio_name
|
140 |
-
# Download video and audio files
|
141 |
-
print(video_size , audio_size)
|
142 |
-
download_file_in_parallel(vid_str, video_size)
|
143 |
-
download_file_in_parallel(audio_str, audio_size)
|
144 |
-
|
145 |
-
return video_name, audio_name
|
146 |
-
|
147 |
-
|
148 |
-
# Define your functions here
|
149 |
-
def yt_download(url):
|
150 |
-
yt = YouTube(url)
|
151 |
-
print(yt.title)
|
152 |
-
video_path = f"{yt.title}.mp4"
|
153 |
-
ys = yt.streams.get_highest_resolution()
|
154 |
-
print(ys)
|
155 |
-
ys.download()
|
156 |
-
return video_path, yt.title
|
157 |
-
|
158 |
-
def download_image(url, save_path='downloaded_image.jpg'):
|
159 |
-
response = requests.get(url)
|
160 |
-
image = Image.open(BytesIO(response.content))
|
161 |
-
image.save(save_path)
|
162 |
-
return save_path
|
163 |
-
|
164 |
-
def insta_oneapi(url, api_key):
|
165 |
-
shortcode = url.split("/")[-2]
|
166 |
-
print(shortcode)
|
167 |
-
url_one="https://api.one-api.ir/instagram/v1/post/?shortcode="+shortcode
|
168 |
-
request_body = [{"shortcode": shortcode},]
|
169 |
-
headers = {"one-api-token": api_key, "Content-Type": "application/json"}
|
170 |
-
response = requests.get(url_one, headers=headers)
|
171 |
-
print(response)
|
172 |
-
if response.status_code == 200:
|
173 |
-
|
174 |
-
result = response.json()
|
175 |
-
try:
|
176 |
-
time.sleep(10)
|
177 |
-
response = requests.get(result["result"]['media'][0]["url"], stream=True)
|
178 |
-
response.raise_for_status()
|
179 |
-
with open("video.mp4", 'wb') as file:
|
180 |
-
for chunk in response.iter_content(chunk_size=8192):
|
181 |
-
if chunk:
|
182 |
-
file.write(chunk)
|
183 |
-
file.close()
|
184 |
-
print(f"Downloaded successfully")
|
185 |
-
image_url = result["result"]['media'][0]["cover"]
|
186 |
-
image_file_path = download_image(image_url)
|
187 |
-
return "video.mp4", image_file_path
|
188 |
-
except requests.exceptions.RequestException as e:
|
189 |
-
print(f"An error occurred: {e}")
|
190 |
-
else:
|
191 |
-
print(f"Error: {response.status_code}, {response.text}")
|
192 |
-
return None
|
193 |
-
|
194 |
|
195 |
-
def insta_download(permalink):
|
196 |
-
# Create an instance of Instaloader
|
197 |
-
L = instaloader.Instaloader()
|
198 |
|
199 |
-
try:
|
200 |
-
# Extract the shortcode from the permalink
|
201 |
-
if "instagram.com/reel/" in permalink:
|
202 |
-
shortcode = permalink.split("instagram.com/reel/")[-1].split("/")[0]
|
203 |
-
elif "instagram.com/p/" in permalink:
|
204 |
-
shortcode = permalink.split("instagram.com/p/")[-1].split("/")[0]
|
205 |
-
else:
|
206 |
-
raise ValueError("Invalid permalink format")
|
207 |
-
|
208 |
-
# Load the post using the shortcode
|
209 |
-
post = instaloader.Post.from_shortcode(L.context, shortcode)
|
210 |
-
|
211 |
-
# Check if the post is a video
|
212 |
-
if not post.is_video:
|
213 |
-
raise ValueError("The provided permalink is not a video.")
|
214 |
-
|
215 |
-
# Get the video URL
|
216 |
-
video_url = post.video_url
|
217 |
-
|
218 |
-
# Extract the filename from the URL
|
219 |
-
filename = video_url.split("/")[-1]
|
220 |
-
# Remove query parameters
|
221 |
-
filename = filename.split("?")[0]
|
222 |
-
|
223 |
-
# Download the video using requests
|
224 |
-
response = requests.get(video_url, stream=True)
|
225 |
-
response.raise_for_status() # Raise an error for bad responses
|
226 |
-
|
227 |
-
# Save the content to a file
|
228 |
-
with open(filename, 'wb') as file:
|
229 |
-
for chunk in response.iter_content(chunk_size=8192):
|
230 |
-
file.write(chunk)
|
231 |
-
|
232 |
-
print(f"Downloaded video {filename} successfully.")
|
233 |
-
return filename
|
234 |
-
except Exception as e:
|
235 |
-
print(f"Failed to download video from {permalink}: {e}")
|
236 |
|
237 |
def extract_audio(input_video_name):
|
238 |
# Define the input video file and output audio file
|
239 |
mp3_file = "audio.mp3"
|
240 |
-
|
241 |
# Load the video clip
|
242 |
video_clip = VideoFileClip(input_video_name)
|
243 |
|
244 |
# Extract the audio from the video clip
|
245 |
audio_clip = video_clip.audio
|
246 |
-
|
|
|
247 |
# Write the audio to a separate file
|
248 |
audio_clip.write_audiofile(mp3_file)
|
249 |
|
@@ -252,15 +24,72 @@ def extract_audio(input_video_name):
|
|
252 |
video_clip.close()
|
253 |
|
254 |
print("Audio extraction successful!")
|
255 |
-
return mp3_file
|
256 |
|
257 |
-
def
|
258 |
-
|
259 |
-
|
260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
261 |
for segment in segments:
|
262 |
-
|
263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
264 |
|
265 |
def format_time(seconds):
|
266 |
hours = math.floor(seconds / 3600)
|
@@ -276,163 +105,39 @@ def generate_subtitle_file(language, segments, input_video_name):
|
|
276 |
subtitle_file = f"sub-{input_video_name}.{language}.srt"
|
277 |
text = ""
|
278 |
for index, segment in enumerate(segments):
|
279 |
-
segment_start = format_time(segment
|
280 |
-
segment_end = format_time(segment
|
281 |
text += f"{str(index+1)} \n"
|
282 |
text += f"{segment_start} --> {segment_end} \n"
|
283 |
-
text += f"{segment
|
284 |
text += "\n"
|
285 |
f = open(subtitle_file, "w", encoding='utf8')
|
286 |
f.write(text)
|
287 |
f.close()
|
288 |
return subtitle_file
|
289 |
|
290 |
-
def
|
291 |
-
try:
|
292 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
293 |
-
srt_content = file.read()
|
294 |
-
file.close()
|
295 |
-
return srt_content
|
296 |
-
except FileNotFoundError:
|
297 |
-
print(f"The file {file_path} was not found.")
|
298 |
-
except Exception as e:
|
299 |
-
print(f"An error occurred: {e}")
|
300 |
-
|
301 |
-
def clean_text(text):
|
302 |
-
# Remove 'srt ' from the start of each line
|
303 |
-
# Remove ''' from the start and end
|
304 |
-
text = re.sub(r"^```|```$", '', text)
|
305 |
-
text = re.sub(r'^srt', '', text, flags=re.MULTILINE)
|
306 |
-
return text
|
307 |
-
|
308 |
-
def enhance_text(api_key, text, google):
|
309 |
-
url = "https://api.one-api.ir/chatbot/v1/gpt4o/"
|
310 |
-
|
311 |
-
# Prepare the request body
|
312 |
-
request_body = [{
|
313 |
-
"role": "user",
|
314 |
-
"content": f"{text} Translate the above text into Persian, converting the English terms used in it into common Persian terms. in respose dont add any thing exept for the srt formated translation."
|
315 |
-
},]
|
316 |
-
|
317 |
-
# Add the API key to the request
|
318 |
-
headers = {
|
319 |
-
"one-api-token": api_key,
|
320 |
-
"Content-Type": "application/json"
|
321 |
-
}
|
322 |
-
|
323 |
-
# Make the POST request
|
324 |
-
response = requests.post(url, headers=headers, json=request_body)
|
325 |
-
|
326 |
-
# Check the response status
|
327 |
-
if response.status_code == 200:
|
328 |
-
result = response.json()
|
329 |
-
clean_text(result["result"][0])
|
330 |
-
last = clean_text(result["result"][0])
|
331 |
-
print("result: ")
|
332 |
-
print(last)
|
333 |
-
return last
|
334 |
-
else:
|
335 |
-
print(f"Error: {response.status_code}, {response.text}")
|
336 |
-
return None
|
337 |
-
|
338 |
-
def translate_text(api_key, source_lang, target_lang, text):
|
339 |
-
url = "https://api.one-api.ir/translate/v1/google/"
|
340 |
-
request_body = {"source": source_lang, "target": target_lang, "text": text}
|
341 |
-
headers = {"one-api-token": api_key, "Content-Type": "application/json"}
|
342 |
-
response = requests.post(url, headers=headers, json=request_body)
|
343 |
-
if response.status_code == 200:
|
344 |
-
result = response.json()
|
345 |
-
enhanced_text = enhance_text(api_key, text, result['result'])
|
346 |
-
return enhanced_text
|
347 |
-
else:
|
348 |
-
print(f"Error: {response.status_code}, {response.text}")
|
349 |
-
return None
|
350 |
-
|
351 |
-
def write_google(google_translate):
|
352 |
-
google = "google_translate.srt"
|
353 |
-
with open(google, 'w', encoding="utf-8") as f:
|
354 |
-
f.write(google_translate)
|
355 |
-
f.close()
|
356 |
-
|
357 |
-
def time_to_seconds(time_obj):
|
358 |
-
return time_obj.hours * 3600 + time_obj.minutes * 60 + time_obj.seconds + time_obj.milliseconds / 1000
|
359 |
-
|
360 |
-
def create_subtitle_clips(subtitles, videosize, fontsize, font, color, debug):
|
361 |
-
subtitle_clips = []
|
362 |
-
for subtitle in subtitles:
|
363 |
-
start_time = time_to_seconds(subtitle.start) # Add 2 seconds offset
|
364 |
-
end_time = time_to_seconds(subtitle.end)
|
365 |
-
duration = end_time - start_time
|
366 |
-
video_width, video_height = videosize
|
367 |
-
max_width = video_width * 0.8
|
368 |
-
max_height = video_height * 0.2
|
369 |
-
#reshaped_text = arabic_reshaper.reshape(subtitle.text)
|
370 |
-
#bidi_text = get_display(reshaped_text)
|
371 |
-
text_clip = TextClip(font, subtitle.text, font_size=fontsize, size=(int(video_width * 0.8), int(video_height * 0.2)) ,text_align="center" ,color=color, method='caption').with_start(start_time).with_duration(duration)
|
372 |
-
subtitle_x_position = 'center'
|
373 |
-
subtitle_y_position = video_height * 0.68
|
374 |
-
text_position = (subtitle_x_position, subtitle_y_position)
|
375 |
-
subtitle_clips.append(text_clip.with_position(text_position))
|
376 |
-
return subtitle_clips
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
def process_video(url, type):
|
381 |
-
|
382 |
-
|
383 |
-
if type=="insta":
|
384 |
-
input_video, image_path=insta_oneapi(url, api_key)
|
385 |
-
input_video_name = input_video.replace(".mp4", "")
|
386 |
-
video = VideoFileClip(input_video)
|
387 |
-
image_clip = ImageClip(image_path).with_duration(1)
|
388 |
-
# Set the position and size of the image (optional)
|
389 |
-
image_clip = image_clip.with_position(("center", "center")).resized(height=video.size[1])
|
390 |
-
first_video = CompositeVideoClip([video.with_start(1), image_clip])
|
391 |
-
input_video = input_video_name+"_cover.mp4"
|
392 |
-
input_video_name = input_video.replace(".mp4", "")
|
393 |
-
first_video.write_videofile(input_video, codec="libx264", audio_codec="aac", logger=None)
|
394 |
-
input_audio = extract_audio(input_video)
|
395 |
-
elif type=="youtube":
|
396 |
-
input_video, input_audio = one_youtube(url, api_key)
|
397 |
-
input_video_name = input_video.replace(".mp4", "")
|
398 |
-
# Get the current local time
|
399 |
-
t = time.localtime()
|
400 |
-
# Format the time as a string
|
401 |
-
current_time = time.strftime("%H:%M:%S", t)
|
402 |
-
print("Current Time =", current_time)
|
403 |
-
segments = transcribe(audio=input_audio)
|
404 |
-
language = "fa"
|
405 |
-
subtitle_file = generate_subtitle_file(language=language, segments=segments, input_video_name=input_video_name)
|
406 |
-
source_language = "en"
|
407 |
-
target_language = "fa"
|
408 |
-
srt_string = read_srt_file(subtitle_file)
|
409 |
-
google_translate = translate_text(api_key, source_language, target_language, srt_string)
|
410 |
-
write_google(google_translate)
|
411 |
-
video = VideoFileClip(input_video)
|
412 |
-
audio = AudioFileClip(input_audio)
|
413 |
-
video = video.with_audio(audio)
|
414 |
-
print(video)
|
415 |
-
subtitles = pysrt.open("google_translate.srt", encoding="utf-8")
|
416 |
-
output_video_file = input_video_name + '_subtitled' + ".mp4"
|
417 |
-
subtitle_clips = create_subtitle_clips(subtitles, video.size, 32, 'arial.ttf', 'white', False)
|
418 |
-
final_video = CompositeVideoClip([video] + subtitle_clips)
|
419 |
-
final_video.write_videofile(output_video_file, codec="libx264", audio_codec="aac", logger=None)
|
420 |
-
video.close()
|
421 |
-
audio.close()
|
422 |
-
print('final')
|
423 |
-
# Get the current local time
|
424 |
-
t = time.localtime()
|
425 |
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
return
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from faster_whisper import WhisperModel
|
|
|
|
|
2 |
import math
|
3 |
import gradio as gr
|
4 |
+
from moviepy import VideoFileClip
|
|
|
5 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
|
|
|
|
|
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
def extract_audio(input_video_name):
|
10 |
# Define the input video file and output audio file
|
11 |
mp3_file = "audio.mp3"
|
|
|
12 |
# Load the video clip
|
13 |
video_clip = VideoFileClip(input_video_name)
|
14 |
|
15 |
# Extract the audio from the video clip
|
16 |
audio_clip = video_clip.audio
|
17 |
+
duration = audio_clip.duration
|
18 |
+
print(f"Audio duration: {duration}")
|
19 |
# Write the audio to a separate file
|
20 |
audio_clip.write_audiofile(mp3_file)
|
21 |
|
|
|
24 |
video_clip.close()
|
25 |
|
26 |
print("Audio extraction successful!")
|
27 |
+
return mp3_file, duration
|
28 |
|
29 |
+
def download_video(url):
|
30 |
+
response = requests.get(url, stream=True)
|
31 |
+
response.raise_for_status()
|
32 |
+
video_file = "video.mp4"
|
33 |
+
with open(video_file, 'wb') as file:
|
34 |
+
for chunk in response.iter_content(chunk_size=8192):
|
35 |
+
if chunk:
|
36 |
+
file.write(chunk)
|
37 |
+
print("Video downloaded successfully!")
|
38 |
+
return video_file
|
39 |
+
|
40 |
+
def word_level_transcribe(audio, max_segment_duration=2.0): # Set your desired max duration here
|
41 |
+
model = WhisperModel("tiny", device="cpu")
|
42 |
+
segments, info = model.transcribe(audio, vad_filter=True, vad_parameters=dict(min_silence_duration_ms=1500), word_timestamps=True, log_progress=True)
|
43 |
+
segments = list(segments) # The transcription will actually run here.
|
44 |
+
wordlevel_info = []
|
45 |
for segment in segments:
|
46 |
+
for word in segment.words:
|
47 |
+
print("[%.2fs -> %.2fs] %s" % (word.start, word.end, word.word))
|
48 |
+
wordlevel_info.append({'word':word.word,'start':word.start,'end':word.end})
|
49 |
+
return wordlevel_info
|
50 |
+
|
51 |
+
def create_subtitles(wordlevel_info):
|
52 |
+
punctuation_marks = {'.', '!', '?', ',', ';', ':', '—', '-', '。', '!', '?'} # Add/remove punctuation as needed
|
53 |
+
subtitles = []
|
54 |
+
line = []
|
55 |
+
|
56 |
+
for word_data in wordlevel_info:
|
57 |
+
line.append(word_data)
|
58 |
+
current_word = word_data['word']
|
59 |
+
|
60 |
+
# Check if current word ends with punctuation or line reached 5 words
|
61 |
+
ends_with_punct = current_word and (current_word[-1] in punctuation_marks)
|
62 |
+
|
63 |
+
if ends_with_punct or len(line) == 5:
|
64 |
+
# Create a new subtitle segment
|
65 |
+
subtitle = {
|
66 |
+
"word": " ".join(item["word"] for item in line),
|
67 |
+
"start": line[0]["start"],
|
68 |
+
"end": line[-1]["end"],
|
69 |
+
"textcontents": line.copy()
|
70 |
+
}
|
71 |
+
subtitles.append(subtitle)
|
72 |
+
line = []
|
73 |
+
|
74 |
+
# Add remaining words if any
|
75 |
+
if line:
|
76 |
+
subtitle = {
|
77 |
+
"word": " ".join(item["word"] for item in line),
|
78 |
+
"start": line[0]["start"],
|
79 |
+
"end": line[-1]["end"],
|
80 |
+
"textcontents": line.copy()
|
81 |
+
}
|
82 |
+
subtitles.append(subtitle)
|
83 |
+
|
84 |
+
# Remove gaps between segments by extending the previous segment's end time
|
85 |
+
for i in range(1, len(subtitles)):
|
86 |
+
prev_subtitle = subtitles[i - 1]
|
87 |
+
current_subtitle = subtitles[i]
|
88 |
+
|
89 |
+
# Extend the previous segment's end time to the start of the current segment
|
90 |
+
prev_subtitle["end"] = current_subtitle["start"]
|
91 |
+
|
92 |
+
return subtitles
|
93 |
|
94 |
def format_time(seconds):
|
95 |
hours = math.floor(seconds / 3600)
|
|
|
105 |
subtitle_file = f"sub-{input_video_name}.{language}.srt"
|
106 |
text = ""
|
107 |
for index, segment in enumerate(segments):
|
108 |
+
segment_start = format_time(segment['start'])
|
109 |
+
segment_end = format_time(segment['end'])
|
110 |
text += f"{str(index+1)} \n"
|
111 |
text += f"{segment_start} --> {segment_end} \n"
|
112 |
+
text += f"{segment['word']} \n"
|
113 |
text += "\n"
|
114 |
f = open(subtitle_file, "w", encoding='utf8')
|
115 |
f.write(text)
|
116 |
f.close()
|
117 |
return subtitle_file
|
118 |
|
119 |
+
def transcribe(video):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
mp3_file, duration = extract_audio(video)
|
122 |
+
print("transcribe")
|
123 |
+
wordlevel_info=word_level_transcribe(mp3_file)
|
124 |
+
subtitles = create_subtitles(wordlevel_info)
|
125 |
+
subtitle_file = generate_subtitle_file('fa', subtitles, 'video_subtitled')
|
126 |
+
return subtitle_file, video, mp3_file
|
127 |
+
|
128 |
+
with gr.Blocks() as demo:
|
129 |
+
gr.Markdown("Start typing below and then click **Run** to see the progress and final output.")
|
130 |
+
with gr.Column():
|
131 |
+
#audio_in = gr.Audio(type="filepath")
|
132 |
+
video = gr.Video()
|
133 |
+
srt_file = gr.File()
|
134 |
+
btn = gr.Button("Create")
|
135 |
+
video_file_output = gr.Video(label="Result Video")
|
136 |
+
mp3_file = gr.Audio(type="filepath")
|
137 |
+
btn.click(
|
138 |
+
fn=transcribe,
|
139 |
+
inputs=video,
|
140 |
+
outputs=[srt_file, video_file_output, mp3_file],
|
141 |
+
)
|
142 |
+
|
143 |
+
demo.launch(debug=True)
|