Explain the code 
import os
import magic
import time
import requests
import random
from threading import Thread
from typing import List, Dict, Union
import subprocess
subprocess.run(
    "pip install flash-attn --no-build-isolation",
    env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
    shell=True,
)
import torch
import gradio as gr
from bs4 import BeautifulSoup
from transformers import LlavaProcessor, LlavaForConditionalGeneration, TextIteratorStreamer
from huggingface_hub import InferenceClient
from PIL import Image, UnidentifiedImageError
import spaces
from functools import lru_cache
import cv2
import re
import io 
import json
from gradio_client import Client, file
from groq import Groq
import asyncio
import aiohttp

# You can also use models that are commented below
# model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"
model_id = "llava-hf/llava-interleave-qwen-7b-hf"
# model_id = "llava-hf/llava-interleave-qwen-7b-dpo-hf"
processor = LlavaProcessor.from_pretrained(model_id)
model = LlavaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16, use_flash_attention_2=True)
model.to("cuda")
# Credit to merve for code of llava interleave qwen

GROQ_API_KEY = os.environ.get("GROQ_API_KEY", None)

client_groq = Groq(api_key=GROQ_API_KEY)

def sample_frames(video_file) :
    try:
        video = cv2.VideoCapture(video_file)
        total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
        num_frames = 12
        interval = total_frames // num_frames
        frames = []
        for i in range(total_frames):
            ret, frame = video.read()
            pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            if not ret:
                continue
            if i % interval == 0:
                frames.append(pil_img)
        video.release()
        return frames
    except:
        frames=[]
        return frames
        

# Path to example images
examples_path = os.path.dirname(__file__)
EXAMPLES = [
    [
        {
            "text": "How much subscribers Ronaldo have in YouTube",
        }
    ],
    [
        {
            "text": "Develop a Python program to check if a string is a palindrome.",
        }
    ],
    [
        {
            "text": "What's the latest price of Bitcoin?",
        }
    ],
    [
        {
            "text": "Search and give me list of spaces trending on HuggingFace.",
        }
    ],
    [
        {
            "text": "Provide me with the latest football news and updates.",
        }
    ],
    [
        {
            "text": "Show me the most recent movies and TV series available.",
        }
    ],
    
]

# Set bot avatar image
BOT_AVATAR = "OpenAI_logo.png"

# Perform a Google search and return the results
@lru_cache(maxsize=128) 
def extract_text_from_webpage(html_content):
    """Extracts visible text from HTML content using BeautifulSoup."""
    soup = BeautifulSoup(html_content, "html.parser")
    for tag in soup(["script", "style", "header", "footer", "nav", "form", "svg"]):
        tag.extract()
    visible_text = soup.get_text(strip=True)
    return visible_text

# Perform a Google search and return the results
def search(query):
    term = query
    start = 0
    all_results = []
    max_chars_per_page = 8000
    with requests.Session() as session:
        resp = session.get(
            url="https://www.google.com/search",
            headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
            params={"q": term, "num": 4, "udm": 14},
            timeout=5,
            verify=None,
        )
        resp.raise_for_status()
        soup = BeautifulSoup(resp.text, "html.parser")
        result_block = soup.find_all("div", attrs={"class": "g"})
        for result in result_block:
            link = result.find("a", href=True)
            link = link["href"]
            try:
                webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, timeout=5, verify=False)
                webpage.raise_for_status()
                visible_text = extract_text_from_webpage(webpage.text)
                if len(visible_text) > max_chars_per_page:
                    visible_text = visible_text[:max_chars_per_page]
                all_results.append({"link": link, "text": visible_text})
            except requests.exceptions.RequestException:
                all_results.append({"link": link, "text": None})
    return all_results


def image_gen(prompt):
    try:
        client = Client("KingNish/Image-Gen-Pro")
        # Perform the API call
        response = client.predict("Image Generation", None, prompt, api_name="/image_gen_pro")
        
        # Log the response for debugging
        print("API Response:", response)
        
        # Check if the response is None or empty
        if not response:
            print("No response received from the API.")
            return None
            
        return response

    except Exception as e:
        print(f"Error occurred during image generation: {e}")
        return None

def generate_image(prompt):
    # Call the image generation function
    response = image_gen(prompt)
    
    # Log the response for debugging
    print("Generated Image Response:", response)
    
    # Return the response or handle it accordingly
    if response:
        return response
    else:
        print("Failed to generate the image.")
        return "Failed to generate the image."
        
