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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import os
|
| 3 |
+
from os import path as osp
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from io import StringIO, BytesIO
|
| 7 |
+
import textwrap
|
| 8 |
+
from typing import Iterator, TextIO, List, Dict, Any, Optional, Sequence, Union
|
| 9 |
+
|
| 10 |
+
import glob
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from pytubefix import YouTube, Stream
|
| 13 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 14 |
+
from youtube_transcript_api.formatters import WebVTTFormatter
|
| 15 |
+
from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning
|
| 16 |
+
import torch
|
| 17 |
+
import cv2
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# encoding image at given path or PIL Image using base64
|
| 21 |
+
def encode_image(image_path_or_PIL_img):
|
| 22 |
+
if isinstance(image_path_or_PIL_img, Image.Image):
|
| 23 |
+
# this is a PIL image
|
| 24 |
+
buffered = BytesIO()
|
| 25 |
+
image_path_or_PIL_img.save(buffered, format="JPEG")
|
| 26 |
+
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 27 |
+
else:
|
| 28 |
+
# this is a image_path
|
| 29 |
+
with open(image_path_or_PIL_img, "rb") as image_file:
|
| 30 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# checking whether the given string is base64 or not
|
| 34 |
+
def isBase64(sb):
|
| 35 |
+
try:
|
| 36 |
+
if isinstance(sb, str):
|
| 37 |
+
# If there's any unicode here, an exception will be thrown and the function will return false
|
| 38 |
+
sb_bytes = bytes(sb, 'ascii')
|
| 39 |
+
elif isinstance(sb, bytes):
|
| 40 |
+
sb_bytes = sb
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError("Argument must be string or bytes")
|
| 43 |
+
return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes
|
| 44 |
+
except Exception:
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def create_dummy_image(size=(224, 224)):
|
| 49 |
+
"""Creates a blank white image to be used as a dummy input when no real image is provided."""
|
| 50 |
+
return Image.new("RGB", size, (255, 255, 255))
|
| 51 |
+
|
| 52 |
+
def bt_embeddings(prompt, base64_image=None):
|
| 53 |
+
# Load the processor and model
|
| 54 |
+
processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
|
| 55 |
+
model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
|
| 56 |
+
|
| 57 |
+
if base64_image:
|
| 58 |
+
if not isBase64(base64_image):
|
| 59 |
+
raise TypeError("Image input must be in base64 encoding!")
|
| 60 |
+
try:
|
| 61 |
+
image_data = base64.b64decode(base64_image)
|
| 62 |
+
image = Image.open(BytesIO(image_data)).convert("RGB")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
raise ValueError("Invalid image data!") from e
|
| 65 |
+
else:
|
| 66 |
+
image = create_dummy_image() # Use a dummy white image for text-only input
|
| 67 |
+
|
| 68 |
+
texts = [prompt]
|
| 69 |
+
images = [image]
|
| 70 |
+
|
| 71 |
+
inputs = processor(images=images, text=texts, padding=True, return_tensors="pt")
|
| 72 |
+
|
| 73 |
+
with torch.no_grad():
|
| 74 |
+
outputs = model(**inputs)
|
| 75 |
+
|
| 76 |
+
if base64_image:
|
| 77 |
+
embeddings = outputs.cross_embeds # Use cross-modal embeddings when an image is provided
|
| 78 |
+
else:
|
| 79 |
+
embeddings = outputs.text_embeds # Extract unimodal text embeddings
|
| 80 |
+
|
| 81 |
+
return embeddings.squeeze().tolist()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# Resizes a image and maintains aspect ratio
|
| 85 |
+
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
|
| 86 |
+
# Grab the image size and initialize dimensions
|
| 87 |
+
dim = None
|
| 88 |
+
(h, w) = image.shape[:2]
|
| 89 |
+
|
| 90 |
+
# Return original image if no need to resize
|
| 91 |
+
if width is None and height is None:
|
| 92 |
+
return image
|
| 93 |
+
|
| 94 |
+
# We are resizing height if width is none
|
| 95 |
+
if width is None:
|
| 96 |
+
# Calculate the ratio of the height and construct the dimensions
|
| 97 |
+
r = height / float(h)
|
| 98 |
+
dim = (int(w * r), height)
|
| 99 |
+
# We are resizing width if height is none
|
| 100 |
+
else:
|
| 101 |
+
# Calculate the ratio of the width and construct the dimensions
|
| 102 |
+
r = width / float(w)
|
| 103 |
+
dim = (width, int(h * r))
|
| 104 |
+
|
| 105 |
+
# Return the resized image
|
| 106 |
+
return cv2.resize(image, dim, interpolation=inter)
|
| 107 |
+
|
| 108 |
+
# a help function that helps to convert a specific time written as a string in format `webvtt` into a time in miliseconds
|
| 109 |
+
def str2time(strtime):
|
| 110 |
+
# strip character " if exists
|
| 111 |
+
strtime = strtime.strip('"')
|
| 112 |
+
# get hour, minute, second from time string
|
| 113 |
+
hrs, mins, seconds = [float(c) for c in strtime.split(':')]
|
| 114 |
+
# get the corresponding time as total seconds
|
| 115 |
+
total_seconds = hrs * 60**2 + mins * 60 + seconds
|
| 116 |
+
total_miliseconds = total_seconds * 1000
|
| 117 |
+
return total_miliseconds
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# helper function for convert time in second to time format for .vtt or .srt file
|
| 121 |
+
def format_timestamp(seconds: float, always_include_hours: bool = False, fractionalSeperator: str = '.'):
|
| 122 |
+
assert seconds >= 0, "non-negative timestamp expected"
|
| 123 |
+
milliseconds = round(seconds * 1000.0)
|
| 124 |
+
|
| 125 |
+
hours = milliseconds // 3_600_000
|
| 126 |
+
milliseconds -= hours * 3_600_000
|
| 127 |
+
|
| 128 |
+
minutes = milliseconds // 60_000
|
| 129 |
+
milliseconds -= minutes * 60_000
|
| 130 |
+
|
| 131 |
+
seconds = milliseconds // 1_000
|
| 132 |
+
milliseconds -= seconds * 1_000
|
| 133 |
+
|
| 134 |
+
hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
|
| 135 |
+
return f"{hours_marker}{minutes:02d}:{seconds:02d}{fractionalSeperator}{milliseconds:03d}"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _processText(text: str, maxLineWidth=None):
|
| 139 |
+
if (maxLineWidth is None or maxLineWidth < 0):
|
| 140 |
+
return text
|
| 141 |
+
|
| 142 |
+
lines = textwrap.wrap(text, width=maxLineWidth, tabsize=4)
|
| 143 |
+
return '\n'.join(lines)
|
| 144 |
+
|
| 145 |
+
# helper function to convert transcripts generated by whisper to .vtt file
|
| 146 |
+
def write_vtt(transcript: Iterator[dict], file: TextIO, maxLineWidth=None):
|
| 147 |
+
print("WEBVTT\n", file=file)
|
| 148 |
+
for segment in transcript:
|
| 149 |
+
text = _processText(segment['text'], maxLineWidth).replace('-->', '->')
|
| 150 |
+
|
| 151 |
+
print(
|
| 152 |
+
f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n"
|
| 153 |
+
f"{text}\n",
|
| 154 |
+
file=file,
|
| 155 |
+
flush=True,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# helper function to convert transcripts generated by whisper to .srt file
|
| 159 |
+
def write_srt(transcript: Iterator[dict], file: TextIO, maxLineWidth=None):
|
| 160 |
+
"""
|
| 161 |
+
Write a transcript to a file in SRT format.
|
| 162 |
+
Example usage:
|
| 163 |
+
from pathlib import Path
|
| 164 |
+
from whisper.utils import write_srt
|
| 165 |
+
result = transcribe(model, audio_path, temperature=temperature, **args)
|
| 166 |
+
# save SRT
|
| 167 |
+
audio_basename = Path(audio_path).stem
|
| 168 |
+
with open(Path(output_dir) / (audio_basename + ".srt"), "w", encoding="utf-8") as srt:
|
| 169 |
+
write_srt(result["segments"], file=srt)
|
| 170 |
+
"""
|
| 171 |
+
for i, segment in enumerate(transcript, start=1):
|
| 172 |
+
text = _processText(segment['text'].strip(), maxLineWidth).replace('-->', '->')
|
| 173 |
+
|
| 174 |
+
# write srt lines
|
| 175 |
+
print(
|
| 176 |
+
f"{i}\n"
|
| 177 |
+
f"{format_timestamp(segment['start'], always_include_hours=True, fractionalSeperator=',')} --> "
|
| 178 |
+
f"{format_timestamp(segment['end'], always_include_hours=True, fractionalSeperator=',')}\n"
|
| 179 |
+
f"{text}\n",
|
| 180 |
+
file=file,
|
| 181 |
+
flush=True,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def getSubs(segments: Iterator[dict], format: str, maxLineWidth: int=-1) -> str:
|
| 185 |
+
segmentStream = StringIO()
|
| 186 |
+
|
| 187 |
+
if format == 'vtt':
|
| 188 |
+
write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
|
| 189 |
+
elif format == 'srt':
|
| 190 |
+
write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
|
| 191 |
+
else:
|
| 192 |
+
raise Exception("Unknown format " + format)
|
| 193 |
+
|
| 194 |
+
segmentStream.seek(0)
|
| 195 |
+
return segmentStream.read()
|
| 196 |
+
|
| 197 |
+
def download_video(video_url, path='/tmp/'):
|
| 198 |
+
print(f'Getting video information for {video_url}')
|
| 199 |
+
if not video_url.startswith('http'):
|
| 200 |
+
return os.path.join(path, video_url)
|
| 201 |
+
|
| 202 |
+
filepath = glob.glob(os.path.join(path, '*.mp4'))
|
| 203 |
+
if len(filepath) > 0:
|
| 204 |
+
return filepath[0]
|
| 205 |
+
|
| 206 |
+
def progress_callback(stream: Stream, data_chunk: bytes, bytes_remaining: int) -> None:
|
| 207 |
+
pbar.update(len(data_chunk))
|
| 208 |
+
|
| 209 |
+
yt = YouTube(video_url, on_progress_callback=progress_callback)
|
| 210 |
+
stream = yt.streams.filter(progressive=True, file_extension='mp4', res='720p').desc().first()
|
| 211 |
+
if stream is None:
|
| 212 |
+
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
|
| 213 |
+
if not os.path.exists(path):
|
| 214 |
+
os.makedirs(path)
|
| 215 |
+
filepath = os.path.join(path, stream.default_filename)
|
| 216 |
+
if not os.path.exists(filepath):
|
| 217 |
+
print('Downloading video from YouTube...')
|
| 218 |
+
pbar = tqdm(desc='Downloading video from YouTube', total=stream.filesize, unit="bytes")
|
| 219 |
+
stream.download(path)
|
| 220 |
+
pbar.close()
|
| 221 |
+
return filepath
|
| 222 |
+
|
| 223 |
+
def get_video_id_from_url(video_url):
|
| 224 |
+
"""
|
| 225 |
+
Examples:
|
| 226 |
+
- http://youtu.be/SA2iWivDJiE
|
| 227 |
+
- http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu
|
| 228 |
+
- http://www.youtube.com/embed/SA2iWivDJiE
|
| 229 |
+
- http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US
|
| 230 |
+
"""
|
| 231 |
+
import urllib.parse
|
| 232 |
+
url = urllib.parse.urlparse(video_url)
|
| 233 |
+
if url.hostname == 'youtu.be':
|
| 234 |
+
return url.path[1:]
|
| 235 |
+
if url.hostname in ('www.youtube.com', 'youtube.com'):
|
| 236 |
+
if url.path == '/watch':
|
| 237 |
+
p = urllib.parse.parse_qs(url.query)
|
| 238 |
+
return p['v'][0]
|
| 239 |
+
if url.path[:7] == '/embed/':
|
| 240 |
+
return url.path.split('/')[2]
|
| 241 |
+
if url.path[:3] == '/v/':
|
| 242 |
+
return url.path.split('/')[2]
|
| 243 |
+
|
| 244 |
+
return video_url
|
| 245 |
+
|
| 246 |
+
# if this has transcript then download
|
| 247 |
+
def get_transcript_vtt(video_url, path='/tmp'):
|
| 248 |
+
video_id = get_video_id_from_url(video_url)
|
| 249 |
+
filepath = os.path.join(path,'captions.vtt')
|
| 250 |
+
if os.path.exists(filepath):
|
| 251 |
+
return filepath
|
| 252 |
+
|
| 253 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en-GB', 'en'])
|
| 254 |
+
formatter = WebVTTFormatter()
|
| 255 |
+
webvtt_formatted = formatter.format_transcript(transcript)
|
| 256 |
+
|
| 257 |
+
with open(filepath, 'w', encoding='utf-8') as webvtt_file:
|
| 258 |
+
webvtt_file.write(webvtt_formatted)
|
| 259 |
+
webvtt_file.close()
|
| 260 |
+
|
| 261 |
+
return filepath
|
| 262 |
+
|
| 263 |
+
# if this has transcript then download
|
| 264 |
+
def download_youtube_subtitle(video_url, path='./shared_data/videos/video1'):
|
| 265 |
+
video_id = video_url.split('v=')[-1]
|
| 266 |
+
output_path = os.path.join(path, f"{video_id}.en.vtt")
|
| 267 |
+
|
| 268 |
+
if os.path.exists(output_path):
|
| 269 |
+
return output_path
|
| 270 |
+
|
| 271 |
+
os.makedirs(path, exist_ok=True)
|
| 272 |
+
|
| 273 |
+
ydl_opts = {
|
| 274 |
+
'skip_download': True,
|
| 275 |
+
'writesubtitles': True,
|
| 276 |
+
'subtitleslangs': ['en'],
|
| 277 |
+
'subtitlesformat': 'vtt',
|
| 278 |
+
'outtmpl': os.path.join(path, '%(id)s.%(ext)s'),
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 282 |
+
ydl.download([video_url])
|
| 283 |
+
|
| 284 |
+
return output_path
|