arjunanand13 commited on
Commit
1c36332
·
verified ·
1 Parent(s): e71f575

Create app.py

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