File size: 16,216 Bytes
30d15db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7de3e83
30d15db
 
 
 
 
 
7de3e83
30d15db
 
 
 
7de3e83
30d15db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dcbe60
1b728eb
c63f250
 
1b728eb
 
 
 
30d15db
1b728eb
30d15db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dcbe60
1b728eb
c63f250
 
1b728eb
30d15db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b728eb
30d15db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import gradio as gr
import os
import whisper
import cv2
import json
import tempfile
import torch
import transformers
import re
import time
from torch import cuda, bfloat16
from moviepy.editor import VideoFileClip
from image_caption import Caption
from pathlib import Path
from langchain import PromptTemplate
from langchain import LLMChain
from langchain.llms import HuggingFacePipeline
from difflib import SequenceMatcher
import argparse
import shutil
from PIL import Image
import google.generativeai as genai
from huggingface_hub import InferenceClient


class VideoClassifier:
    def __init__(self, no_of_frames, mode='interface',model='gemini'):
        self.no_of_frames = no_of_frames
        self.mode = mode
        self.model_name = model.strip().lower()
        print(self.model_name)
        os.environ["TOKENIZERS_PARALLELISM"] = "false"
        if self.model_name=='mistral':
            print("Setting up Mistral model for Class Selection")
            self.setup_mistral_model()
        else :
            print("Setting up Gemini model for Class Selection")
            self.setup_gemini_model()
        self.setup_paths()
        self.hf_key = os.environ.get("HF_KEY", None)
        
    def setup_paths(self):
        self.path = './results'
        if os.path.exists(self.path):
            shutil.rmtree(self.path)  
        os.mkdir(self.path)

    def setup_gemini_model(self):
        self.genai = genai
        self.genai.configure(api_key="AIzaSyAFG94rVbm9eWepO5uPGsMha8XJ-sHbMdA")
        self.genai_model = genai.GenerativeModel('gemini-pro')
        self.whisper_model = whisper.load_model("base")
        self.img_cap = Caption()

    def setup_mistral_space_model(self):
        if not self.hf_key:
            raise ValueError("Hugging Face API key is not set or invalid.")
    
        self.client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
    
        self.whisper_model = whisper.load_model("base")
        self.img_cap = Caption()

    
    def setup_mistral_model(self):
        self.model_id = "mistralai/Mistral-7B-Instruct-v0.2"
        self.device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
        # self.device_name = torch.cuda.get_device_name()
        # print(f"Using device: {self.device} ({self.device_name})")
        bnb_config = transformers.BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type='nf4',
            bnb_4bit_use_double_quant=True,
            bnb_4bit_compute_dtype=bfloat16,
        )
        hf_auth = self.hf_key
        print(hf_auth)
        model_config = transformers.AutoConfig.from_pretrained(
            self.model_id,
            # use_auth_token=hf_auth
        )
        self.model = transformers.AutoModelForCausalLM.from_pretrained(
            self.model_id,
            trust_remote_code=True,
            config=model_config,
            quantization_config=bnb_config,
            # use_auth_token=hf_auth
        )
        self.model.eval()
        self.tokenizer = transformers.AutoTokenizer.from_pretrained(
            self.model_id,
            # use_auth_token=hf_auth
        )
        self.generate_text = transformers.pipeline(
            model=self.model, tokenizer=self.tokenizer,
            return_full_text=True,
            task='text-generation',
            temperature=0.01,
            max_new_tokens=32
        )
        self.whisper_model = whisper.load_model("base")
        self.img_cap = Caption()
        self.llm = HuggingFacePipeline(pipeline=self.generate_text)

    def audio_extraction(self,video_input):
        print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
        mp4_file = video_input
        video_name = mp4_file.split("/")[-1]
        wav_file = "results/audiotrack.wav"
        video_clip = VideoFileClip(mp4_file)
        audioclip = video_clip.audio
        wav_file = audioclip.write_audiofile(wav_file)
        audioclip.close()
        video_clip.close()
        audiotrack = "results/audiotrack.wav"
        result = self.whisper_model.transcribe(audiotrack, fp16=False)
        transcript = result["text"]
        print("TRANSCRIPT",transcript)
        return transcript
       
    def generate_text(self, inputs, parameters=None):
        if parameters is None:
            parameters = {
                "temperature": 0.7,
                "max_new_tokens": 50,
                "top_p": 0.9,
                "repetition_penalty": 1.2
            }
            
        return self.client(inputs, parameters)
    
    def classify_video(self,video_input):
    
        transcript=self.audio_extraction(video_input)

        video = cv2.VideoCapture(video_input)
        length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
        no_of_frame = int(self.no_of_frames)
        temp_div = length // no_of_frame
        currentframe = 50
        caption_text = []

        for i in range(no_of_frame):
            video.set(cv2.CAP_PROP_POS_FRAMES, currentframe)
            ret, frame = video.read()
            if ret:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                image = Image.fromarray(frame)
                content = self.img_cap.predict_image_caption_gemini(image)
                print("content", content)
                caption_text.append(content)
                currentframe += temp_div - 1
            else:
                break

        captions = ", ".join(caption_text)
        print("CAPTIONS", captions)
        video.release()
        cv2.destroyAllWindows()

        main_categories = Path("main_classes.txt").read_text()
        main_categories_list = ['Automotive', 'Books and Literature', 'Business and Finance', 'Careers', 'Education','Family and Relationships',
        'Fine Art', 'Food & Drink', 'Healthy Living', 'Hobbies & Interests', 'Home & Garden','Medical Health', 'Movies', 'Music and Audio', 
        'News and Politics', 'Personal Finance', 'Pets', 'Pop Culture','Real Estate', 'Religion & Spirituality', 'Science', 'Shopping', 'Sports', 
        'Style & Fashion','Technology & Computing', 'Television', 'Travel', 'Video Gaming']

        generate_kwargs = {
            "temperature": 0.9,
            "max_new_tokens": 256,
            "top_p": 0.95,
            "repetition_penalty": 1.0,
            "do_sample": True,
            "seed": 42,
            "return_full_text": False
        }

        template1 = '''Given below are the different type of main video classes  
        {main_categories}
        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.
        Give more importance to Transcript while classifying .
        Transcript: {transcript}
        Captions: {captions}
        Return only the answer chosen from list and nothing else
        Main-class =>  '''

        prompt1 = PromptTemplate(template=template1, input_variables=['main_categories', 'transcript', 'captions'])
        print("PROMPT 1",prompt1)
        # print(self.model)
        # print(f"Current model in use: {self.model}")
        if self.model_name=='mistral':
            try:
                chain1 = LLMChain(llm=self.llm, prompt=prompt1)
                main_class  = chain1.predict(main_categories=main_categories, transcript=transcript, captions=captions)
            except:
                prompt1 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
                messages = [{"role": "user", "content": prompt1}]
                stream = self.client.chat_completion(messages, max_tokens=100)
                main_class = stream.choices[0].message.content.strip()
                # output = ""
                # for response in stream:
                #     output += response['token'].text 
                #     print("Streaming output:", output) 
    
                # main_class = output.strip()
                
            print(main_class)
            print("#######################################################")
            pattern = r"Main-class =>\s*(.+)"
            match = re.search(pattern, main_class)
            if match:
                main_class = match.group(1).strip()
            else:
                main_class = None
        else:
            prompt_text = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
            response = self.genai_model.generate_content(contents=prompt_text)
            main_class = response.text
            
            print(main_class)
            print("#######################################################")
        print("MAIN CLASS: ",main_class)
        def category_class(class_name,categories_list):
            def similar(str1, str2):
                return SequenceMatcher(None, str1, str2).ratio()
            index_no = 0
            sim = 0
            for sub in categories_list:
                res = similar(class_name, sub)
                if res>sim:
                    sim = res
                    index_no = categories_list.index(sub)
            class_name = categories_list[index_no]
            return class_name
        
        if main_class not in main_categories_list:
            main_class = category_class(main_class,main_categories_list)
        print("POST PROCESSED MAIN CLASS : ",main_class)
        tier_1_index_no = main_categories_list.index(main_class) + 1

        with open('categories_json.txt') as f:
            data = json.load(f)
        sub_categories_list = data[main_class]
        print("SUB CATEGORIES LIST",sub_categories_list)
        with open("sub_categories.txt", "w") as f:
            no = 1
            
            # print(data[main_class])
            for i in data[main_class]:
                f.write(str(no)+')'+str(i) + '\n')
                no = no+1
        sub_categories = Path("sub_categories.txt").read_text()

        template2 = '''Given below are the sub classes of {main_class}.
        {sub_categories}
        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 .
        Give more importance to Transcript while classifying .
        Transcript: {transcript}
        Captions: {captions}
        Return only the Sub-class answer chosen from list and nothing else
        Answer in the format:
        Main-class => {main_class}
        Sub-class => 
         '''
        
        prompt2 = PromptTemplate(template=template2, input_variables=['sub_categories', 'transcript', 'captions','main_class'])
        
        if self.model_name=='mistral':
            try:
                chain2 = LLMChain(llm=self.llm, prompt=prompt2)
                answer = chain2.predict(sub_categories=sub_categories, transcript=transcript, captions=captions,main_class=main_class)
            except:
                prompt2 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
                messages = [{"role": "user", "content": prompt1}]
                stream = self.client.chat_completion(messages, max_tokens=100)
                answer = stream.choices[0].message.content.strip()
                
            print("Preprocess Answer",answer)

            
            pattern = r"Sub-class =>\s*(.+)"
            match = re.search(pattern, answer)
            if match:
                sub_class = match.group(1).strip()
            else:
                sub_class = None
            
        else:
            prompt_text2 = template1.format(main_categories=main_categories, transcript=transcript, captions=captions)
            response = self.genai_model.generate_content(contents=prompt_text2)
            sub_class = response.text
            print("Preprocess Answer",sub_class)
        
        print("SUB CLASS",sub_class)
        if sub_class not in sub_categories_list:
            sub_class = category_class(sub_class,sub_categories_list)
            print("POST PROCESSED SUB CLASS",sub_class)
        tier_2_index_no = sub_categories_list.index(sub_class) + 1
        print("ANSWER:",sub_class)
        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}")

        first_video = os.path.join(os.path.dirname(__file__), "American_football_heads_to_India_clip.mp4")
        second_video = os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4")

        # return final_answer, first_video, second_video
        return final_answer
    
    def save_model_choice(self,model_name):
        self.model_name = model_name
        if self.model_name=='mistral':
            print("Setting up Mistral model for Class Selection")
            self.setup_mistral_space_model()
        else :
            print("Setting up Gemini model for Class Selection")
            self.setup_gemini_model()
        return "Model selected: " + model_name

    def launch_interface(self):
        css_code = """
        .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;}
        """
        css_code += """
        :root {
        --body-background-fill: #FFFFFF; /* New value */
        }
        """
        css_code += """
        :root {
        --body-background-fill: #000000; /* New value */
        }
        """

        interface_1 = gr.Interface(
        self.save_model_choice,
        inputs=gr.Dropdown(choices=['gemini', 'mistral'], label="Select Model", info="Default model: Gemini"),
        # outputs=interface_1_output,
        outputs="text"
        
    )


        demo = gr.Interface(fn=self.classify_video, inputs="playablevideo",allow_flagging='never', examples=[
                            os.path.join(os.path.dirname(__file__), 
                                         "American_football_heads_to_India_clip.mp4"),os.path.join(os.path.dirname(__file__), "PersonalFinance_clip.mp4"),
                                         os.path.join(os.path.dirname(__file__), "Motorcycle_clip.mp4"),
                                         os.path.join(os.path.dirname(__file__), "Spirituality_1_clip.mp4"),
                                         os.path.join(os.path.dirname(__file__), "Science_clip.mp4")], 
                        cache_examples=False, outputs=["text"],
                        css=css_code, title="Interactive Advertising Bureau (IAB) compliant Video-Ad classification")
        # demo.launch(debug=True)

        gr.TabbedInterface([interface_1, demo], ["Model Selection", "Video Classification"]).launch(debug=True)

    def run_inference(self, video_path,model):
        result = self.classify_video(video_path)
        print(result)
    

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Process some videos.')
    parser.add_argument("video_path", nargs='?', default=None, help="Path to the video file")
    parser.add_argument("-n", "--no_of_frames", type=int, default=3, help="Number of frames for image captioning")
    parser.add_argument("--mode", choices=['interface', 'inference'], default='interface', help="Mode of operation: interface or inference")
    parser.add_argument("--model", choices=['gemini','mistral'],default='gemini',help="Model for inference")
    
    args = parser.parse_args()

    vc = VideoClassifier(no_of_frames=args.no_of_frames, mode=args.mode , model=args.model)
    
    if args.mode == 'interface':
        vc.launch_interface()
    elif args.mode == 'inference' and args.video_path and args.model:
        vc.run_inference(args.video_path,args.model)
    else:
        print("Error: No video path/model provided for inference mode.")

#Usage
### python main.py --mode interface
### python main.py videos/Spirituality_1_clip.mp4 -n 3 --mode inference --model gemini