ImageCreator + Pika.AIの自動化

年初から動画作成にいそしんでいる。

# ImageCreator 自動化

　リポジトリを発見したので，利用させていただいた。

 https://github.com/acheong08/BingImageCreator

# Pika.AI の自動化
　PIKAのネットワーク履歴を追いかけながら、RequestとResponseの中身を調べてある程度まで解析できた。しかしながら、Genetateの部分でgoogle認証を経由できず、Htmlが戻ってきてしまい、手詰まり状態


```Pika.py
import requests
import os
from dotenv import load_dotenv
import pdb
import requests
from requests.exceptions import JSONDecodeError
import requests
from requests.structures import CaseInsensitiveDict
import json
import brotli  # You might need to install this library
import time
import tkinter as tk
from tkinter import filedialog

def open_file_dialog():
    root = tk.Tk()
    root.withdraw()  # Hide the main window
    file_path = filedialog.askopenfilename()  # Show the file dialog
    return file_path


# .envファイルのパスを指定して読み込む
load_dotenv('.env')

# APIキーを環境変数から取得
api_key = os.getenv('API_KEY')
Authorization = os.getenv('Authorization')
sb_login_auth_token = os.getenv('sb-login-auth-token')


# APIエンドポイントURL
url = 'https://login.pika.art/auth/v1/user'

# Headers
headers = {
    'Apikey': api_key,
    'Authorization': Authorization,
    'X-Client-Info': 'supabase-ssr/0.0.9',
    'Accept': '*/*',
    'Accept-Language': 'en-US,en;q=0.9,ja;q=0.8,ja-JP;q=0.7,zh-CN;q=0.6,zh;q=0.5',
    'Origin': 'https://pika.art',
    'Referer': 'https://pika.art/',
    'Sec-Ch-Ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-site',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}

# Make the GET request
response = requests.get(url, headers=headers)

# Process the response based on status code
if response.status_code == 200:
    # Assuming 'response_json' contains the parsed JSON response
    response_json = response.json()

    # Extracting specific fields
    user_id = response_json['id']
    email = response_json['email']
    full_name = response_json['user_metadata']['full_name']

    print("User ID:", user_id)
    print("Email:", email)
    print("Full Name:", full_name)


# The file path from the GUI
selected_file_path = open_file_dialog()
print("Selected file:", selected_file_path)

# Preparing text fields
payload = {
    'promptText': 'flattering',
    'options': '{"frameRate":24,"camera":{"zoom":"out","pan":null,"tilt":"up","rotate":null},"parameters":{"guidanceScale":25,"motion":4,"negativePrompt":""},"extend":false}',
    'userId': user_id
}

# Only proceed if a file was selected
if selected_file_path:
    # Endpoint URL
    url = "https://api.pika.art/generate"

    # Headers
    headers = CaseInsensitiveDict()
    headers["Authorization"] = Authorization

    # Preparing the file payload
    with open(selected_file_path, 'rb') as f:
        files = {'file': (selected_file_path, f, 'file_type')}  # Replace 'file_type' with the actual file type
        response = requests.post(url, headers=headers, data=payload, files=files)

    # Checking the response
    if response.status_code == 200:
        data = response.json()

        # Extract the 'id' value
        id_value = data['data']['id']
        print("Extracted ID:", id_value)


# URL
url = "https://pika.art/my-library"


# Headers
headers = {
    'Content-Type': 'text/plain;charset=UTF-8',
    'Cookie': sb_login_auth_token, 
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'text/x-component',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,ja;q=0.8,ja-JP;q=0.7,zh-CN;q=0.6,zh;q=0.5',
    # Add any other necessary headers
}

# Payload
payload = json.dumps([{"ids": [ id_value]}])



# ... [your existing setup code for url, headers, and payload] ...

def check_video_status(url, headers, payload, interval=10, max_attempts=30):
    """
    Check video status periodically until it's 'finished' or until max_attempts is reached.
    :param url: API URL
    :param headers: Request headers
    :param payload: Payload for POST request
    :param interval: Time (in seconds) to wait between each attempt
    :param max_attempts: Maximum number of attempts to check status
    :return: MP4 URL if available, else None
    """
    for attempt in range(max_attempts):
        response = requests.post(url, headers=headers, data=payload)

        if response.status_code == 200:
            try:
                data = json.loads(response.text)
                videos = data.get('data', {}).get('results', [])[0].get('videos', [])

                if videos:
                    video_status = videos[0].get('status')
                    if video_status == 'finished':
                        # Replace 'url' with the actual key name for the MP4 URL
                        mp4_url = videos[0].get('url')
                        return mp4_url
                    else:
                        print(f"Attempt {attempt + 1}: Video is not ready yet. Current status: {video_status}")
                else:
                    print("No video information found in the response.")
                    return None

            except json.JSONDecodeError as e:
                print("Failed to parse JSON:", e)
                return None
        else:
            print(f"Failed to retrieve data: {response.status_code}, {response.text}")
            return None

        # Wait for the specified interval before the next attempt
        time.sleep(interval)

    print("Maximum attempts reached. Video is still not ready.")
    return None

# Call the function
mp4_url = check_video_status(url, headers, payload)

if mp4_url:
    print("MP4 URL:", mp4_url)
else:
    print("Failed to get MP4 URL.")

```

# 今後の課題
　動画作成に当たり、シナリオをChatgptに書かせて、そこからImageCreatorで静止画のたたき台を作り、Pikaで動画に変換したい。まだAPIがリリースされていないので、いまは静観状態。
　ミュージックビデオの場合は、歌詞に合わせた動画作成プロンプトも作らせたいところ

# 参考フロー
　一応、手動ながら現状での動画作成工程をまとめておく。

 * BARD もしくは GPT4で作曲　→　ここは想像つくと思うので割愛します。
 * 音楽作成　→　もちろん　SUNO-AIです。
 * テロップ作成　→　以下のサイトでSRTを作成します。　https://converter.app/mp3-to-srt/result.php?lang=en
 * 動画編集　→　Filmoreを使っています。ちょっと前まで、CapcutでもLyricsを作れたのですが、なぜか今は出来なくなりました。

# まとめ
　自分が出来ることは他人も出来る　→　来年には、さくっとミュージック動画ぐらい作れるサービスが出てくると思われる。
 →　個人的には、さらにその上での活用方法などの検討を進める。

# 最後に
 以下、完成した動画

 https://www.youtube.com/watch?v=bJG4koteC-c