1. Introduction
In today's fast-paced digital world, time is a precious commodity. YouTube is a vast repository of information, but lengthy videos can be a significant time investment. This is where YouTube summarizers become invaluable. These tools efficiently condense lengthy videos into concise summaries, allowing users to quickly grasp the core content without watching the entire video. This is particularly useful for students, professionals, and anyone seeking to efficiently extract key information from online video content. Essentially, YouTube summarizers enable users to maximize their learning and information intake while minimizing wasted time.
By the end of this lab, you will have a working web application that can generate summary from YouTube videos. You will also have a better understanding of how to use Gemini API, Google Gen AI SDK, and integrate them together to build a web application.
Your web application will look like this:
All you need to do is to provide a link to the YouTube video and Gemini will do the rest.
2. Before you begin
This codelab assumes that you already have a Google Cloud project with billing enabled. If you do not have it yet, you can follow the instructions below to get started.
- In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.
- Ensure that billing is enabled for your Google Cloud project. Learn how to check if billing is enabled on a project.
- You'll use Cloud Shell, a command-line environment running in Google Cloud. To access it, click Activate Cloud Shell at the top of the Google Cloud console.
- Once connected to Cloud Shell, you check that you're already authenticated and that the project is set to your project ID using the following command:
gcloud auth list
- Run the following command in Cloud Shell to confirm that the gcloud command knows about your project.
gcloud config list project
- If your project is not set, use the following command to set it:
gcloud config set project <YOUR_PROJECT_ID>
- Make sure that the following APIs are enabled:
- Cloud Run
- Vertex AI
The alternative to using the gcloud command is going through the console using this link. Refer to documentation for gcloud commands and usage.
Prerequisites
- Able to read and write Python and HTML codes
- Comfortable working with Gemini API and Google Gen AI SDK
- An understanding of basic full-stack development
What you'll learn
- How to create a Gemini-powered back-end API using Flask API library
- How to build a GenAI app link the front-end and back-end together
- How to deploy the developed GenAI application on Cloud Run
What you'll need
- A working computer and reliable wifi
- A curious mind
3. Create a Python Flask App on Cloud Run
We will create the Python Flask App on Cloud Run using the auto-generated template first from Cloud Shell.
Navigate to the Cloud Shell Terminal and click on the Open Editor button.
Make sure the Cloud Code project is set in the bottom left corner (status bar) of the Cloud Shell editor, as highlighted in the image below and is set to the active Google Cloud project where you have billing enabled. Authorize if prompted.
Click that active project on the status bar and wait for the Cloud Code pop up to open. In the pop up select "New Application".
From the list of applications, choose Cloud Run Application:
For the page 2/2, select Python Flask template:
Provide the name of the project as you wish (e.g. "amazing-gemini-app") and click OK:
This will open up the template for the new project you just set up.
That is how simple it is to create a Python Flask App on Cloud Run with Google Cloud Shell.
4. Build the front-end
As stated before, this is what the final web application going to look like:
It contains an input field to take in a YouTube link from the user, an option to choose a different model family, a textarea to provide additional prompt if needed, and a button to submit the form.
If you like the challenge, feel free to design your own form or edit the CSS properties. You may also copy the code from below and replace the content from your index.html file in the templates folder with it.
<!DOCTYPE html>
<html>
<head>
<title>YouTube Summarizer</title>
<style>
body {
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f4f4f4;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
text-align: center;
}
h2 {
text-align: center;
margin-bottom: 20px;
}
input[type="text"], textarea, select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<h2>YouTube Summarizer</h2>
<form action="/summarize" target="_blank" method="post">
<input type="text" name="youtube_link" placeholder="Enter YouTube Link">
<select name="model">
<option value="gemini-2.0-flash-001">Gemini 2.0 Flash</option>
</select>
<textarea name="additional_prompt" placeholder="Write your additional prompt here. For example: 'explain to me like I am five years old'"></textarea>
<button type="submit">Summarize</button>
</form>
</div>
</body>
</html>
To test whether you have done this step correctly, right click on app.py and choose Run Python File in Terminal.
If everyone went well, you should be able to access your web application on http://127.0.0.1:8080.
5. Build the back-end
Once the front-end has been set up, you will need to create a back-end service that makes use of the Gemini model to summarize the YouTube video provided by the user. Note that you will be overwriting the app.py to complete this task.
Before changing the code, you will need to create a virtual environment and install the necessary libraries to run the Gemini components.
Firstly, you will need to add Google Gen AI SDK library to requirements.txt file. It should looks like this:
Flask==2.3.3
requests==2.31.0
debugpy # Required for debugging.
google-genai==1.2.0
Secondly, you need to create a virtual environment and install the packages from requirements.txt so that you can run the back-end code successfully.
- Click on the bars at the top left corner and choose Terminal > New Terminal
2. Create a virtual environment by typing in the terminal and wait for it to install sucessfully
python -m venv venv source venv/bin/activate pip install -r requirements.txt
Again feel free to challenge yourself and create a Gemini endpoint using Flask API yourself. Your code should be similar to what is provided below.
import os
from flask import Flask, render_template, request
from google import genai
from google.genai import types
app = Flask(__name__)
PROJECT_ID = "REPLACE_WITH_YOUR_PROJECT_ID"
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location="us-central1",
)
# Define the home page route.
@app.route('/', methods=['GET'])
def index():
'''
Renders the home page.
Returns:The rendered template.
'''
return render_template('index.html')
def generate(youtube_link, model, additional_prompt):
# Prepare youtube video using the provided link
youtube_video = types.Part.from_uri(
file_uri=youtube_link,
mime_type="video/*",
)
# If addtional prompt is not provided, just append a space
if not additional_prompt:
additional_prompt = " "
# Prepare content to send to the model
contents = [
youtube_video,
types.Part.from_text(text="""Provide a summary of the video."""),
additional_prompt,
]
# Define content configuration
generate_content_config = types.GenerateContentConfig(
temperature = 1,
top_p = 0.95,
max_output_tokens = 8192,
response_modalities = ["TEXT"],
)
return client.models.generate_content(
model = model,
contents = contents,
config = generate_content_config,
).text
@app.route('/summarize', methods=['GET', 'POST'])
def summarize():
'''
Summarize the user provided YouTube video.
Returns: Summary.
'''
# If the request is a POST request, process the form data.
if request.method == 'POST':
youtube_link = request.form['youtube_link']
model = request.form['model']
additional_prompt = request.form['additional_prompt']
# Generate the summary.
try:
summary = generate(youtube_link, model, additional_prompt)
return summary
except ValueError as e:
raise e
# If the request is a GET request, redirect to the home page.
else:
return redirect('/')
if __name__ == '__main__':
server_port = os.environ.get('PORT', '8080')
app.run(debug=False, port=server_port, host='0.0.0.0')
In essence, the code does the following:
Imports necessary libraries:
- Flask: For creating the web application.
- os: For environment variable access.
- google.genai: For interacting with Google's Gemini AI.
- google.genai.types: For defining data structures for Gemini.
Initializing the Gemini Client:
- It sets up a connection to Google's Vertex AI, enabling the app to use the Gemini AI model. Make sure to replace "REPLACE_WITH_YOUR_PROJECT_ID" with your project ID.
Defining the generate Function:
- This function takes a YouTube video link, a Gemini model id, and an additional prompt as input. It then sends the video and prompt to Gemini and returns the generated summary text.
Defining the Home Page Route (/):
- This function renders the index.html template, which displays a form for the user to enter a YouTube link.
Defining the Summarization Route (/summarize):
- This function handles form submissions. It retrieves the YouTube link, model, and prompt from the form, calls the generate function to get the summary, and then displays the summary in the result.html template.
Running the Application:
- It retrieves the server port from environment variables and starts the Flask web server.
You may test the code by running the app.py from the terminal. Same method as testing the front end. Right click on the app.py and choose Run Python File in Terminal.
Go ahead and test your application. It should be working as expected.
6. Deploy the Web Application
Now that you have the working GenAI application, let's deploy the app on Cloud Run so that you can share it with your friends and colleagues to try.
Navigate to the Cloud Shell Terminal and make sure the current project is configured to your active project, if not you have use the gcloud configure command to set the project id:
gcloud config set project [PROJECT_ID]
Don't forget to replace [PROJECT_ID] with your own project id. Then enter the following commands in that order one by one:
cd amazing-gemini-app
gcloud run deploy --source .
It will prompt you to enter a name for your service, let's say "youtube-summarizer". Choose the corresponding number for the region "us-central1". Say "y" when it asks if you want to allow unauthenticated invocations. Note that we are allowing unauthenticated access here because this is a demo application. Recommendation is to use appropriate authentication for your enterprise and production applications.
Once the deployment is complete, you should get a link similar to the below:
https://amazing-gemini-app-*******.a.run.app/
Go ahead and use your application from Inconito window or your mobile device. It should be live already.
7. Challenge
Now is your time to shine. Do you have what it takes to change the code so that you can upload videos directly from your computer?
8. Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this codelab, follow these steps:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- Alternatively you can go to Cloud Run on the console, select the service you just deployed and delete.