{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "3azo9uQaETcx" }, "source": [ "# Youtube Video Assistant\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "id": "d03axJueETcy" }, "source": [ "## 1. Importing the required libraries" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "id": "W841lhjmETcy" }, "outputs": [], "source": [ "import os\n", "import textwrap\n", "\n", "from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI\n", "from langchain.document_loaders import YoutubeLoader\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.vectorstores import FAISS\n", "from langchain.chains import LLMChain\n", "from langchain.prompts.chat import (\n", " ChatPromptTemplate,\n", " SystemMessagePromptTemplate,\n", " HumanMessagePromptTemplate,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "INZsIwbWETcy" }, "source": [ "## 2. Setting Up the API Key" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "id": "cMWcJUU_ETcy" }, "outputs": [], "source": [ "# setting up the API token\n", "API_KEY = \"AI-----------------------------------PJ\"\n", "os.environ[\"API_KEY\"] = API_KEY" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "API_KEY = os.environ.get(\"API_Key\")" ] }, { "cell_type": "markdown", "metadata": { "id": "Yp_hqQ0LETcy" }, "source": [ "## 3. Building the YouTube Video Assistant" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "id": "Iza8T78METcy" }, "outputs": [], "source": [ "def create_db_from_video_url(video_url):\n", " \"\"\"\n", " Creates an Embedding of the Video and performs \n", " \"\"\"\n", " embeddings = GoogleGenerativeAIEmbeddings(model=\"models/embedding-001\", google_api_key=API_KEY)\n", "\n", " loader = YoutubeLoader.from_youtube_url(video_url)\n", " transcripts = loader.load()\n", " # cannot provide this directly to the model so we are splitting the transcripts into small chunks\n", "\n", " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n", " docs = text_splitter.split_documents(transcripts)\n", "\n", " db = FAISS.from_documents(docs, embedding=embeddings)\n", "\n", " return db" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "id": "ce4gLz4cETcy", "outputId": "389bc688-4af3-42c1-90db-1b494a893b0a" }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "db = create_db_from_video_url(\"https://www.youtube.com/watch?v=C82lT9cWQiA\")\n", "db" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "id": "wED74_iXETcz" }, "outputs": [], "source": [ "def get_response(api_key, db, request, k=5):\n", " \"\"\"\n", " Usind Gemini Pro to get the response. It can handle upto 32k.\n", " \"\"\"\n", "\n", " docs = db.similarity_search(query=request, k=k)\n", " docs_content = \" \".join([doc.page_content for doc in docs])\n", "\n", " chat = ChatGoogleGenerativeAI(model=\"gemini-1.5-flash\", google_api_key=api_key, convert_system_message_to_human=True)\n", "\n", " # creating a template for request\n", " template = \"\"\"\n", " You are an assistant that can answer questions about youtube videos based on\n", " video transcripts: {docs}\n", "\n", " Only use factual information from the transcript to answer the question.\n", "\n", " If you don't have enough information to answer the question, say \"I don't know\".\n", "\n", " Your Answers should be detailed.\n", " \"\"\"\n", "\n", " system_msg_prompt = SystemMessagePromptTemplate.from_template(template)\n", "\n", " # human prompt\n", " human_template = \"Answer the following questions: {question}\"\n", " human_msg_prompt = HumanMessagePromptTemplate.from_template(human_template)\n", "\n", " chat_prompt = ChatPromptTemplate.from_messages(\n", " [system_msg_prompt, human_msg_prompt]\n", " )\n", "\n", " chain = LLMChain(llm=chat, prompt=chat_prompt)\n", "\n", " response = chain.run(question=request, docs=docs_content)\n", "\n", " return response, docs" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "id": "ymqtluKPETcz" }, "outputs": [], "source": [ "video_url = \"https://www.youtube.com/watch?v=Q8d4FGWZDbE\"\n", "db = create_db_from_video_url(video_url=video_url)\n", "\n", "request = \"What is he talking about? and mention each phones specialities\"\n", "response, docs = get_response(API_KEY, db, request)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. What is he talking about? He is comparing the design, camera system, performance, and audio of\n", "the iPhone and the Xiaomi. 2. What are the iPhone's specialities? - Simple and elegant design -\n", "Consistent and accurate colors in photos - Direct and loud vocals in audio - Familiar and intuitive\n", "software that works with muscle memory developed on the iPhone 3. What are the Xiaomi's\n", "specialities? - Unique and edgy design - High-quality camera system with super high-quality lenses,\n", "first-class focusing, and pleasing colors - Better graphics and stability under extreme stress test\n", "- Symmetrical sound with one bottom-firing and one top-firing speaker - New MIUI 14 that allows for\n", "opening more apps at once but still may be too similar to Apple's software for some users - Unibody\n", "design with reduced points of vulnerability and a specially treated silicone rug on top that is\n", "resistant to smudges, fingerprints, and yellowing\n" ] } ], "source": [ "# using textwrap for printing neatly\n", "print(textwrap.fill(response, width=100))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "id": "rJdkPI-fETcz", "outputId": "b99f9bb1-de0d-4907-cb65-e9bb62169e48" }, "outputs": [ { "data": { "text/plain": [ "[Document(page_content=\"the design of these phones the iPhone is much less polarizing it kind of has to be if Apple wants this to be the phone that 30 million people are going to buy they've got no room to be edgy with any of the style choices they've got to keep it simple clean elegant and this does that xiaomi doesn't have that same concern I think this company knows full well that they won't be selling 30 million units of these they're going to sell two maybe three million and those three million are going to be Pro users who are actively seeking something that feels unique and this achieves that goal I wouldn't say it's the neatest prettiest phone it's got like a speed bump halfway up the back of it besides the phone blend into the rear which is again just a bit weird and it kind of makes this strip going up the back look like a carpet that's not fitted properly the phone rattles quite a bit thanks to lots of large camera lenses moving around and the screen borders are still not completely even all the\", metadata={'source': 'Q8d4FGWZDbE'}),\n", " Document(page_content=\"makes it to do that the key thing that I would say xiaomi have just mastered with this phone is the thoughtlessness everything about the way this camera system works the fact that each individual lens is super high quality and so you can zoom all the way in and all the way out without worrying about degradation the fact that focusing is first class so you don't need to sit there messing with it or even tapping your screen to pick out your subject the fact that colors are really pleasing I hesitate to say that the colors are accurate because to be honest if you're going for raw accuracy I still think the iPhone does do a better job but for me personally what the xiaomi does do is better than that I think if you point blank ask someone would you rather your photos are realistic or not the vast majority of people would say I want realism we don't like the idea that images are being tampered with and I'm the same I like the concept but the truth is every smartphone is doing thousands of\", metadata={'source': 'Q8d4FGWZDbE'}),\n", " Document(page_content=\"on how you measure it but xiaomi leads when it comes to the graphics and just to see how well each phone handles temperature because xiaomi does go on about how this phone has the first Aerospace grade toroidal Vapor liquid separated powered cooling system called the marketing these days kill me now I ran an extreme stress test for 20 minutes straight and actually yeah you'll notice that xiaomi not just starts at a higher score because its Graphics are better but also that this score Falls slower over the course of the test it has a higher stability of 80.8 percent as opposed to 65.8 which basically means that whatever gobbledygook they've actually called this internal cooling system it does work when you push both phones to their limits this does feel hotter on the outside but that's because the cooling system is doing a better job of getting heat out the inside and internal heat is generally where more of the problems occur which makes overall performance about a draw depending on\", metadata={'source': 'Q8d4FGWZDbE'}),\n", " Document(page_content=\"kicker bass but it's not one of those phones at the same time that like defies its dimensions in audio or anything so now let's switch over to the xiaomi and this phone does something a little differently instead of one downward firing speaker and then the earpiece on the front doubling as the second this has one bottom firing and then one top firing and I like the fact that xiaomi gives you more symmetrical sound but to be honest for me the fact that Apple's earpiece fires directly towards you makes the vocals feel more direct and it's also a little bit louder so I'll go with the iPhone here the software is subjective of course but I will say one thing xiaomi is not xiaoming shying away from being clearly inspired by Apple you know it's similar when you're finding that the muscle memory that you've developed with your iPhone still works to control this phone now that doesn't make it bad I mean on the contrary this new MIUI 14 can let you open up more apps at once although who\", metadata={'source': 'Q8d4FGWZDbE'}),\n", " Document(page_content=\"of large camera lenses moving around and the screen borders are still not completely even all the way rounds which at this point is just bordering on painful but technically it's really impressive the only reason that you can even see the sides blending into the back is that the sides and the back are actually all one continuous piece here which you know I've had a pretty good play at trying to bend or Creak or crack and uh nothing by using a unibody design like this they've massively reduced the number of points of vulnerability around the phone it reminds me of how reassuring the unibody MacBook feels is like how resistant it is to any kind of flexing compared to a lot of these even technically more expensive laptops that just are made of more parts well that did not sound good and then this uh rug on top is actually specially treated silicon which is made for grip is completely resistant to smudges and fingerprints made to be anti-yellowing which is not a given for silicone\", metadata={'source': 'Q8d4FGWZDbE'})]" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# video transcripts\n", "docs" ] }, { "cell_type": "markdown", "metadata": { "id": "1EW_EayxETcz" }, "source": [ "## 4. Creating a Gradio Web App" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "id": "ZUJKvny6ETcz" }, "outputs": [], "source": [ "import gradio, langchain, langchain_google_genai, faiss" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "id": "N_WLmi_fETc0", "outputId": "18f4c0ce-755e-4239-af50-d224552f2173" }, "outputs": [ { "data": { "text/plain": [ "('4.8.0', '0.0.345', '1.7.4')" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gradio.__version__, langchain.__version__, faiss.__version__" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "id": "MjNKxIcQETc0", "outputId": "5733d415-e3b0-48e2-cc05-062ae920208a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting requirements.txt\n" ] } ], "source": [ "%%writefile requirements.txt\n", "gradio==4.8.0\n", "langchain==0.0.345\n", "faiss-cpu==1.7.4\n", "langchain_google_genai\n", "youtube_transcript_api" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "id": "VxIU2_xPETc0", "outputId": "f2c86270-c334-460b-b785-70917e472a94" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting app.py\n" ] } ], "source": [ "%%writefile app.py\n", "import gradio as gr\n", "import os\n", "\n", "from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI\n", "from langchain.document_loaders import YoutubeLoader\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.vectorstores import FAISS\n", "from langchain.chains import LLMChain\n", "from langchain.prompts.chat import (\n", " ChatPromptTemplate,\n", " SystemMessagePromptTemplate,\n", " HumanMessagePromptTemplate,\n", ")\n", "\n", "def create_db_from_video_url(video_url, api_key):\n", " \"\"\"\n", " Creates an Embedding of the Video and performs \n", " \"\"\"\n", " embeddings = GoogleGenerativeAIEmbeddings(model=\"models/embedding-001\", google_api_key=api_key)\n", "\n", " loader = YoutubeLoader.from_youtube_url(video_url)\n", " transcripts = loader.load()\n", " # cannot provide this directly to the model so we are splitting the transcripts into small chunks\n", "\n", " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n", " docs = text_splitter.split_documents(transcripts)\n", "\n", " db = FAISS.from_documents(docs, embedding=embeddings)\n", " return db\n", "\n", "def get_response(video, request):\n", " \"\"\"\n", " Usind Gemini Pro to get the response. It can handle upto 32k tokens.\n", " \"\"\"\n", " API_KEY = os.environ.get(\"API_Key\")\n", " db = create_db_from_video_url(video, API_KEY)\n", " docs = db.similarity_search(query=request, k=5)\n", " docs_content = \" \".join([doc.page_content for doc in docs])\n", "\n", " chat = ChatGoogleGenerativeAI(model=\"gemini-pro\", google_api_key=API_KEY, convert_system_message_to_human=True)\n", "\n", " # creating a template for request\n", " template = \"\"\"\n", " You are an assistant that can answer questions about youtube videos based on\n", " video transcripts: {docs}\n", "\n", " Only use factual information from the transcript to answer the question.\n", "\n", " If you don't have enough information to answer the question, say \"I don't know\".\n", "\n", " Your Answers should be detailed.\n", " \"\"\"\n", "\n", " system_msg_prompt = SystemMessagePromptTemplate.from_template(template)\n", "\n", " # human prompt\n", " human_template = \"Answer the following questions: {question}\"\n", " human_msg_prompt = HumanMessagePromptTemplate.from_template(human_template)\n", "\n", " chat_prompt = ChatPromptTemplate.from_messages(\n", " [system_msg_prompt, human_msg_prompt]\n", " )\n", "\n", " chain = LLMChain(llm=chat, prompt=chat_prompt)\n", "\n", " response = chain.run(question=request, docs=docs_content)\n", "\n", " return response\n", "\n", "# creating title, description for the web app\n", "title = \"YouTube Video Assistant 🧑‍ðŸ’ŧ\"\n", "description = \"Answers to the Questions asked by the user on the specified YouTube video. (English Only).\\n\\n\"\\\n", "\"Click here to view [demo](https://cdn-uploads.huggingface.co/production/uploads/641aa7814577db917f70f8aa/A-AN-Nkt4qGUKvPhJ92dJ.mp4).\"\n", "article = \"Other Projects:
\"\\\n", "\"💰 [Health Insurance Predictor](http://health-insurance-cost-predictor-k19.streamlit.app/)
\"\\\n", "\"📰 [Fake News Detector](https://fake-news-detector-k19.streamlit.app/)
\"\\\n", "\"ðŸŠķ [Birds Classifier](https://huggingface.co/spaces/Kathir0011/Birds_Classification)\"\n", "\n", "# building the app\n", "youtube_video_assistant = gr.Interface(\n", " fn=get_response,\n", " inputs=[gr.Text(label=\"Enter the Youtube Video URL:\", placeholder=\"Example: https://www.youtube.com/watch?v=MnDudvCyWpc\"),\n", " gr.Text(label=\"Enter your Question\", placeholder=\"Example: What's the video is about?\")],\n", " outputs=gr.TextArea(label=\"Answers using Gemini Pro:\"),\n", " title=title,\n", " description=description,\n", " article=article\n", ")\n", "\n", "# launching the web app\n", "youtube_video_assistant.launch()\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "id": "SmpFQv8gETc0", "outputId": "0a6715b6-2f35-4374-c55e-f05108a39a5e" }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# embedding the deployed app to notebook\n", "from IPython.display import IFrame\n", "\n", "IFrame(src=\"https://kathir0011-youtube-video-assistant.hf.space\", width=800, height=600)" ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "LangChain", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 0 }