arjunanand13 commited on
Commit
0068e69
·
verified ·
1 Parent(s): f6de084

Create app.py

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