def chatbot_function(user_prompt, chat_history):
    # If the user is asking for an image, use the new image generation function
    if "generate an image" in user_prompt.lower():
        prompt = user_prompt.split("generate an image of ")[1]
        image = generate_image(prompt)
        return chat_history, gr.Image(image)
    else:
        # If the user is not asking for an image, use the original chatbot function
        inputs = llava(user_prompt, chat_history)
        streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
        generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048, pad_token_id=model.config.eos_token_id)
        thread = Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()
        buffer = ""
        for new_text in streamer:
            buffer += new_text
            yield buffer

        
def video_gen(prompt):
    client = Client("KingNish/Instant-Video")
    return client.predict(prompt, api_name="/instant_video")

def llava(user_prompt, chat_history):
    image = None
    inputs = None  # Initialize inputs to None

    # Accessing the files and text from MultimodalData object
    if hasattr(user_prompt, "files") and user_prompt.files:
        image = user_prompt.files[0]  # Assuming this is a FileData object
    else:
        for hist in chat_history:
            if isinstance(hist[0], tuple):
                image = hist[0][0]

    txt = user_prompt.text if hasattr(user_prompt, "text") else ""

    video_extensions = (".avi", ".mp4", ".mov", ".mkv", ".flv", ".wmv", ".mjpeg", ".wav", ".webm", ".m4v", ".3gp")
    image_extensions = tuple(f".{ext.strip('.')}" for ext in Image.registered_extensions().keys())

    prompt = f"user {txt}\nassistant"  # Default prompt without image/video

    if image:
        try:
            # Check if `image` is a FileData object with raw bytes
            if hasattr(image, 'data'):  # Assuming `image.data` contains the raw image bytes
                image_bytes = image.data
                image = Image.open(BytesIO(image_bytes)).convert("RGB")
                gr.Info("Analyzing image")
                prompt = f"user <image>\n{txt}\nassistant"
            elif hasattr(image, 'path'):
                file_ext = os.path.splitext(image.path)[1].lower()
                if file_ext in video_extensions:
                    image = sample_frames(image)  # Assuming sample_frames processes the video file
                    gr.Info("Analyzing Video")
                    image_tokens = "<image>" * len(image)
                    prompt = f"user {image_tokens}\n{txt}\nassistant"
                elif file_ext in image_extensions:
                    image = Image.open(image.path).convert("RGB")
                    gr.Info("Analyzing image")
                    prompt = f"user <image>\n{txt}\nassistant"
            else:
                print("Unsupported image type.")
        except UnidentifiedImageError:
            print("Error: Image could not be identified.")
            image = None
        except Exception as e:
            print(f"Error processing image: {e}")
            image = None

    system_llava = ("system\nYou are RocketGPT, an exceptionally capable and versatile AI assistant. "
                    "Your task is to fulfill users' queries in the best possible way. You are provided with images, "
                    "videos, and 3D structures as input along with questions. Your task is to give the best possible, "
                    "detailed results to the user according to their query. Reply to the question asked by the user "
                    "properly and in the best possible way.")
    
    final_prompt = f"{system_llava}\n{prompt}"

    if image:
        try:
            inputs = processor(final_prompt, [image], return_tensors="pt").to("cuda", torch.float16)
        except Exception as e:
            print(f"Error processing input for the model: {e}")
            inputs = None
    else:
        print("No image found.")

    if inputs is None:
        return None  # Handle the case where inputs could not be processed
    
    return inputs

def model_inference(inputs, streamer):
    if inputs is None:
        print("No valid inputs to process.")
        return
    
# Initialize inference clients for different models
client_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
client_mistral_nemo = InferenceClient("mistralai/Mistral-Nemo-Instruct-2407")

