Spaces:
Runtime error
Runtime error
File size: 22,610 Bytes
134e8b7 251794a 7997dd9 134e8b7 43c92dd 134e8b7 7997dd9 134e8b7 2b03cfe 134e8b7 2b03cfe 134e8b7 3525fa5 134e8b7 921d4a0 134e8b7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# Usage
### python main.py --mode interface
### python main.py videos/Spirituality_1_clip.mp4 -n 3 --mode inference --model gemini
import gradio as gr
import os
import whisper
import cv2
import json
import tempfile
import torch
import transformers
from transformers import pipeline
import re
import time
from torch import cuda, bfloat16
from moviepy.editor import VideoFileClip
from image_caption import Caption
from pathlib import Path
from langchain import PromptTemplate
from langchain import LLMChain
from langchain.llms import HuggingFacePipeline
from difflib import SequenceMatcher
import argparse
import shutil
from PIL import Image
import google.generativeai as genai
from huggingface_hub import InferenceClient
from openai import OpenAI
class VideoClassifier:
global audio_time , setup_time , caption_time , classification_time
audio_time = 0
setup_time = 0
caption_time = 0
classification_time = 0
def __init__(self, no_of_frames, mode='interface',model='mistral'):
self.hf_key = os.environ.get("HF_KEY", None)
self.no_of_frames = no_of_frames
self.mode = mode
self.model_name = model.strip().lower()
print(self.model_name)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
if self.model_name=='mistral':
print("Setting up Mistral model for Class Selection")
self.setup_mistral_space_model()
else :
print("Setting up Gemini model for Class Selection")
self.setup_gemini_model()
self.setup_paths()
# self.hf_key = os.environ.get("HF_KEY", None)
"""chatgpt 3.5"""
# self.chatgpt_client = OpenAI(api_key="sk-proj-KY1qI7zTpsUiJhMUHuNdT3BlbkFJLOjVnTUSpYJi87yUtSEI")
self.chatgpt_client= OpenAI(api_key="sk-proj-TVoFQ4X9apDUs0V6zCDIT3BlbkFJmWRNMgJ6fapge12zygzG")
# self.whisper_model = whisper.load_model("base")
def setup_paths(self):
self.path = './results'
if os.path.exists(self.path):
shutil.rmtree(self.path)
os.mkdir(self.path)
def setup_gemini_model(self):
self.genai = genai
self.genai.configure(api_key="AIzaSyAFG94rVbm9eWepO5uPGsMha8XJ-sHbMdA")
self.genai_model = genai.GenerativeModel('gemini-pro')
self.whisper_model = whisper.load_model("base")
self.img_cap = Caption()
def setup_mistral_space_model(self):
# if not self.hf_key:
# raise ValueError("Hugging Face API key is not set or invalid.")
self.client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
# self.client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.1")
# self.client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
self.whisper_model = whisper.load_model("base")
self.img_cap = Caption()
def setup_mistral_model(self):
self.model_id = "mistralai/Mistral-7B-Instruct-v0.2"
self.device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
# self.device_name = torch.cuda.get_device_name()
# print(f"Using device: {self.device} ({self.device_name})")
bnb_config = transformers.BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type='nf4',
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=bfloat16,
)
hf_auth = self.hf_key
print(hf_auth)
model_config = transformers.AutoConfig.from_pretrained(
self.model_id,
# use_auth_token=hf_auth
)
self.model = transformers.AutoModelForCausalLM.from_pretrained(
self.model_id,
trust_remote_code=True,
config=model_config,
quantization_config=bnb_config,
# use_auth_token=hf_auth
)
self.model.eval()
self.tokenizer = transformers.AutoTokenizer.from_pretrained(
self.model_id,
# use_auth_token=hf_auth
)
self.generate_text = transformers.pipeline(
model=self.model, tokenizer=self.tokenizer,
return_full_text=True,
task='text-generation',
temperature=0.01,
max_new_tokens=32
)
self.whisper_model = whisper.load_model("base")
self.img_cap = Caption()
self.llm = HuggingFacePipeline(pipeline=self.generate_text)
def audio_extraction(self,video_input):
"""When running on local we use this library approach which consumes 3 seconds of gpu inference"""
global audio_time
start_time_audio = time.time()
print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
mp4_file = video_input
video_name = mp4_file.split("/")[-1]
wav_file = "results/audiotrack.wav"
video_clip = VideoFileClip(mp4_file)
audioclip = video_clip.audio
wav_file = audioclip.write_audiofile(wav_file)
audioclip.close()
video_clip.close()
audiotrack = "results/audiotrack.wav"
result = self.whisper_model.transcribe(audiotrack, fp16=False)
transcript = result["text"]
print("TRANSCRIPT",transcript)
end_time_audio = time.time()
audio_time=end_time_audio-start_time_audio
# print("TIME TAKEN FOR AUDIO CONVERSION (WHISPER)",audio_time)
return transcript
def audio_extraction_space(self,video_input):
"""When running the project in space we use model directly from huggingface to beat the inference time"""
MODEL_NAME = "openai/whisper-large-v3"
BATCH_SIZE = 8
device = "cuda" if torch.cuda.is_available() else "cpu"
global audio_time
start_time_audio = time.time()
print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
mp4_file = video_input
video_name = mp4_file.split("/")[-1]
wav_file = "results/audiotrack.wav"
video_clip = VideoFileClip(mp4_file)
audioclip = video_clip.audio
wav_file = audioclip.write_audiofile(wav_file)
audioclip.close()
video_clip.close()
audiotrack = "results/audiotrack.wav"
pipe = pipeline(
"automatic-speech-recognition",
model=MODEL_NAME,
device=device
)
# if audio_file is None:
# return "No audio file submitted! Please upload or record an audio file before submitting your request."
# if not os.path.exists(audio_file):
# return "File does not exist. Please check the file path."
task="transcribe"
result = pipe(audiotrack, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
return result["text"]
def audio_extraction_chatgptapi(self,video_input):
"""For cpu inference , we use this function for faster api calling inference"""
global audio_time
start_time_audio = time.time()
print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
mp4_file = video_input
video_name = mp4_file.split("/")[-1]
wav_file = "results/audiotrack.wav"
video_clip = VideoFileClip(mp4_file)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
video_clip.audio.write_audiofile(temp_audio.name, codec='pcm_s16le', nbytes=2, fps=16000)
video_clip.close()
with open(temp_audio.name, 'rb') as audio_file:
transcription = self.chatgpt_client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
print(transcription.text)
os.remove(temp_audio.name)
# audioclip = video_clip.audio
# wav_file = audioclip.write_audiofile(wav_file)
# audioclip.close()
# video_clip.close()
# audiotrack = "results/audiotrack.wav"
# # client = OpenAI(api_key="sk-proj-KY1qI7zTpsUiJhMUHuNdT3BlbkFJLOjVnTUSpYJi87yUtSEI")
# # audiotrack= open("audiotrack.wav", "rb")
# transcription = self.client.audio.transcriptions.create(
# model="whisper-1",
# file=audioclip
# )
# print(transcription.text)
return transcription.text
def generate_text(self, inputs, parameters=None):
if parameters is None:
parameters = {
"temperature": 0.7,
"max_new_tokens": 50,
"top_p": 0.9,
"repetition_penalty": 1.2
}
return self.client(inputs, parameters)
default_checkbox = []
def classify_video(self,video_input,checkbox=default_checkbox):
global classification_time , caption_time
print("checkbox",checkbox)
# transcript=self.audio_extraction_space(video_input)
try:
transcript=self.audio_extraction(video_input)
except:
transcript=self.audio_extraction_space(video_input)
# try:
# transcript=self.audio_extraction_chatgptapi(video_input)
# except :
# print("Chatgpt Key expired , inferencing using whisper library")
# try:
# transcript=self.audio_extraction(video_input)
# except:
# transcript=self.audio_extraction_space(video_input)
start_time_caption = time.time()
captions = ""
if checkbox==["Image Captions and Audio for Classification"]:
video = cv2.VideoCapture(video_input)
length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
no_of_frame = int(self.no_of_frames)
temp_div = length // no_of_frame
currentframe = 50
caption_text = []
for i in range(no_of_frame):
video.set(cv2.CAP_PROP_POS_FRAMES, currentframe)
ret, frame = video.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(frame)
content = self.img_cap.predict_image_caption_gemini(image)
print("content", content)
caption_text.append(content)
currentframe += temp_div - 1
else:
break
captions = ", ".join(caption_text)
print("CAPTIONS", captions)
video.release()
cv2.destroyAllWindows()
# print("TIME TAKEN FOR IMAGE CAPTIONING", end_time_caption-start_time_caption)
end_time_caption = time.time()
caption_time=end_time_caption-start_time_caption
start_time_generation = time.time()
main_categories = Path("main_classes.txt").read_text()
main_categories_list = ['Automotive', 'Books and Literature', 'Business and Finance', 'Careers', 'Education','Family and Relationships',
'Fine Art', 'Food & Drink', 'Healthy Living', 'Hobbies & Interests', 'Home & Garden','Medical Health', 'Movies', 'Music and Audio',
'News and Politics', 'Personal Finance', 'Pets', 'Pop Culture','Real Estate', 'Religion & Spirituality', 'Science', 'Shopping', 'Sports',
'Style & Fashion','Technology & Computing', 'Television', 'Travel', 'Video Gaming']
generate_kwargs = {
"temperature": 0.9,
"max_new_tokens": 256,
"top_p": 0.95,
"repetition_penalty": 1.0,
"do_sample": True,
"seed": 42,
"return_full_text": False
}
template1 = '''Given below are the different type of main video classes
{main_categories}
You are a text classifier that catergorises the transcript and captions into one main class whose context match with one main class and only generate main class name no need of sub classe or explanation.
Give more importance to Transcript while classifying .
Transcript: {transcript}
Captions: {captions}
Return only the answer chosen from list and nothing else
Main-class => '''
prompt1 = PromptTemplate(template=template1, input_variables=['main_categories', 'transcript', 'captions'])
print("PROMPT 1",prompt1)
# print(self.model)
# print(f"Current model in use: {self.model}")
if self.model_name=='mistral':
try:
print("Entering mistral chain approach")
chain1 = LLMChain(llm=self.llm, prompt=prompt1)
main_class = chain1.predict(main_categories=main_categories, transcript=transcript, captions=captions)
except:
print("Entering mistral template approach")
prompt1 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
messages = [{"role": "user", "content": prompt1}]
stream = self.client.chat_completion(messages, max_tokens=100)
main_class = stream.choices[0].message.content.strip()
# output = ""
# for response in stream:
# output += response['token'].text
# print("Streaming output:", output)
# main_class = output.strip()
print(main_class)
print("#######################################################")
try:
pattern = r"Main-class =>\s*(.+)"
match = re.search(pattern, main_class)
if match:
main_class = match.group(1).strip()
except:
main_class=main_class
else:
prompt_text = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
response = self.genai_model.generate_content(contents=prompt_text)
main_class = response.text
print(main_class)
print("#######################################################")
print("MAIN CLASS: ",main_class)
def category_class(class_name,categories_list):
def similar(str1, str2):
return SequenceMatcher(None, str1, str2).ratio()
index_no = 0
sim = 0
for sub in categories_list:
res = similar(class_name, sub)
if res>sim:
sim = res
index_no = categories_list.index(sub)
class_name = categories_list[index_no]
return class_name
if main_class not in main_categories_list:
main_class = category_class(main_class,main_categories_list)
print("POST PROCESSED MAIN CLASS : ",main_class)
tier_1_index_no = main_categories_list.index(main_class) + 1
with open('categories_json.txt') as f:
data = json.load(f)
sub_categories_list = data[main_class]
print("SUB CATEGORIES LIST",sub_categories_list)
with open("sub_categories.txt", "w") as f:
no = 1
# print(data[main_class])
for i in data[main_class]:
f.write(str(no)+')'+str(i) + '\n')
no = no+1
sub_categories = Path("sub_categories.txt").read_text()
template2 = '''Given below are the sub classes of {main_class}.
{sub_categories}
You are a text classifier that catergorises the transcript and captions into one sub class whose context match with one sub class and only generate sub class name, Don't give explanation .
Give more importance to Transcript while classifying .
Transcript: {transcript}
Captions: {captions}
Return only the Sub-class answer chosen from list and nothing else
Answer in the format:
Main-class => {main_class}
Sub-class =>
'''
prompt2 = PromptTemplate(template=template2, input_variables=['sub_categories', 'transcript', 'captions','main_class'])
if self.model_name=='mistral':
try:
chain2 = LLMChain(llm=self.llm, prompt=prompt2)
sub_class = chain2.predict(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
except:
prompt2 = template2.format(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
messages = [{"role": "user", "content": prompt2}]
stream = self.client.chat_completion(messages, max_tokens=100)
sub_class = stream.choices[0].message.content.strip()
print("Preprocess Answer",sub_class)
try:
pattern = r"Sub-class =>\s*(.+)"
match = re.search(pattern, sub_class)
if match:
sub_class = match.group(1).strip()
except:
subclass=sub_class
else:
prompt_text2 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
response = self.genai_model.generate_content(contents=prompt_text2)
sub_class = response.text
print("Preprocess Answer",sub_class)
print("SUB CLASS",sub_class)
if sub_class not in sub_categories_list:
sub_class = category_class(sub_class,sub_categories_list)
print("POST PROCESSED SUB CLASS",sub_class)
tier_2_index_no = sub_categories_list.index(sub_class) + 1
print("ANSWER:",sub_class)
final_answer = (f"Tier 1 category : IAB{tier_1_index_no} : {main_class}\nTier 2 category : IAB{tier_1_index_no}-{tier_2_index_no} : {sub_class}")
first_video = os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")
second_video = os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4")
# return final_answer, first_video, second_video
end_time_generation = time.time()
classification_time = end_time_generation-start_time_generation
print ("MODEL USED :",self.model_name)
print("MODEL SETUP TIME :",setup_time)
print("TIME TAKEN FOR AUDIO CONVERSION (WHISPER) :",audio_time)
print("TIME TAKEN FOR IMAGE CAPTIONING :", caption_time)
print("TIME TAKEN FOR CLASS GENERATION :",classification_time)
print("TOTAL INFERENCE TIME :",audio_time+caption_time+classification_time)
return final_answer
def save_model_choice(self,model_name):
global setup_time
start_time_setup = time.time()
if not model_name:
model_name = "mistral"
self.model_name = model_name
if self.model_name=='mistral':
print("Setting up Mistral model for Class Selection")
self.setup_mistral_space_model()
else :
print("Setting up Gemini model for Class Selection")
self.setup_gemini_model()
end_time_setup = time.time()
setup_time=end_time_setup-start_time_setup
# print("MODEL SETUP TIME",setup_time)
return "Model selected: " + model_name
def launch_interface(self):
css_code = """
.gradio-container {
background-color: #daccdb;
}
/* Button styling for all buttons */
button {
background-color: #d6cbd6; /* Default color for all other buttons */
color: black;
border: 1px solid black;
padding: 10px;
margin-right: 10px;
font-size: 16px; /* Increase font size */
font-weight: bold; /* Make text bold */
}
/* Style for the second button */
button:nth-child(2) {
background-color: #927fc7;
color: black;
}
"""
interface_1 = gr.Interface(
self.save_model_choice,
inputs=gr.Dropdown(choices=['mistral','gemini'], label="Select Model", info="Default model: Mistral"),
# outputs=interface_1_output,
outputs="text",
title="Model Selection",
)
video_examples = [
[os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")],
[os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4")],
[os.path.join(os.path.dirname(__file__), "Motorcycle_clip.mp4")],
[os.path.join(os.path.dirname(__file__), "Spirituality_1_clip.mp4")],
[os.path.join(os.path.dirname(__file__), "Science_clip.mp4")]
]
# Define the checkbox for additional feature control
checkbox = gr.CheckboxGroup(
["Image Captions and Audio for Classification"],
label="Features",
info="default : Audio for classification",
)
default_checkbox = []
demo = gr.Interface(fn=self.classify_video, inputs=["playablevideo",checkbox],allow_flagging='never', examples=video_examples,
cache_examples=False, outputs=["text"],
css=css_code, title="Interactive Advertising Bureau (IAB) compliant Video-Ad classification")
# demo.launch(debug=True)
gr.TabbedInterface([interface_1, demo], ["Model Selection", "Video Classification"],css=css_code,).launch(debug=True)
def run_inference(self, video_path,model):
result = self.classify_video(video_path)
print(result)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some videos.')
parser.add_argument("video_path", nargs='?', default=None, help="Path to the video file")
parser.add_argument("-n", "--no_of_frames", type=int, default=3, help="Number of frames for image captioning")
parser.add_argument("--mode", choices=['interface', 'inference'], default='interface', help="Mode of operation: interface or inference")
parser.add_argument("--model", choices=['gemini','mistral'],default='mistral',help="Model for inference")
args = parser.parse_args()
vc = VideoClassifier(no_of_frames=args.no_of_frames, mode=args.mode , model=args.model)
if args.mode == 'interface':
vc.launch_interface()
elif args.mode == 'inference' and args.video_path and args.model:
vc.run_inference(args.video_path,args.model)
else:
print("Error: No video path/model provided for inference mode.")
|