arjunanand13 commited on
Commit
19fd223
1 Parent(s): 2b21093

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +379 -0
app.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from huggingface_hub import InferenceClient
24
+
25
+
26
+ class VideoClassifier:
27
+ def __init__(self, no_of_frames, mode='interface',model='gemini'):
28
+ self.no_of_frames = no_of_frames
29
+ self.mode = mode
30
+ self.model_name = model.strip().lower()
31
+ print(self.model_name)
32
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
33
+ if self.model_name=='mistral':
34
+ print("Setting up Mistral model for Class Selection")
35
+ self.setup_mistral_model()
36
+ else :
37
+ print("Setting up Gemini model for Class Selection")
38
+ self.setup_gemini_model()
39
+ self.setup_paths()
40
+ self.hf_key = os.environ.get("HF_KEY", None)
41
+ # self.whisper_model = whisper.load_model("base")
42
+
43
+ def setup_paths(self):
44
+ self.path = './results'
45
+ if os.path.exists(self.path):
46
+ shutil.rmtree(self.path)
47
+ os.mkdir(self.path)
48
+
49
+ def setup_gemini_model(self):
50
+ self.genai = genai
51
+ self.genai.configure(api_key="AIzaSyAFG94rVbm9eWepO5uPGsMha8XJ-sHbMdA")
52
+ self.genai_model = genai.GenerativeModel('gemini-pro')
53
+ self.whisper_model = whisper.load_model("base")
54
+ self.img_cap = Caption()
55
+
56
+ def setup_mistral_space_model(self):
57
+ # if not self.hf_key:
58
+ # raise ValueError("Hugging Face API key is not set or invalid.")
59
+
60
+ self.client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
61
+
62
+ self.whisper_model = whisper.load_model("base")
63
+ self.img_cap = Caption()
64
+
65
+
66
+ def setup_mistral_model(self):
67
+ self.model_id = "mistralai/Mistral-7B-Instruct-v0.2"
68
+ self.device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
69
+ # self.device_name = torch.cuda.get_device_name()
70
+ # print(f"Using device: {self.device} ({self.device_name})")
71
+ bnb_config = transformers.BitsAndBytesConfig(
72
+ load_in_4bit=True,
73
+ bnb_4bit_quant_type='nf4',
74
+ bnb_4bit_use_double_quant=True,
75
+ bnb_4bit_compute_dtype=bfloat16,
76
+ )
77
+ hf_auth = self.hf_key
78
+ print(hf_auth)
79
+ model_config = transformers.AutoConfig.from_pretrained(
80
+ self.model_id,
81
+ # use_auth_token=hf_auth
82
+ )
83
+ self.model = transformers.AutoModelForCausalLM.from_pretrained(
84
+ self.model_id,
85
+ trust_remote_code=True,
86
+ config=model_config,
87
+ quantization_config=bnb_config,
88
+ # use_auth_token=hf_auth
89
+ )
90
+ self.model.eval()
91
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
92
+ self.model_id,
93
+ # use_auth_token=hf_auth
94
+ )
95
+ self.generate_text = transformers.pipeline(
96
+ model=self.model, tokenizer=self.tokenizer,
97
+ return_full_text=True,
98
+ task='text-generation',
99
+ temperature=0.01,
100
+ max_new_tokens=32
101
+ )
102
+ self.whisper_model = whisper.load_model("base")
103
+ self.img_cap = Caption()
104
+ self.llm = HuggingFacePipeline(pipeline=self.generate_text)
105
+
106
+ def audio_extraction(self,video_input):
107
+ print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
108
+ mp4_file = video_input
109
+ video_name = mp4_file.split("/")[-1]
110
+ wav_file = "results/audiotrack.wav"
111
+ video_clip = VideoFileClip(mp4_file)
112
+ audioclip = video_clip.audio
113
+ wav_file = audioclip.write_audiofile(wav_file)
114
+ audioclip.close()
115
+ video_clip.close()
116
+ audiotrack = "results/audiotrack.wav"
117
+ result = self.whisper_model.transcribe(audiotrack, fp16=False)
118
+ transcript = result["text"]
119
+ print("TRANSCRIPT",transcript)
120
+ return transcript
121
+
122
+ def generate_text(self, inputs, parameters=None):
123
+ if parameters is None:
124
+ parameters = {
125
+ "temperature": 0.7,
126
+ "max_new_tokens": 50,
127
+ "top_p": 0.9,
128
+ "repetition_penalty": 1.2
129
+ }
130
+
131
+ return self.client(inputs, parameters)
132
+
133
+ def classify_video(self,video_input):
134
+
135
+ transcript=self.audio_extraction(video_input)
136
+
137
+ video = cv2.VideoCapture(video_input)
138
+ length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
139
+ no_of_frame = int(self.no_of_frames)
140
+ temp_div = length // no_of_frame
141
+ currentframe = 50
142
+ caption_text = []
143
+
144
+ for i in range(no_of_frame):
145
+ video.set(cv2.CAP_PROP_POS_FRAMES, currentframe)
146
+ ret, frame = video.read()
147
+ if ret:
148
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
149
+ image = Image.fromarray(frame)
150
+ content = self.img_cap.predict_image_caption_gemini(image)
151
+ print("content", content)
152
+ caption_text.append(content)
153
+ currentframe += temp_div - 1
154
+ else:
155
+ break
156
+
157
+ captions = ", ".join(caption_text)
158
+ print("CAPTIONS", captions)
159
+ video.release()
160
+ cv2.destroyAllWindows()
161
+
162
+ main_categories = Path("main_classes.txt").read_text()
163
+ main_categories_list = ['Automotive', 'Books and Literature', 'Business and Finance', 'Careers', 'Education','Family and Relationships',
164
+ 'Fine Art', 'Food & Drink', 'Healthy Living', 'Hobbies & Interests', 'Home & Garden','Medical Health', 'Movies', 'Music and Audio',
165
+ 'News and Politics', 'Personal Finance', 'Pets', 'Pop Culture','Real Estate', 'Religion & Spirituality', 'Science', 'Shopping', 'Sports',
166
+ 'Style & Fashion','Technology & Computing', 'Television', 'Travel', 'Video Gaming']
167
+
168
+ generate_kwargs = {
169
+ "temperature": 0.9,
170
+ "max_new_tokens": 256,
171
+ "top_p": 0.95,
172
+ "repetition_penalty": 1.0,
173
+ "do_sample": True,
174
+ "seed": 42,
175
+ "return_full_text": False
176
+ }
177
+
178
+ template1 = '''Given below are the different type of main video classes
179
+ {main_categories}
180
+ 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.
181
+ Give more importance to Transcript while classifying .
182
+ Transcript: {transcript}
183
+ Captions: {captions}
184
+ Return only the answer chosen from list and nothing else
185
+ Main-class => '''
186
+
187
+ prompt1 = PromptTemplate(template=template1, input_variables=['main_categories', 'transcript', 'captions'])
188
+ print("PROMPT 1",prompt1)
189
+ # print(self.model)
190
+ # print(f"Current model in use: {self.model}")
191
+ if self.model_name=='mistral':
192
+ try:
193
+ chain1 = LLMChain(llm=self.llm, prompt=prompt1)
194
+ main_class = chain1.predict(main_categories=main_categories, transcript=transcript, captions=captions)
195
+ except:
196
+ prompt1 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
197
+ messages = [{"role": "user", "content": prompt1}]
198
+ stream = self.client.chat_completion(messages, max_tokens=100)
199
+ main_class = stream.choices[0].message.content.strip()
200
+ # output = ""
201
+ # for response in stream:
202
+ # output += response['token'].text
203
+ # print("Streaming output:", output)
204
+
205
+ # main_class = output.strip()
206
+
207
+ print(main_class)
208
+ print("#######################################################")
209
+ try:
210
+ pattern = r"Main-class =>\s*(.+)"
211
+ match = re.search(pattern, main_class)
212
+ if match:
213
+ main_class = match.group(1).strip()
214
+ except:
215
+ main_class=main_class
216
+ else:
217
+ prompt_text = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
218
+ response = self.genai_model.generate_content(contents=prompt_text)
219
+ main_class = response.text
220
+
221
+ print(main_class)
222
+ print("#######################################################")
223
+ print("MAIN CLASS: ",main_class)
224
+ def category_class(class_name,categories_list):
225
+ def similar(str1, str2):
226
+ return SequenceMatcher(None, str1, str2).ratio()
227
+ index_no = 0
228
+ sim = 0
229
+ for sub in categories_list:
230
+ res = similar(class_name, sub)
231
+ if res>sim:
232
+ sim = res
233
+ index_no = categories_list.index(sub)
234
+ class_name = categories_list[index_no]
235
+ return class_name
236
+
237
+ if main_class not in main_categories_list:
238
+ main_class = category_class(main_class,main_categories_list)
239
+ print("POST PROCESSED MAIN CLASS : ",main_class)
240
+ tier_1_index_no = main_categories_list.index(main_class) + 1
241
+
242
+ with open('categories_json.txt') as f:
243
+ data = json.load(f)
244
+ sub_categories_list = data[main_class]
245
+ print("SUB CATEGORIES LIST",sub_categories_list)
246
+ with open("sub_categories.txt", "w") as f:
247
+ no = 1
248
+
249
+ # print(data[main_class])
250
+ for i in data[main_class]:
251
+ f.write(str(no)+')'+str(i) + '\n')
252
+ no = no+1
253
+ sub_categories = Path("sub_categories.txt").read_text()
254
+
255
+ template2 = '''Given below are the sub classes of {main_class}.
256
+ {sub_categories}
257
+ 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 .
258
+ Give more importance to Transcript while classifying .
259
+ Transcript: {transcript}
260
+ Captions: {captions}
261
+ Return only the Sub-class answer chosen from list and nothing else
262
+ Answer in the format:
263
+ Main-class => {main_class}
264
+ Sub-class =>
265
+ '''
266
+
267
+ prompt2 = PromptTemplate(template=template2, input_variables=['sub_categories', 'transcript', 'captions','main_class'])
268
+
269
+ if self.model_name=='mistral':
270
+ try:
271
+ chain2 = LLMChain(llm=self.llm, prompt=prompt2)
272
+ sub_class = chain2.predict(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
273
+ except:
274
+ prompt2 = template2.format(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
275
+ messages = [{"role": "user", "content": prompt2}]
276
+ stream = self.client.chat_completion(messages, max_tokens=100)
277
+ sub_class = stream.choices[0].message.content.strip()
278
+
279
+ print("Preprocess Answer",sub_class)
280
+
281
+ try:
282
+ pattern = r"Sub-class =>\s*(.+)"
283
+ match = re.search(pattern, sub_class)
284
+ if match:
285
+ sub_class = match.group(1).strip()
286
+ except:
287
+ subclass=sub_class
288
+ else:
289
+ prompt_text2 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
290
+ response = self.genai_model.generate_content(contents=prompt_text2)
291
+ sub_class = response.text
292
+ print("Preprocess Answer",sub_class)
293
+
294
+ print("SUB CLASS",sub_class)
295
+ if sub_class not in sub_categories_list:
296
+ sub_class = category_class(sub_class,sub_categories_list)
297
+ print("POST PROCESSED SUB CLASS",sub_class)
298
+ tier_2_index_no = sub_categories_list.index(sub_class) + 1
299
+ print("ANSWER:",sub_class)
300
+ 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}")
301
+
302
+ first_video = os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")
303
+ second_video = os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4")
304
+
305
+ # return final_answer, first_video, second_video
306
+ return final_answer
307
+
308
+ def save_model_choice(self,model_name):
309
+ self.model_name = model_name
310
+ if self.model_name=='mistral':
311
+ print("Setting up Mistral model for Class Selection")
312
+ self.setup_mistral_space_model()
313
+ else :
314
+ print("Setting up Gemini model for Class Selection")
315
+ self.setup_gemini_model()
316
+ return "Model selected: " + model_name
317
+
318
+ def launch_interface(self):
319
+ css_code = """
320
+ .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;}
321
+ """
322
+ css_code += """
323
+ :root {
324
+ --body-background-fill: #FFFFFF; /* New value */
325
+ }
326
+ """
327
+ css_code += """
328
+ :root {
329
+ --body-background-fill: #000000; /* New value */
330
+ }
331
+ """
332
+
333
+ interface_1 = gr.Interface(
334
+ self.save_model_choice,
335
+ inputs=gr.Dropdown(choices=['gemini', 'mistral'], label="Select Model", info="Default model: Gemini"),
336
+ # outputs=interface_1_output,
337
+ outputs="text"
338
+
339
+ )
340
+
341
+
342
+ demo = gr.Interface(fn=self.classify_video, inputs="playablevideo",allow_flagging='never', examples=[
343
+ os.path.join(os.path.dirname(__file__),
344
+ "American_football_heads_to_India_clip.mp4"),os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4"),
345
+ os.path.join(os.path.dirname(__file__), "Motorcycle_clip.mp4"),
346
+ os.path.join(os.path.dirname(__file__), "Spirituality_1_clip.mp4"),
347
+ os.path.join(os.path.dirname(__file__), "Science_clip.mp4")],
348
+ cache_examples=False, outputs=["text"],
349
+ css=css_code, title="Interactive Advertising Bureau (IAB) compliant Video-Ad classification")
350
+ # demo.launch(debug=True)
351
+
352
+ gr.TabbedInterface([interface_1, demo], ["Model Selection", "Video Classification"]).launch(debug=True)
353
+
354
+ def run_inference(self, video_path,model):
355
+ result = self.classify_video(video_path)
356
+ print(result)
357
+
358
+
359
+ if __name__ == "__main__":
360
+ parser = argparse.ArgumentParser(description='Process some videos.')
361
+ parser.add_argument("video_path", nargs='?', default=None, help="Path to the video file")
362
+ parser.add_argument("-n", "--no_of_frames", type=int, default=3, help="Number of frames for image captioning")
363
+ parser.add_argument("--mode", choices=['interface', 'inference'], default='interface', help="Mode of operation: interface or inference")
364
+ parser.add_argument("--model", choices=['gemini','mistral'],default='gemini',help="Model for inference")
365
+
366
+ args = parser.parse_args()
367
+
368
+ vc = VideoClassifier(no_of_frames=args.no_of_frames, mode=args.mode , model=args.model)
369
+
370
+ if args.mode == 'interface':
371
+ vc.launch_interface()
372
+ elif args.mode == 'inference' and args.video_path and args.model:
373
+ vc.run_inference(args.video_path,args.model)
374
+ else:
375
+ print("Error: No video path/model provided for inference mode.")
376
+
377
+ #Usage
378
+ ### python main.py --mode interface
379
+ ### python main.py videos/Spirituality_1_clip.mp4 -n 3 --mode inference --model gemini