@spaces.GPU(duration=60, queue=False)
def model_inference(user_prompt, chat_history):
    # Check if `user_prompt` has a `files` attribute and it contains files
    if hasattr(user_prompt, "files") and user_prompt.files:
        # Prepare the inputs using `llava` function
        inputs = llava(user_prompt, chat_history)
        
        # Setup the text streamer for generation
        streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
        
        # Define generation arguments
        generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048, pad_token_id=model.config.eos_token_id)
        
        # Start the text generation in a separate thread
        thread = Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()
        
        buffer = ""
        # Stream the generated text and yield it
        for new_text in streamer:
            buffer += new_text
            yield buffer


    else: 
        func_caller = []
        message = user_prompt

        functions_metadata = [
            {"type": "function", "function": {"name": "web_search", "description": "Search query on google and find latest information, info about any person, object, place thing, everything that available on google.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
            {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER, with LLM like you. But it does not answer tough questions and latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
            {"type": "function", "function": {"name": "hard_query", "description": "Reply tough query of USER, using powerful LLM. But it does not answer latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
            {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
            {"type": "function", "function": {"name": "video_generation", "description": "Generate video for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "video generation prompt"}}, "required": ["query"]}}},
            {"type": "function", "function": {"name": "image_qna", "description": "Answer question asked by user related to image", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Question by user"}}, "required": ["query"]}}},
        ]

        for msg in chat_history:
            func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
            func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})

        message_text = message.text
        func_caller.append({"role": "user", "content": f'[SYSTEM]You are a helpful assistant. You have access to the following functions: \n {str(functions_metadata)}\n\nTo use these functions respond with:\n<functioncall> {{ "name": "function_name", "arguments": {{ "arg_1": "value_1", "arg_1": "value_1", ... }} }}  </functioncall> , Reply in JSOn format, you can call only one function at a time, So, choose functions wisely. [USER] {message_text}'})
    
        response = client_mistral.chat_completion(func_caller, max_tokens=200)
        response = str(response)
        try:
            response = response[response.find("{"):response.index("</")]
        except:
            response = response[response.find("{"):(response.rfind("}")+1)]
        response = response.replace("\\n", "")
        response = response.replace("\\'", "'")
        response = response.replace('\\"', '"')
        response = response.replace('\\', '')
        print(f"\n{response}")
    
        try:
            json_data = json.loads(str(response))
            if json_data["name"] == "web_search":
                query = json_data["arguments"]["query"]

                gr.Info("Searching Web")
                yield "Searching Web"
                web_results = search(query)
                
                gr.Info("Extracting relevant Info")
                yield "Extracting Relevant Info"
                web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])

                try:
                    message_groq = []
                    message_groq.append({"role":"system", "content": "You are RocketGPT a helpful and very powerful web assistant. You are provided with WEB results from which you can find informations to answer users query in Structured, Detailed and Better way, in Human Style. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You reply in detail like human, use short forms, structured format, friendly tone and emotions."})
                    for msg in chat_history:
                        message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                        message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                    message_groq.append({"role": "user", "content": f"[USER] {str(message_text)} ,  [WEB RESULTS] {str(web2)}"})
                    # its meta-llama/Meta-Llama-3.1-8B-Instruct
                    stream = client_groq.chat.completions.create(model="llama-3.1-8b-instant",  messages=message_groq, max_tokens=4096, stream=True)
                    output = ""
                    for chunk in stream:
                        content = chunk.choices[0].delta.content
                        if content:
                            output += chunk.choices[0].delta.content 
                            yield output
                except Exception as e:
                    messages = f"
system\nYou are RocketGPT a helpful and very powerful chatbot web assistant. You are provided with WEB results from which you can find informations to answer users query in Structured, Better and in Human Way. You do not say Unnecesarry things. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply in details like human, use short forms, friendly tone and emotions.
"
                    for msg in chat_history:
                        messages += f"\n
user\n{str(msg[0])}
"
                        messages += f"\n
assistant\n{str(msg[1])}
"
                    messages+=f"\n
user\n{message_text}
\n
web_result\n{web2}
\n
assistant\n"
                    
                    stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
                    output = ""
                    for response in stream:
                        if not response.token.text == "
":
                            output += response.token.text
                            yield output
            
            elif json_data["name"] == "image_generation":
                query = json_data["arguments"]["query"]
                gr.Info("Generating Image, Please wait 10 sec...")
                yield "Generating Image, Please wait 10 sec..."
                try:
                    image = image_gen(f"{str(query)}")
                    yield gr.Image(image[1])
                except:
                    client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
                    seed = random.randint(0,999999)
                    image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
                    yield gr.Image(image)
                    

            elif json_data["name"] == "video_generation":
                query = json_data["arguments"]["query"]
                gr.Info("Generating Video, Please wait 15 sec...")
                yield "Generating Video, Please wait 15 sec..."
                video = video_gen(f"{str(query)}")
                yield gr.Video(video)
                
            elif json_data["name"] == "image_qna":
                inputs = llava(user_prompt, chat_history)
                streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
                generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)

                thread = Thread(target=model.generate, kwargs=generation_kwargs)
                thread.start()
    
                buffer = ""
                for new_text in streamer:
                    buffer += new_text
                    yield buffer

            else:
                try:
                    message_groq = []
                    message_groq.append({"role":"system", "content": "You are RocketGPT a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
                    for msg in chat_history:
                        message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                        message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                    message_groq.append({"role": "user", "content": f"{str(message_text)}"})
                    # its meta-llama/Meta-Llama-3.1-70B-Instruct
                    stream = client_groq.chat.completions.create(model="llama-3.1-70b-versatile",  messages=message_groq, max_tokens=4096, stream=True)
                    output = ""
                    for chunk in stream:
                        content = chunk.choices[0].delta.content
                        if content:
                            output += chunk.choices[0].delta.content 
                            yield output
                except Exception as e:
                    print(e)
                    try:
                        message_groq = []
                        message_groq.append({"role":"system", "content": "You are RocketGPT a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
                        for msg in chat_history:
                            message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                            message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                        message_groq.append({"role": "user", "content": f"{str(message_text)}"})
                        # its meta-llama/Meta-Llama-3-70B-Instruct
                        stream = client_groq.chat.completions.create(model="llama3-70b-8192",  messages=message_groq, max_tokens=4096, stream=True)
                        output = ""
                        for chunk in stream:
                            content = chunk.choices[0].delta.content
                            if content:
                                output += chunk.choices[0].delta.content 
                                yield output
                    except Exception as e:
                        print(e)
                        message_groq = []
                        message_groq.append({"role":"system", "content": "You are RocketGPT a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
                        for msg in chat_history:
                            message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                            message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                        message_groq.append({"role": "user", "content": f"{str(message_text)}"})
                        stream = client_groq.chat.completions.create(model="llama3-groq-70b-8192-tool-use-preview",  messages=message_groq, max_tokens=4096, stream=True)
                        output = ""
                        for chunk in stream:
                            content = chunk.choices[0].delta.content
                            if content:
                                output += chunk.choices[0].delta.content 
                                yield output
        except Exception as e:
            print(e)
            try:
                message_groq = []
                message_groq.append({"role":"system", "content": "You are a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
                for msg in chat_history:
                    message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                    message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                message_groq.append({"role": "user", "content": f"{str(message_text)}"})
                # its meta-llama/Meta-Llama-3-70B-Instruct
                stream = client_groq.chat.completions.create(model="llama3-70b-8192",  messages=message_groq, max_tokens=4096, stream=True)
                output = ""
                for chunk in stream:
                    content = chunk.choices[0].delta.content
                    if content:
                        output += chunk.choices[0].delta.content 
                        yield output
            except Exception as e:
                print(e)
                try:
                    message_groq = []
                    message_groq.append({"role":"system", "content": "You are RocketGPT a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
                    for msg in chat_history:
                        message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
                        message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
                    message_groq.append({"role": "user", "content": f"{str(message_text)}"})
                    # its meta-llama/Meta-Llama-3-8B-Instruct
                    stream = client_groq.chat.completions.create(model="llama3-8b-8192",  messages=message_groq, max_tokens=4096, stream=True)
                    output = ""
                    for chunk in stream:
                        content = chunk.choices[0].delta.content
                        if content:
                            output += chunk.choices[0].delta.content 
                            yield output
                except Exception as e:
                    print(e)
                    messages = f"
system\nYou are RocketGPT a helpful and powerful assistant. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions.
"
                    for msg in chat_history:
                        messages += f"\n
user\n{str(msg[0])}
"
                        messages += f"\n
assistant\n{str(msg[1])}
"
                    messages+=f"\n
user\n{message_text}
\n
assistant\n"
                    stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
                    output = ""
                    for response in stream:
                        if not response.token.text == "
":
                            output += response.token.text
                            yield output
                    
# Create a chatbot interface
chatbot = gr.Chatbot(
    label="RocketGPT",
    avatar_images=[None, BOT_AVATAR],
    show_copy_button=True,
    likeable=True,
    layout="panel",
    height=400,
)
output = gr.Textbox(label="Prompt")