InstagramのプロアカウントとFacebook APIとInstagram グラフAPIとPython3とpandasとStreamlitを用いる事ができる状況において、①自分がInstagramで投稿したコンテンツに投稿日を元にした"YYYYMMDD"というIDを付与(同日に複数投稿がある場合には枝番として"_1","_2"と付与)しリストから選択できるようにし、対象のコンテンツ画像をInstagramから自動でダウンロードして表示し、コンテンツに対する"いいね"数と"いいね"したユーザー名とユーザー画像の表示と隣にインプレッションから計算した"いいね"の割合のパーセントを表示するのが1列目、コンテンツに対するコメントとそのコメント実施ユーザー名とユーザー画像が2列目、コンテンツがきっかけでフォローを実施したユーザー名とユーザー画像の表示が3列目、これらの情報を1ペイン目で表示し、②2ペイン目で、すべてのコンテンツの取得可能なすべてのアナリティクス情報の各データをリストから選択し分析でき、インタラクティブなグラフやチャートで1ペイン目と並行して表示できるようにし、③毎回の入力が不要なように事前に必要な情報はコードに埋め込んである設定のPythonコードを作成しています。

'''

import json
import pandas as pd
import requests
import streamlit as st

from datetime import datetime
from typing import Tuple, List

# 事前に必要な情報を埋め込む
ACCESS_TOKEN = ""
USER_ID = ""

def get_post_id(timestamp: str, media_id: str, post_creation_dates: List[str]) -> str:
    date = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S%z').strftime('%Y%m%d')
    post_id = f"{date}_{post_creation_dates.count(date)+1}"
    post_creation_dates.append(date)
    return post_id

def get_media_data(media_id: str) -> Tuple[str, str]:
    media_url = f"https://graph.instagram.com/v12.0/{media_id}?fields=media_type,media_url,timestamp&access_token={ACCESS_TOKEN}"
    response = requests.get(media_url)
    media_data = response.json()
    return media_data["media_url"], media_data["timestamp"]

def get_username_and_picture(user_id: str) -> Tuple[str, str]:
    user_url = f"https://graph.instagram.com/v12.0/{user_id}?fields=username,profile_picture_url&access_token={ACCESS_TOKEN}"
    response = requests.get(user_url)
    user_data = response.json()
    return user_data["username"], user_data["profile_picture_url"]

def get_total_counts(count_type: str, media_id: str) -> int:
    if count_type not in ["likes", "comments"]:
        return 0
    count_url = f"https://graph.instagram.com/v12.0/{media_id}?fields={count_type}.summary(true)&access_token={ACCESS_TOKEN}"
    response = requests.get(count_url)
    summary_data = response.json()
    return summary_data["summary"]["total_count"]

# Check if the access token and user ID are not empty
if not ACCESS_TOKEN:
    st.warning("Please set your ACCESS_TOKEN in the code.")
    st.stop()

if not USER_ID:
    st.warning("Please set your USER_ID in the code.")
    st.stop()

# Main logic
try:
    st.set_page_config(page_title="Instagram Analytics", layout="wide")

    with st.sidebar:
        st.title("Instagram Analytics")

    # Get media
    media_url = f"https://graph.instagram.com/v12.0/{USER_ID}/media?fields=id,caption,timestamp&access_token={ACCESS_TOKEN}"
    response = requests.get(media_url)
    media_df = extract_data(response)

    # Add post ID
    post_creation_dates = []
    media_df["post_id"] = media_df.apply(
        lambda row: get_post_id(row["timestamp"], row["id"], post_creation_dates), axis=1
    )

    # Sidebar selectbox
    selected_post = st.sidebar.selectbox("Select Post:", media_df["post_id"].values)

    with st.empty():
        col1, col2, col3 = st.columns([1, 1, 1])

        # Get selected post data
        selected_media_id = media_df.loc[
            media_df["post_id"] == selected_post, "id"
        ].values[0]

        image_url, post_created_time = get_media_data(selected_media_id)
        st.image(image_url, width=300)

        # Get user-like data
        like_user_information = []
        like_url = f"https://graph.instagram.com/v12.0/{selected_media_id}/likes?fields=username,profile_picture_url,timestamp&access_token={ACCESS_TOKEN}"
        like_data = requests.get(like_url).text
        like_df = extract_data(like_data)
        for idx, user in like_df.iterrows():
            username, profile_picture_url = get_username_and_picture(user["id"])
            like_user_information.append(
                {
                    "username": username,
                    "profile_picture_url": profile_picture_url,
                    "timestamp": user["timestamp"],
                }
            )

        like_user_df = pd.DataFrame(like_user_information)
        if not like_user_df.empty:
            like_user_df = like_user_df[like_user_df["timestamp"] == post_created_time]
            col1.write(like_user_df)

        # Get comments data
        comments_url = f"https://graph.instagram.com/v12.0/{selected_media_id}/comments?fields=username,profile_picture_url,timestamp&access_token={ACCESS_TOKEN}"
        comments_data = requests.get(comments_url).text
        comments_df = extract_data(comments_data)
        if not comments_df.empty:
            comments_df = comments_df[comments_df["timestamp"] == post_created_time]
            for idx, user in comments_df.iterrows():
                username, profile_picture_url = get_username_and_picture(user["id"])
                col2.write(f'{username}: {user["text"]}')
                col2.image(profile_picture_url, width=50)

        # Get follow data (sample data)
        follow_user_info = [
            {
                "id": "id_1",
                "username": "John",
                "profile_picture_url": "https://example.com/profile_1.jpg",
            },
            {
                "id": "id_2",
                "username": "Jane",
                "profile_picture_url": "https://example.com/profile_2.jpg",
            },
        ]
        for follow_user in follow_user_info:
            col3.write(follow_user["username"])
            col3.image(follow_user["profile_picture_url"], width=50)

    with st.expander("Analytics Pane"):
        total_comments = get_total_counts("comments", selected_media_id)
        col1.metric("Total Comments", total_comments)

        # Display interactive graphs and charts of analytics data (sample data)
        sample_data = pd.DataFrame(
            {
                "dates": pd.date_range(start="2021-01-01", periods=10, freq="M"),
                "values": [100, 150, 170, 200, 220, 250, 270, 300, 330, 350],
            }
        )
        selected_analytics = st.multiselect("Select Analytics:", sample_data.columns)
        if any(selected_analytics):
            st.line_chart(sample_data[selected_analytics])

except ValueError as ve:
    st.error(f"An error occurred while fetching data from the API: {str(ve)}")


'''

上記コードを実行すると下記のエラーが発生します。行頭にPython用のインデントを付与した修正済みのコードを省略せずにすべて表示してください。


‘’‘
NameError: name ‘extract_data’ is not defined
Traceback:
File “/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/script_runner.py”, line 565, in _run_script
exec(code, module.dict)
File “/home/walhalax/PycharmProjects/pythonProject/その他/instagram_analytics.py”, line 58, in <module>
media_df = extract_data(response)
’’’