arjunanand13 commited on
Commit
30d15db
1 Parent(s): 195077e

Create app3.py

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