File size: 21,859 Bytes
be3c36b 549fdc1 be3c36b 4ac4a54 be3c36b 4ac4a54 be3c36b 4ac4a54 be3c36b 4ac4a54 be3c36b |
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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 |
{
"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": [
"<langchain.vectorstores.faiss.FAISS at 0x23d311f2bd0>"
]
},
"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:<br/>\"\\\n",
"\"π° [Health Insurance Predictor](http://health-insurance-cost-predictor-k19.streamlit.app/)<br/>\"\\\n",
"\"π° [Fake News Detector](https://fake-news-detector-k19.streamlit.app/)<br/>\"\\\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",
" <iframe\n",
" width=\"800\"\n",
" height=\"600\"\n",
" src=\"https://kathir0011-youtube-video-assistant.hf.space\"\n",
" frameborder=\"0\"\n",
" allowfullscreen\n",
" \n",
" ></iframe>\n",
" "
],
"text/plain": [
"<IPython.lib.display.IFrame at 0x1deb305ea50>"
]
},
"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
}
|