IAB_VIDEO_AD_CLASSIFIER / app_error.py
arjunanand13's picture
Rename app.py to app_error.py
3d2a582 verified
raw
history blame
24.7 kB
# 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='gemini'):
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_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()
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():
css_code = """
.gradio-container {
background-color: #d6cbd6;
}
/* 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; /* Custom color for the second button */
}
"""
# First interface for model selection
interface_1 = gr.Interface(
fn=save_model_choice,
inputs=gr.Dropdown(
choices=['gemini', 'mistral'],
label="Select Model",
info="Default model: Gemini",
),
outputs="text",
title="Model Selection",
)
# Second interface for video classification
video_examples = [
[os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")],
[os.path.dirname(__file__) + "/PersonalFinance_clip.mp4"],
[os.path.dirname(__file__) + "/Motorcycle_clip.mp4"],
[os.path.dirname(__file__) + "/Spirituality_1_clip.mp4"],
[os.path.dirname(__file__) + "/Science_clip.mp4"],
]
checkbox = gr.CheckboxGroup(
["Image Captions and Audio for Classification"],
label="Features",
info="default: Audio for classification",
)
interface_2 = gr.Interface(
fn=classify_video,
inputs=[gr.PlayableVideo(), checkbox],
outputs="text",
examples=video_examples,
title="Video Classification",
css=css_code,
)
# Create a tabbed interface
gr.TabbedInterface(
[interface_1, interface_2],
["Model Selection", "Video Classification"],
css=css_code,
).launch(debug=True, share=True)
launch_interface()
# css_code = """
# .gradio-container {background-color: #FFFFFF;color:#000000;background-size: 200px; background-image:url(https://gitlab.ignitarium.in/saran/logo/-/raw/aab7c77b4816b8a4bbdc5588eb57ce8b6c15c72d/ign_logo_white.png);background-repeat:no-repeat; position:relative; top:1px; left:5px; padding: 50px;text-align: right;background-position: right top;}
# """
# css_code += """
# :root {
# --body-background-fill: #FFFFFF; /* New value */
# }
# """
# css_code += """
# :root {
# --body-background-fill: #000000; /* New value */
# }
# """
# interface_1 = gr.Interface(
# self.save_model_choice,
# inputs=gr.Dropdown(choices=['gemini', 'mistral'], label="Select Model", info="Default model: Gemini"),
# # outputs=interface_1_output,
# outputs="text"
# )
# 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"]).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='gemini',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.")