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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import whisper
|
4 |
+
import cv2
|
5 |
+
import json
|
6 |
+
import tempfile
|
7 |
+
import torch
|
8 |
+
import transformers
|
9 |
+
import re
|
10 |
+
import time
|
11 |
+
from torch import cuda, bfloat16
|
12 |
+
from moviepy.editor import VideoFileClip
|
13 |
+
from image_caption import Caption
|
14 |
+
from pathlib import Path
|
15 |
+
from langchain import PromptTemplate
|
16 |
+
from langchain import LLMChain
|
17 |
+
from langchain.llms import HuggingFacePipeline
|
18 |
+
from difflib import SequenceMatcher
|
19 |
+
import argparse
|
20 |
+
import shutil
|
21 |
+
from PIL import Image
|
22 |
+
import google.generativeai as genai
|
23 |
+
|
24 |
+
class VideoClassifier:
|
25 |
+
def __init__(self, no_of_frames, mode='interface',model='gemini'):
|
26 |
+
self.no_of_frames = no_of_frames
|
27 |
+
self.mode = mode
|
28 |
+
self.model_name = model.strip().lower()
|
29 |
+
print(self.model_name)
|
30 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
31 |
+
if self.model_name=='mistral':
|
32 |
+
print("Setting up Mistral model for Class Selection")
|
33 |
+
self.setup_mistral_model()
|
34 |
+
else :
|
35 |
+
print("Setting up Gemini model for Class Selection")
|
36 |
+
self.setup_gemini_model()
|
37 |
+
self.setup_paths()
|
38 |
+
|
39 |
+
def setup_paths(self):
|
40 |
+
self.path = './results'
|
41 |
+
if os.path.exists(self.path):
|
42 |
+
shutil.rmtree(self.path) # Remove the directory if it exists
|
43 |
+
os.mkdir(self.path)
|
44 |
+
|
45 |
+
def setup_gemini_model(self):
|
46 |
+
self.genai = genai
|
47 |
+
self.genai.configure(api_key="AIzaSyAFG94rVbm9eWepO5uPGsMha8XJ-sHbMdA")
|
48 |
+
self.genai_model = genai.GenerativeModel('gemini-pro')
|
49 |
+
self.whisper_model = whisper.load_model("base")
|
50 |
+
self.img_cap = Caption()
|
51 |
+
|
52 |
+
def setup_mistral_model(self):
|
53 |
+
self.model_id = "mistralai/Mistral-7B-Instruct-v0.2"
|
54 |
+
self.device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
|
55 |
+
self.device_name = torch.cuda.get_device_name()
|
56 |
+
# print(f"Using device: {self.device} ({self.device_name})")
|
57 |
+
bnb_config = transformers.BitsAndBytesConfig(
|
58 |
+
load_in_4bit=True,
|
59 |
+
bnb_4bit_quant_type='nf4',
|
60 |
+
bnb_4bit_use_double_quant=True,
|
61 |
+
bnb_4bit_compute_dtype=bfloat16,
|
62 |
+
)
|
63 |
+
hf_auth = hf_key
|
64 |
+
model_config = transformers.AutoConfig.from_pretrained(
|
65 |
+
self.model_id,
|
66 |
+
use_auth_token=hf_auth
|
67 |
+
)
|
68 |
+
self.model = transformers.AutoModelForCausalLM.from_pretrained(
|
69 |
+
self.model_id,
|
70 |
+
trust_remote_code=True,
|
71 |
+
config=model_config,
|
72 |
+
quantization_config=bnb_config,
|
73 |
+
use_auth_token=hf_auth
|
74 |
+
)
|
75 |
+
self.model.eval()
|
76 |
+
self.tokenizer = transformers.AutoTokenizer.from_pretrained(
|
77 |
+
self.model_id,
|
78 |
+
use_auth_token=hf_auth
|
79 |
+
)
|
80 |
+
self.generate_text = transformers.pipeline(
|
81 |
+
model=self.model, tokenizer=self.tokenizer,
|
82 |
+
return_full_text=True,
|
83 |
+
task='text-generation',
|
84 |
+
temperature=0.01,
|
85 |
+
max_new_tokens=32
|
86 |
+
)
|
87 |
+
self.whisper_model = whisper.load_model("base")
|
88 |
+
self.img_cap = Caption()
|
89 |
+
self.llm = HuggingFacePipeline(pipeline=self.generate_text)
|
90 |
+
|
91 |
+
def audio_extraction(self,video_input):
|
92 |
+
print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
|
93 |
+
mp4_file = video_input
|
94 |
+
video_name = mp4_file.split("/")[-1]
|
95 |
+
wav_file = "results/audiotrack.wav"
|
96 |
+
video_clip = VideoFileClip(mp4_file)
|
97 |
+
audioclip = video_clip.audio
|
98 |
+
wav_file = audioclip.write_audiofile(wav_file)
|
99 |
+
audioclip.close()
|
100 |
+
video_clip.close()
|
101 |
+
audiotrack = "results/audiotrack.wav"
|
102 |
+
result = self.whisper_model.transcribe(audiotrack, fp16=False)
|
103 |
+
transcript = result["text"]
|
104 |
+
print("TRANSCRIPT",transcript)
|
105 |
+
return transcript
|
106 |
+
|
107 |
+
|
108 |
+
def classify_video(self,video_input,model_selection=None):
|
109 |
+
if model_selection is not None:
|
110 |
+
self.model = model_selection
|
111 |
+
print(f"Model set to: {self.model}")
|
112 |
+
|
113 |
+
transcript=self.audio_extraction(video_input)
|
114 |
+
|
115 |
+
video = cv2.VideoCapture(video_input)
|
116 |
+
length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
117 |
+
no_of_frame = int(self.no_of_frames)
|
118 |
+
temp_div = length // no_of_frame
|
119 |
+
currentframe = 50
|
120 |
+
caption_text = []
|
121 |
+
|
122 |
+
for i in range(no_of_frame):
|
123 |
+
video.set(cv2.CAP_PROP_POS_FRAMES, currentframe)
|
124 |
+
ret, frame = video.read()
|
125 |
+
if ret:
|
126 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
127 |
+
image = Image.fromarray(frame)
|
128 |
+
content = self.img_cap.predict_image_caption_gemini(image)
|
129 |
+
print("content", content)
|
130 |
+
caption_text.append(content)
|
131 |
+
currentframe += temp_div - 1
|
132 |
+
else:
|
133 |
+
break
|
134 |
+
|
135 |
+
captions = ", ".join(caption_text)
|
136 |
+
print("CAPTIONS", captions)
|
137 |
+
video.release()
|
138 |
+
cv2.destroyAllWindows()
|
139 |
+
|
140 |
+
main_categories = Path("main_classes.txt").read_text()
|
141 |
+
main_categories_list = ['Automotive', 'Books and Literature', 'Business and Finance', 'Careers', 'Education','Family and Relationships',
|
142 |
+
'Fine Art', 'Food & Drink', 'Healthy Living', 'Hobbies & Interests', 'Home & Garden','Medical Health', 'Movies', 'Music and Audio',
|
143 |
+
'News and Politics', 'Personal Finance', 'Pets', 'Pop Culture','Real Estate', 'Religion & Spirituality', 'Science', 'Shopping', 'Sports',
|
144 |
+
'Style & Fashion','Technology & Computing', 'Television', 'Travel', 'Video Gaming']
|
145 |
+
|
146 |
+
|
147 |
+
template1 = '''Given below are the different type of main video classes
|
148 |
+
{main_categories}
|
149 |
+
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.
|
150 |
+
Give more importance to Transcript while classifying .
|
151 |
+
Transcript: {transcript}
|
152 |
+
Captions: {captions}
|
153 |
+
Return only the answer chosen from list and nothing else
|
154 |
+
Main-class => '''
|
155 |
+
|
156 |
+
prompt1 = PromptTemplate(template=template1, input_variables=['main_categories', 'transcript', 'captions'])
|
157 |
+
print("PROMPT 1",prompt1)
|
158 |
+
# print(self.model)
|
159 |
+
# print(f"Current model in use: {self.model}")
|
160 |
+
if self.model_name=='mistral':
|
161 |
+
chain1 = LLMChain(llm=self.llm, prompt=prompt1)
|
162 |
+
main_class = chain1.predict(main_categories=main_categories, transcript=transcript, captions=captions)
|
163 |
+
print(main_class)
|
164 |
+
print("#######################################################")
|
165 |
+
pattern = r"Main-class =>\s*(.+)"
|
166 |
+
match = re.search(pattern, main_class)
|
167 |
+
if match:
|
168 |
+
main_class = match.group(1).strip()
|
169 |
+
else:
|
170 |
+
main_class = None
|
171 |
+
else:
|
172 |
+
prompt_text = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
|
173 |
+
response = self.genai_model.generate_content(contents=prompt_text)
|
174 |
+
main_class = response.text
|
175 |
+
|
176 |
+
print(main_class)
|
177 |
+
print("#######################################################")
|
178 |
+
print("MAIN CLASS: ",main_class)
|
179 |
+
def category_class(class_name,categories_list):
|
180 |
+
def similar(str1, str2):
|
181 |
+
return SequenceMatcher(None, str1, str2).ratio()
|
182 |
+
index_no = 0
|
183 |
+
sim = 0
|
184 |
+
for sub in categories_list:
|
185 |
+
res = similar(class_name, sub)
|
186 |
+
if res>sim:
|
187 |
+
sim = res
|
188 |
+
index_no = categories_list.index(sub)
|
189 |
+
class_name = categories_list[index_no]
|
190 |
+
return class_name
|
191 |
+
|
192 |
+
if main_class not in main_categories_list:
|
193 |
+
main_class = category_class(main_class,main_categories_list)
|
194 |
+
print("POST PROCESSED MAIN CLASS : ",main_class)
|
195 |
+
tier_1_index_no = main_categories_list.index(main_class) + 1
|
196 |
+
|
197 |
+
with open('categories_json.txt') as f:
|
198 |
+
data = json.load(f)
|
199 |
+
sub_categories_list = data[main_class]
|
200 |
+
print("SUB CATEGORIES LIST",sub_categories_list)
|
201 |
+
with open("sub_categories.txt", "w") as f:
|
202 |
+
no = 1
|
203 |
+
|
204 |
+
# print(data[main_class])
|
205 |
+
for i in data[main_class]:
|
206 |
+
f.write(str(no)+')'+str(i) + '\n')
|
207 |
+
no = no+1
|
208 |
+
sub_categories = Path("sub_categories.txt").read_text()
|
209 |
+
|
210 |
+
template2 = '''Given below are the sub classes of {main_class}.
|
211 |
+
{sub_categories}
|
212 |
+
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 .
|
213 |
+
Give more importance to Transcript while classifying .
|
214 |
+
Transcript: {transcript}
|
215 |
+
Captions: {captions}
|
216 |
+
Return only the Sub-class answer chosen from list and nothing else
|
217 |
+
Answer in the format:
|
218 |
+
Main-class => {main_class}
|
219 |
+
Sub-class =>
|
220 |
+
'''
|
221 |
+
|
222 |
+
prompt2 = PromptTemplate(template=template2, input_variables=['sub_categories', 'transcript', 'captions','main_class'])
|
223 |
+
|
224 |
+
if self.model_name=='mistral':
|
225 |
+
chain2 = LLMChain(llm=self.llm, prompt=prompt2)
|
226 |
+
answer = chain2.predict(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
|
227 |
+
print("Preprocess Answer",answer)
|
228 |
+
|
229 |
+
|
230 |
+
pattern = r"Sub-class =>\s*(.+)"
|
231 |
+
match = re.search(pattern, answer)
|
232 |
+
if match:
|
233 |
+
sub_class = match.group(1).strip()
|
234 |
+
else:
|
235 |
+
sub_class = None
|
236 |
+
|
237 |
+
else:
|
238 |
+
prompt_text2 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
|
239 |
+
response = self.genai_model.generate_content(contents=prompt_text2)
|
240 |
+
sub_class = response.text
|
241 |
+
print("Preprocess Answer",sub_class)
|
242 |
+
|
243 |
+
print("SUB CLASS",sub_class)
|
244 |
+
if sub_class not in sub_categories_list:
|
245 |
+
sub_class = category_class(sub_class,sub_categories_list)
|
246 |
+
print("POST PROCESSED SUB CLASS",sub_class)
|
247 |
+
tier_2_index_no = sub_categories_list.index(sub_class) + 1
|
248 |
+
print("ANSWER:",sub_class)
|
249 |
+
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}")
|
250 |
+
|
251 |
+
first_video = os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")
|
252 |
+
second_video = os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4")
|
253 |
+
|
254 |
+
# return final_answer, first_video, second_video
|
255 |
+
return final_answer
|
256 |
+
|
257 |
+
|
258 |
+
def launch_interface(self):
|
259 |
+
css_code = """
|
260 |
+
.gradio-container {background-color: #000000;color:#FFFFFF;background-size: 200px; background-image:url(https://gitlab.ignitarium.in/saran/logo/-/raw/aab7c77b4816b8a4bbdc5588eb57ce8b6c15c72d/ign_logo_white.png);background-repeat:no-repeat; position:absolute; top:1px; left:5px;}
|
261 |
+
.gradio-container-4-1-2 .prose h1 {color:#FFFFFF !important }
|
262 |
+
.body {background-color: #000000 !important}
|
263 |
+
@media screen and (max-width: 1200px) {
|
264 |
+
.gradio-container-4-1-2 .prose h1 {color:#FFFFFF !important; margin-top: 6%}
|
265 |
+
}
|
266 |
+
.built-with svelte-mpyp5e {visibility:hidden}
|
267 |
+
.show-api svelte-mpyp5e {visibility:hidden}
|
268 |
+
"""
|
269 |
+
css_code += """
|
270 |
+
:root {
|
271 |
+
--body-background-fill: #000000; /* New value */
|
272 |
+
}
|
273 |
+
"""
|
274 |
+
model_dropdown = gr.inputs.Dropdown(choices=['gemini', 'mistral'], label="Select Model", default='gemini')
|
275 |
+
demo = gr.Interface(fn=self.classify_video, inputs=["playablevideo", model_dropdown],,allow_flagging='never', examples=[
|
276 |
+
os.path.join(os.path.dirname(__file__),
|
277 |
+
"American_football_heads_to_India_clip.mp4"),os.path.join(os.path.dirname(__file__), "videos/PersonalFinance_clip.mp4"),
|
278 |
+
os.path.join(os.path.dirname(__file__), "Motorcycle_clip.mp4"),
|
279 |
+
os.path.join(os.path.dirname(__file__), "Spirituality_1_clip.mp4"),
|
280 |
+
os.path.join(os.path.dirname(__file__), "Science_clip.mp4")],
|
281 |
+
cache_examples=False, outputs=["text", gr.Video(height=80, width=120), gr.Video(height=80, width=120)],
|
282 |
+
css=css_code, title="Interactive Advertising Bureau (IAB) compliant Video-Ad classification")
|
283 |
+
demo.launch(debug=True)
|
284 |
+
|
285 |
+
def run_inference(self, video_path,model):
|
286 |
+
result = self.classify_video(video_path)
|
287 |
+
print(result)
|
288 |
+
|
289 |
+
|
290 |
+
if __name__ == "__main__":
|
291 |
+
parser = argparse.ArgumentParser(description='Process some videos.')
|
292 |
+
parser.add_argument("video_path", nargs='?', default=None, help="Path to the video file")
|
293 |
+
parser.add_argument("-n", "--no_of_frames", type=int, default=8, help="Number of frames for image captioning")
|
294 |
+
parser.add_argument("--mode", choices=['interface', 'inference'], default='interface', help="Mode of operation: interface or inference")
|
295 |
+
parser.add_argument("--model", choices=['gemini','mistral'],default='gemini',help="Model for inference")
|
296 |
+
|
297 |
+
args = parser.parse_args()
|
298 |
+
|
299 |
+
vc = VideoClassifier(no_of_frames=args.no_of_frames, mode=args.mode , model=args.model)
|
300 |
+
|
301 |
+
if args.mode == 'interface':
|
302 |
+
vc.launch_interface()
|
303 |
+
elif args.mode == 'inference' and args.video_path and args.model:
|
304 |
+
vc.run_inference(args.video_path,args.model)
|
305 |
+
else:
|
306 |
+
print("Error: No video path/model provided for inference mode.")
|