File size: 13,176 Bytes
7fd6e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import whisper
import cv2
import io
from PIL import Image
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
import google.generativeai as genai

class VideoClassifier:
    def __init__(self, no_of_frames, mode='interface'):
        self.no_of_frames = no_of_frames
        self.mode = mode
        os.environ["TOKENIZERS_PARALLELISM"] = "false"
        # self.setup_model()
        self.setup_paths()
        self.setup_gemini_model()
        
    def setup_paths(self):
        self.path = './results'
        if os.path.exists(self.path):
            shutil.rmtree(self.path)  # Remove the directory if it exists
        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_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 = hf_key
        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,
            device_map='auto',
            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 classify_video(self, video_input):
        print(f"Processing video: {video_input} with {self.no_of_frames} frames.")
        start = time.time()
        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)
        # print("####transcript length:", len(transcript))
        end = time.time()
        time_taken_1 = round(end - start, 3)
        # print("Time taken from video to transcript:", time_taken_1)

        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)
                # img_byte_arr = io.BytesIO()
                # image.save(img_byte_arr, format='JPEG')  # Save as JPEG or any other format your model supports
                # img_byte_arr.seek(0)
                
                content = self.img_cap.predict_image_caption_gemini(image)
                print("content", content)
                caption_text.append(content[0])
                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']


        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)
        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("#######################################################")
        # pattern = r"Main-class =>\s*(.+)"
        # match = re.search(pattern, main_class)
        # if match:
        #     main_class = match.group(1).strip()
        # else:
        #     main_class = None
        # 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'])
        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("Time taken by model to predict:", time_taken_predict)
        # print("Total time taken:", time_taken_total)
        

        # pattern = r"Sub-class =>\s*(.+)"
        # match = re.search(pattern, sub_class)
        # if match:
        #     sub_class = match.group(1).strip()
        # else:
        #     sub_class = None
        # 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


        # .gradio-container-4-1-2 .prose h1 {color:#FFFFFF !important }
        # .body {background-color: #000000 !important}
        # @media screen and (max-width: 1500px) {
        # .gradio-container-4-1-2 .prose h1 {color:#FFFFFF !important; margin-top: 6%}
        # }
        # .built-with svelte-mpyp5e {visibility:hidden}
        # .show-api svelte-mpyp5e {visibility:hidden}
    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 */
        }
        """

        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", gr.Video(height=80, width=120), gr.Video(height=80, width=120)],
                        outputs=["text"],
                        css=css_code, 
                        title="Interactive Advertising Bureau (IAB) compliant Video-Ad classification"
                        )
        demo.launch(debug=True)
    

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

if __name__ == "__main__":

    vc = VideoClassifier(no_of_frames=3, mode='interface')
    vc.launch_interface()
    
    # 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=8, help="Number of frames for image captioning")
    # parser.add_argument("--mode", choices=['interface', 'inference'], default='interface', help="Mode of operation: interface or inference")
    
    # args = parser.parse_args()

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

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