arjunanand13's picture
Rename app.py to app2.py
09f8081 verified
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