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, Union

# 事前に必要な情報を埋め込む
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)
    response.raise_for_status()  # Raise an exception if there's an error in the response
    media_data = response.json()
    return media_data["media_url"], media_data["timestamp"]

def get_username_and_picture(user_id: str) -> Union[Tuple[str, str], Tuple[None, None]]:
    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)
    if response.status_code != 200:
        return None, None
    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)
    response.raise_for_status()  # Raise an exception if there's an error in the response
    summary_data = response.json()
    return summary_data["summary"]["total_count"]

def extract_data(response: requests.models.Response) -> pd.DataFrame:
    if response.text:
        response.raise_for_status()  # Raise an exception if there's an error in the response
        data = json.loads(response.text)["data"]
        return pd.DataFrame(data)
    return None

# 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)
    if response.status_code != 200:
        st.write("An error occurred while fetching data from the API:")
        st.write(response.json())
        st.stop()

    media_df = extract_data(response)
    if media_df is None:
        st.write("No data available for the given ACCESS_TOKEN and USER_ID.")
        st.stop()

    # Add post ID
    try:
        post_creation_dates = []
        media_df["post_id"] = media_df.apply(
            lambda row: get_post_id(row["timestamp"], row["id"], post_creation_dates), axis=1
        )
    except KeyError as e:
        st.error(f"An error occurred while processing the data: {str(e)}")
        st.stop()

    # 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_response = requests.get(like_url)

        if like_response.status_code == 200:
            like_df = extract_data(like_response)

            if like_df is not None:
                for idx, user in like_df.iterrows():
                    username, profile_picture_url = get_username_and_picture(user["id"])
                    if username is not None and profile_picture_url is not None:
                        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_response = requests.get(comments_url)

        if comments_response.status_code == 200:
            comments_df = extract_data(comments_response)

            if comments_df is not None:
                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"])
                        if username is not None and profile_picture_url is not None:
                            col2.write(f'{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)}")
except requests.exceptions.RequestException as e:
    st.error(f"An error occurred while fetching data from the API: {str(e)}")


'''

他のコードでは正常に利用可能な"Insragram Business Account ID "と"AccessToken"を入力して上記コードをstreamlitで実行した際に下記のエラーが発生します。根本的なコードの問題の可能性も考慮して、行頭にPython用のインデントを付与した修正済みのコードを省略せずにすべて表示してください。


‘’‘
An error occurred while fetching data from the API:

An error occurred while fetching data from the API: Expecting value: line 1 column 1 (char 0)
’‘’