colab-enterprise/Create-Campaign-Naming.ipynb (989 lines of code) (raw):
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='#4285f4'>Overview</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This process generates campaign name suggestions based on the analysis of marketing videos. It provides a suggested campaign name, a description, and an explanation of the reasoning behind the suggestions, leveraging information extracted from the video content.\n",
"\n",
"Process Flow:\n",
"\n",
"1. Create a BigQuery table to hold the results.\n",
"2. Downloads 3 of our GenAI (text-to-video) marketing videos\n",
"3. Use Gemini to watch each video and suggest ideas / names.\n",
"4. Save the data to BigQuery. We are using the JSON output feature of Gemini to saving is easy.\n",
"\n",
"Cost:\n",
"* Low: Gemini, BigQuery\n",
"* Medium: Remember to stop your Colab Enterprise Notebook Runtime\n",
"\n",
"Author: \n",
"* Adam Paternostro"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='#4285f4'>Video Walkthrough</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[](https://storage.googleapis.com/data-analytics-golden-demo/chocolate-ai/v1/Videos/Create-Campaign-Naming.mp4)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import HTML\n",
"\n",
"HTML(\"\"\"\n",
"<video width=\"800\" height=\"600\" controls>\n",
" <source src=\"https://storage.googleapis.com/data-analytics-golden-demo/chocolate-ai/v1/Videos/Create-Campaign-Naming.mp4\" type=\"video/mp4\">\n",
" Your browser does not support the video tag.\n",
"</video>\n",
"\"\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HMsUvoF4BP7Y"
},
"source": [
"### <font color='#4285f4'>License</font>\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jQgQkbOvj55d"
},
"source": [
"```\n",
"# Copyright 2024 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "m65vp54BUFRi"
},
"source": [
"### <font color='#4285f4'>Pip installs</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5MaWM6H5i6rX"
},
"outputs": [],
"source": [
"# PIP Installs\n",
"import sys\n",
"\n",
"# https://PLACEHOLDER.com/index.html\n",
"#!{sys.executable} -m pip install PLACEHOLDER"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UmyL-Rg4Dr_f"
},
"source": [
"### <font color='#4285f4'>Initialize</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xOYsEVSXp6IP"
},
"outputs": [],
"source": [
"from PIL import Image\n",
"from IPython.display import HTML\n",
"from IPython.display import Audio\n",
"from functools import reduce\n",
"import IPython.display\n",
"import google.auth\n",
"import requests\n",
"import json\n",
"import uuid\n",
"import base64\n",
"import os\n",
"import cv2\n",
"import random\n",
"import time\n",
"import datetime\n",
"import base64\n",
"import random\n",
"\n",
"import logging\n",
"from tenacity import retry, wait_exponential, stop_after_attempt, before_sleep_log, retry_if_exception"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wMlHl3bnkFPZ"
},
"outputs": [],
"source": [
"# Set these (run this cell to verify the output)\n",
"\n",
"bigquery_location = \"${bigquery_location}\"\n",
"region = \"${region}\"\n",
"location = \"${location}\"\n",
"storage_account = \"${chocolate_ai_bucket}\"\n",
"public_storage_storage_account = \"data-analytics-golden-demo\"\n",
"\n",
"# Get the current date and time\n",
"now = datetime.datetime.now()\n",
"\n",
"# Format the date and time as desired\n",
"formatted_date = now.strftime(\"%Y-%m-%d-%H-%M\")\n",
"\n",
"# Get some values using gcloud\n",
"project_id = !(gcloud config get-value project)\n",
"user = !(gcloud auth list --filter=status:ACTIVE --format=\"value(account)\")\n",
"\n",
"if len(project_id) != 1:\n",
" raise RuntimeError(f\"project_id is not set: {project_id}\")\n",
"project_id = project_id[0]\n",
"\n",
"if len(user) != 1:\n",
" raise RuntimeError(f\"user is not set: {user}\")\n",
"user = user[0]\n",
"\n",
"print(f\"project_id = {project_id}\")\n",
"print(f\"user = {user}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sZ6m_wGrK0YG"
},
"source": [
"### <font color='#4285f4'>Helper Methods</font>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JbOjdSP1kN9T"
},
"source": [
"#### restAPIHelper\n",
"Calls the Google Cloud REST API using the current users credentials."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "40wlwnY4kM11"
},
"outputs": [],
"source": [
"def restAPIHelper(url: str, http_verb: str, request_body: str) -> str:\n",
" \"\"\"Calls the Google Cloud REST API passing in the current users credentials\"\"\"\n",
"\n",
" import requests\n",
" import google.auth\n",
" import json\n",
"\n",
" # Get an access token based upon the current user\n",
" creds, project = google.auth.default()\n",
" auth_req = google.auth.transport.requests.Request()\n",
" creds.refresh(auth_req)\n",
" access_token=creds.token\n",
"\n",
" headers = {\n",
" \"Content-Type\" : \"application/json\",\n",
" \"Authorization\" : \"Bearer \" + access_token\n",
" }\n",
"\n",
" if http_verb == \"GET\":\n",
" response = requests.get(url, headers=headers)\n",
" elif http_verb == \"POST\":\n",
" response = requests.post(url, json=request_body, headers=headers)\n",
" elif http_verb == \"PUT\":\n",
" response = requests.put(url, json=request_body, headers=headers)\n",
" elif http_verb == \"PATCH\":\n",
" response = requests.patch(url, json=request_body, headers=headers)\n",
" elif http_verb == \"DELETE\":\n",
" response = requests.delete(url, headers=headers)\n",
" else:\n",
" raise RuntimeError(f\"Unknown HTTP verb: {http_verb}\")\n",
"\n",
" if response.status_code == 200:\n",
" return json.loads(response.content)\n",
" #image_data = json.loads(response.content)[\"predictions\"][0][\"bytesBase64Encoded\"]\n",
" else:\n",
" error = f\"Error restAPIHelper -> ' Status: '{response.status_code}' Text: '{response.text}'\"\n",
" raise RuntimeError(error)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### RetryCondition (for retrying LLM calls)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def RetryCondition(error):\n",
" error_string = str(error)\n",
" print(error_string)\n",
"\n",
" retry_errors = [\n",
" \"RESOURCE_EXHAUSTED\",\n",
" \"No content in candidate\",\n",
" # Add more error messages here as needed\n",
" ]\n",
"\n",
" for retry_error in retry_errors:\n",
" if retry_error in error_string:\n",
" print(\"Retrying...\")\n",
" return True\n",
"\n",
" return False"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "em6TFf833Dg1"
},
"source": [
"#### Gemini LLM (Pro 1.0 , Pro 1.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gh2gsPZ83Kub"
},
"outputs": [],
"source": [
"@retry(wait=wait_exponential(multiplier=1, min=1, max=60), stop=stop_after_attempt(10), retry=retry_if_exception(RetryCondition), before_sleep=before_sleep_log(logging.getLogger(), logging.INFO))\n",
"def GeminiLLM(prompt, model = \"gemini-2.0-flash\", response_schema = None,\n",
" temperature = 1, topP = 1, topK = 32):\n",
"\n",
" # https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported_models\n",
" # model = \"gemini-2.0-flash\"\n",
"\n",
" llm_response = None\n",
" if temperature < 0:\n",
" temperature = 0\n",
"\n",
" creds, project = google.auth.default()\n",
" auth_req = google.auth.transport.requests.Request() # required to acess access token\n",
" creds.refresh(auth_req)\n",
" access_token=creds.token\n",
"\n",
" headers = {\n",
" \"Content-Type\" : \"application/json\",\n",
" \"Authorization\" : \"Bearer \" + access_token\n",
" }\n",
"\n",
" # https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference\n",
" url = f\"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/publishers/google/models/{model}:generateContent\"\n",
"\n",
" generation_config = {\n",
" \"temperature\": temperature,\n",
" \"topP\": topP,\n",
" \"maxOutputTokens\": 8192,\n",
" \"candidateCount\": 1,\n",
" \"responseMimeType\": \"application/json\",\n",
" }\n",
"\n",
" # Add inthe response schema for when it is provided\n",
" if response_schema is not None:\n",
" generation_config[\"responseSchema\"] = response_schema\n",
"\n",
" if model == \"gemini-2.0-flash\":\n",
" generation_config[\"topK\"] = topK\n",
"\n",
" payload = {\n",
" \"contents\": {\n",
" \"role\": \"user\",\n",
" \"parts\": {\n",
" \"text\": prompt\n",
" },\n",
" },\n",
" \"generation_config\": {\n",
" **generation_config\n",
" },\n",
" \"safety_settings\": {\n",
" \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n",
" \"threshold\": \"BLOCK_LOW_AND_ABOVE\"\n",
" }\n",
" }\n",
"\n",
" response = requests.post(url, json=payload, headers=headers)\n",
"\n",
" if response.status_code == 200:\n",
" try:\n",
" json_response = json.loads(response.content)\n",
" except Exception as error:\n",
" raise RuntimeError(f\"An error occurred parsing the JSON: {error}\")\n",
"\n",
" if \"candidates\" in json_response:\n",
" candidates = json_response[\"candidates\"]\n",
" if len(candidates) > 0:\n",
" candidate = candidates[0]\n",
" if \"content\" in candidate:\n",
" content = candidate[\"content\"]\n",
" if \"parts\" in content:\n",
" parts = content[\"parts\"]\n",
" if len(parts):\n",
" part = parts[0]\n",
" if \"text\" in part:\n",
" text = part[\"text\"]\n",
" llm_response = text\n",
" else:\n",
" raise RuntimeError(\"No text in part: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No parts in content: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No parts in content: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No content in candidate: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No candidates: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No candidates: {response.content}\")\n",
"\n",
" # Remove some typically response characters (if asking for a JSON reply)\n",
" llm_response = llm_response.replace(\"```json\",\"\")\n",
" llm_response = llm_response.replace(\"```\",\"\")\n",
" llm_response = llm_response.replace(\"\\n\",\"\")\n",
"\n",
" return llm_response\n",
"\n",
" else:\n",
" raise RuntimeError(f\"Error with prompt:'{prompt}' Status:'{response.status_code}' Text:'{response.text}'\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "C-WfLTyD3PdM"
},
"source": [
"#### Gemini LLM - Multimodal"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xPpHNMuz3TA2"
},
"outputs": [],
"source": [
"@retry(wait=wait_exponential(multiplier=1, min=1, max=60), stop=stop_after_attempt(10), retry=retry_if_exception(RetryCondition), before_sleep=before_sleep_log(logging.getLogger(), logging.INFO))\n",
"def GeminiLLM_Multimodal(multimodal_prompt_list, model = \"gemini-2.0-flash\", response_schema = None,\n",
" temperature = 1, topP = 1, topK = 32):\n",
"\n",
" # https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported_models\n",
" # model = \"gemini-2.0-flash\"\n",
"\n",
" llm_response = None\n",
" if temperature < 0:\n",
" temperature = 0\n",
"\n",
" creds, project = google.auth.default()\n",
" auth_req = google.auth.transport.requests.Request() # required to acess access token\n",
" creds.refresh(auth_req)\n",
" access_token=creds.token\n",
"\n",
" headers = {\n",
" \"Content-Type\" : \"application/json\",\n",
" \"Authorization\" : \"Bearer \" + access_token\n",
" }\n",
"\n",
" # https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference\n",
" url = f\"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/publishers/google/models/{model}:generateContent\"\n",
"\n",
" generation_config = {\n",
" \"temperature\": temperature,\n",
" \"topP\": topP,\n",
" \"maxOutputTokens\": 8192,\n",
" \"candidateCount\": 1,\n",
" \"responseMimeType\": \"application/json\",\n",
" }\n",
"\n",
" # Add inthe response schema for when it is provided\n",
" if response_schema is not None:\n",
" generation_config[\"responseSchema\"] = response_schema\n",
"\n",
" if model == \"gemini-2.0-flash\":\n",
" generation_config[\"topK\"] = topK\n",
"\n",
" payload = {\n",
" \"contents\": {\n",
" \"role\": \"user\",\n",
" \"parts\": multimodal_prompt_list\n",
" },\n",
" \"generation_config\": {\n",
" **generation_config\n",
" },\n",
" \"safety_settings\": {\n",
" \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n",
" \"threshold\": \"BLOCK_LOW_AND_ABOVE\"\n",
" }\n",
" }\n",
"\n",
" response = requests.post(url, json=payload, headers=headers)\n",
"\n",
" if response.status_code == 200:\n",
" try:\n",
" json_response = json.loads(response.content)\n",
" except Exception as error:\n",
" raise RuntimeError(f\"An error occurred parsing the JSON: {error}\")\n",
"\n",
" if \"candidates\" in json_response:\n",
" candidates = json_response[\"candidates\"]\n",
" if len(candidates) > 0:\n",
" candidate = candidates[0]\n",
" if \"content\" in candidate:\n",
" content = candidate[\"content\"]\n",
" if \"parts\" in content:\n",
" parts = content[\"parts\"]\n",
" if len(parts):\n",
" part = parts[0]\n",
" if \"text\" in part:\n",
" text = part[\"text\"]\n",
" llm_response = text\n",
" else:\n",
" raise RuntimeError(\"No text in part: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No parts in content: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No parts in content: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No content in candidate: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No candidates: {response.content}\")\n",
" else:\n",
" raise RuntimeError(\"No candidates: {response.content}\")\n",
"\n",
" # Remove some typically response characters (if asking for a JSON reply)\n",
" llm_response = llm_response.replace(\"```json\",\"\")\n",
" llm_response = llm_response.replace(\"```\",\"\")\n",
" llm_response = llm_response.replace(\"\\n\",\"\")\n",
"\n",
" return llm_response\n",
"\n",
" else:\n",
" raise RuntimeError(f\"Error with prompt:'{prompt}' Status:'{response.status_code}' Text:'{response.text}'\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t69_Jg6u3cJE"
},
"source": [
"#### Helper Functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NGI9DHLEXCmy"
},
"outputs": [],
"source": [
"def RunQuery(sql):\n",
" import time\n",
" from google.cloud import bigquery\n",
" client = bigquery.Client()\n",
"\n",
" if (sql.startswith(\"SELECT\") or sql.startswith(\"WITH\")):\n",
" df_result = client.query(sql).to_dataframe()\n",
" return df_result\n",
" else:\n",
" job_config = bigquery.QueryJobConfig(priority=bigquery.QueryPriority.INTERACTIVE)\n",
" query_job = client.query(sql, job_config=job_config)\n",
"\n",
" # Check on the progress by getting the job's updated state.\n",
" query_job = client.get_job(\n",
" query_job.job_id, location=query_job.location\n",
" )\n",
" print(\"Job {} is currently in state {} with error result of {}\".format(query_job.job_id, query_job.state, query_job.error_result))\n",
"\n",
" while query_job.state != \"DONE\":\n",
" time.sleep(2)\n",
" query_job = client.get_job(\n",
" query_job.job_id, location=query_job.location\n",
" )\n",
" print(\"Job {} is currently in state {} with error result of {}\".format(query_job.job_id, query_job.state, query_job.error_result))\n",
"\n",
" if query_job.error_result == None:\n",
" return True\n",
" else:\n",
" raise Exception(query_job.error_result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "v386dal63iO7"
},
"outputs": [],
"source": [
"# prompt: python to delete a file even if it does not exist\n",
"\n",
"def delete_file(filename):\n",
" try:\n",
" os.remove(filename)\n",
" print(f\"File '{filename}' deleted successfully.\")\n",
" except FileNotFoundError:\n",
" print(f\"File '{filename}' not found.\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6Ver7Zw3mQB"
},
"outputs": [],
"source": [
"def PrettyPrintJson(json_string):\n",
" json_object = json.loads(json_string)\n",
" json_formatted_str = json.dumps(json_object, indent=2)\n",
" #print(json_formatted_str)\n",
" return json_formatted_str"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ayxhgKXl3sy4"
},
"outputs": [],
"source": [
"# prompt: python code to download a pdf from the internet\n",
"\n",
"import requests\n",
"\n",
"def download_http_file(url, filename):\n",
" \"\"\"Downloads a PDF file from a given URL.\n",
"\n",
" Args:\n",
" url: The URL of the PDF file to download.\n",
" filename: The name to save the downloaded PDF file as.\n",
" \"\"\"\n",
" try:\n",
" response = requests.get(url)\n",
" response.raise_for_status() # Raise an exception for bad status codes\n",
"\n",
" with open(filename, 'wb') as f:\n",
" f.write(response.content)\n",
"\n",
" print(f\"PDF downloaded successfully to {filename}\")\n",
"\n",
" except requests.exceptions.RequestException as e:\n",
" print(f\"An error occurred while downloading the PDF: {e}\")\n",
"\n",
"# Example usage:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "McbCq7185ak7"
},
"outputs": [],
"source": [
"def download_from_gcs(filename, gcs_storage_bucket, gcs_storage_path):\n",
" # prompt: Write python code to download a blob from a gcs bucket. do not use the requests method\n",
"\n",
" from google.cloud import storage\n",
"\n",
" # The ID of your GCS object\n",
" object_name = gcs_storage_path + filename\n",
"\n",
" # The path to which the file should be downloaded\n",
" destination_file_name = filename\n",
"\n",
" storage_client = storage.Client()\n",
"\n",
" bucket = storage_client.bucket(gcs_storage_bucket)\n",
"\n",
" # Construct a client side representation of a blob.\n",
" # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve\n",
" # any content from Google Cloud Storage. As we don't need additional data,\n",
" # using `Bucket.blob` is preferred here.\n",
" blob = bucket.blob(object_name)\n",
" blob.download_to_filename(destination_file_name)\n",
"\n",
" print(\n",
" \"Downloaded storage object {} from bucket {} to local file {}.\".format(\n",
" object_name, gcs_storage_bucket, destination_file_name\n",
" )\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rGFlKWhQ5_Sb"
},
"outputs": [],
"source": [
"# This was generated by GenAI\n",
"\n",
"def copy_file_to_gcs(local_file_path, bucket_name, destination_blob_name):\n",
" \"\"\"Copies a file from a local drive to a GCS bucket.\n",
"\n",
" Args:\n",
" local_file_path: The full path to the local file.\n",
" bucket_name: The name of the GCS bucket to upload to.\n",
" destination_blob_name: The desired name of the uploaded file in the bucket.\n",
"\n",
" Returns:\n",
" None\n",
" \"\"\"\n",
"\n",
" import os\n",
" from google.cloud import storage\n",
"\n",
" # Ensure the file exists locally\n",
" if not os.path.exists(local_file_path):\n",
" raise FileNotFoundError(f\"Local file '{local_file_path}' not found.\")\n",
"\n",
" # Create a storage client\n",
" storage_client = storage.Client()\n",
"\n",
" # Get a reference to the bucket\n",
" bucket = storage_client.bucket(bucket_name)\n",
"\n",
" # Create a blob object with the desired destination path\n",
" blob = bucket.blob(destination_blob_name)\n",
"\n",
" # Upload the file from the local filesystem\n",
" content_type = \"\"\n",
" if local_file_path.endswith(\".html\"):\n",
" content_type = \"text/html; charset=utf-8\"\n",
"\n",
" if local_file_path.endswith(\".json\"):\n",
" content_type = \"application/json; charset=utf-8\"\n",
"\n",
" if content_type == \"\":\n",
" blob.upload_from_filename(local_file_path)\n",
" else:\n",
" blob.upload_from_filename(local_file_path, content_type = content_type)\n",
"\n",
" print(f\"File '{local_file_path}' uploaded to GCS bucket '{bucket_name}' as '{destination_blob_name}. Content-Type: {content_type}'.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kQT05zdzUrsc"
},
"source": [
"### <font color='#4285f4'>Create BigQuery table</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ysxdLhDvUrCK"
},
"outputs": [],
"source": [
"%%bigquery\n",
"\n",
"--DROP TABLE `${project_id}.${bigquery_chocolate_ai_dataset}.campaign_name_suggestion`;\n",
"\n",
"CREATE TABLE IF NOT EXISTS `${project_id}.${bigquery_chocolate_ai_dataset}.campaign_name_suggestion`\n",
"(\n",
" campaign_name_suggestion_id STRING OPTIONS(description=\"Primary key.\"),\n",
" media STRING OPTIONS(description=\"The video file that is being used to sugguest the name.\"),\n",
" llm_prompt STRING OPTIONS(description=\"LLM Prompt\"),\n",
" campaign_name STRING OPTIONS(description=\"Suggusted Campaign name\"),\n",
" campaign_description STRING OPTIONS(description=\"Suggusted Campaign Description\"),\n",
" llm_explanation STRING OPTIONS(description=\"LLM Explaination\"),\n",
" create_date DATE OPTIONS(description=\"The data the campaign name was created\"),\n",
")\n",
"CLUSTER BY media;"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EYRHDPdVKBzd"
},
"source": [
"### <font color='#4285f4'>Download Existing Ad</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "uIE7-rcs-BL6"
},
"outputs": [],
"source": [
"# Download our sample Chocolate A.I. Ad and upload to our project storage account\n",
"\n",
"print(f\"To browse the public storage account: https://console.cloud.google.com/storage/browser/{public_storage_storage_account}/chocolate-ai/v1\")\n",
"print(\"\")\n",
"\n",
"download_from_gcs(\"full-video-with-audio-en-GB.mp4\", \"data-analytics-golden-demo\", \"chocolate-ai/v1/Campaign-Assets-Text-to-Video-01/story-01/\")\n",
"copy_file_to_gcs(\"full-video-with-audio-en-GB.mp4\", storage_account, f\"chocolate-ai/Create-Campaign-Naming/text-to-videos-{formatted_date}/story-01-full-video-with-audio-en-GB.mp4\")\n",
"\n",
"download_from_gcs(\"full-video-with-audio-en-GB.mp4\", \"data-analytics-golden-demo\", \"chocolate-ai/v1/Campaign-Assets-Text-to-Video-01/story-02/\")\n",
"copy_file_to_gcs(\"full-video-with-audio-en-GB.mp4\", storage_account, f\"chocolate-ai/Create-Campaign-Naming/text-to-videos-{formatted_date}/story-02-full-video-with-audio-en-GB.mp4\")\n",
"\n",
"download_from_gcs(\"full-video-with-audio-en-GB.mp4\", \"data-analytics-golden-demo\", \"chocolate-ai/v1/Campaign-Assets-Text-to-Video-01/story-03/\")\n",
"copy_file_to_gcs(\"full-video-with-audio-en-GB.mp4\", storage_account, f\"chocolate-ai/Create-Campaign-Naming/text-to-videos-{formatted_date}/story-03-full-video-with-audio-en-GB.mp4\")\n",
"\n",
"print(\"\")\n",
"\n",
"print(f\"To view in your project storage account: https://console.cloud.google.com/storage/browser/{storage_account}/chocolate-ai/Create-Campaign-Naming/text-to-videos-{formatted_date}\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vdTa-mUg4SFN"
},
"source": [
"### <font color='#4285f4'>Gemini Prompt</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7Xv1XaaY4UVE"
},
"outputs": [],
"source": [
"# Write me the json in OpenAPI 3.0 schema object for the below object.\n",
"# Make all fields required.\n",
"# [\n",
"# {\n",
"# \"campaign_name\" : \"text\",\n",
"# \"campaign_description\" : \"text\",\n",
"# \"explanation\" : \"text\"\n",
"# }\n",
"# ]\n",
"response_schema = {\n",
" \"type\": \"array\",\n",
" \"items\": {\n",
" \"type\": \"object\",\n",
" \"required\": [\"campaign_name\", \"campaign_description\", \"explanation\"],\n",
" \"properties\": {\n",
" \"campaign_name\": {\n",
" \"type\": \"string\"\n",
" },\n",
" \"campaign_description\": {\n",
" \"type\": \"string\"\n",
" },\n",
" \"explanation\": {\n",
" \"type\": \"string\"\n",
" }\n",
" }\n",
" }\n",
"}\n",
"\n",
"for i in [1,2,3]:\n",
" retry_count = 0\n",
"\n",
" while True:\n",
" try:\n",
"\n",
" filename = f\"gs://{storage_account}/chocolate-ai/Create-Campaign-Naming/text-to-videos-{formatted_date}/story-0{i}-full-video-with-audio-en-GB.mp4\"\n",
" print(f\"filename: {filename}\")\n",
"\n",
" prompt = f\"\"\"You are an expert at creating marketing campaigns.\n",
" You work at Chocolate A.I. a company that sells chocolates, desserts and coffee.\n",
" I am providing you with a video of our latest campaign.\n",
" I need you to create a name for the campaign that is 150 characters or less.\n",
" I need you to create a description for the campaign that is 500 characters or less which is used for upper management to understand the campaign.\n",
" I need you to explain why you have chosen this name.\n",
" This name if for our internal marketing application and is not a name for external customers.\n",
"\n",
" Encourage unconventional ideas and fresh perspectives in your recommendations.\n",
" Embrace unconventional ideas and mutate the recommended action in a way that surprises and inspires unique variations.\n",
"\n",
" Generate 5 potential names and place them in the JSON array.\n",
" \"\"\"\n",
"\n",
" multimodal_prompt_list = [\n",
" { \"text\": prompt },\n",
" { \"fileData\": { \"mimeType\": \"video/mp4\", \"fileUri\": filename } }\n",
" ]\n",
"\n",
" campaign_name_response = GeminiLLM_Multimodal(multimodal_prompt_list, response_schema=response_schema)\n",
" print(campaign_name_response)\n",
"\n",
" campaign_name_dict = json.loads(campaign_name_response)\n",
"\n",
" for item in campaign_name_dict:\n",
" print(f\"campaign_name: {item['campaign_name']}\")\n",
" print(f\"campaign_description: {item['campaign_description']}\")\n",
" print(f\"explanation: {item['explanation']}\")\n",
" sql = f\"\"\"INSERT INTO `${project_id}.${bigquery_chocolate_ai_dataset}.campaign_name_suggestion`\n",
" (campaign_name_suggestion_id, media, llm_prompt, campaign_name, campaign_description, llm_explanation, create_date)\n",
" VALUES ('{str(uuid.uuid4())}',\n",
" '{filename}',\n",
" \\\"\\\"\\\"{prompt}\\\"\\\"\\\",\n",
" '{item[\"campaign_name\"].replace(\"'\",\"\")}',\n",
" '{item[\"campaign_description\"].replace(\"'\",\"\")}',\n",
" '{item[\"explanation\"].replace(\"'\",\"\")}',\n",
" CURRENT_DATE()\n",
" )\"\"\"\n",
"\n",
" RunQuery(sql)\n",
"\n",
" break\n",
"\n",
" except Exception as error:\n",
" print(f\"Error: {error}\")\n",
" retry_count += 1\n",
" if retry_count > 3:\n",
" break\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-Zt3a8lhZjEO"
},
"outputs": [],
"source": [
"%%bigquery\n",
"SELECT media, campaign_name, campaign_description, llm_explanation\n",
" FROM `${project_id}.${bigquery_chocolate_ai_dataset}.campaign_name_suggestion`\n",
" WHERE create_date = CURRENT_DATE()\n",
"ORDER BY media;"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "42IxhtRRrvR-"
},
"source": [
"### <font color='#4285f4'>Clean Up</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6lF2Z7skFbvf"
},
"outputs": [],
"source": [
"# Placeholder"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ASQ2BPisXDA0"
},
"source": [
"### <font color='#4285f4'>Reference Links</font>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wdeshIvv-BL6"
},
"source": [
"- [Google.com](https://www.google.com)"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"HMsUvoF4BP7Y",
"m65vp54BUFRi",
"UmyL-Rg4Dr_f",
"sZ6m_wGrK0YG",
"JbOjdSP1kN9T",
"em6TFf833Dg1",
"C-WfLTyD3PdM",
"t69_Jg6u3cJE",
"kQT05zdzUrsc",
"EYRHDPdVKBzd",
"42IxhtRRrvR-",
"ASQ2BPisXDA0"
],
"name": "Create-Campaign-Naming.ipynb",
"private_outputs": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}