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 extract_data(response_text: str) -> pd.DataFrame:
    data = json.loads(response_text)['data']
    df = pd.DataFrame(data)
    return df

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

def get_total_counts(count_type: str, media_id: str) -> int:
    COUNT_URL = f"https://graph.instagram.com/v12.0/{media_id}/{count_type}/count/?access_token={ACCESS_TOKEN}"
    response = requests.get(COUNT_URL)
    return response.json()['count']

def get_media_data(media_id: str) -> Tuple[str, str]:
    MEDIA_URL = f"https://graph.instagram.com/v12.0/{media_id}?fields=id,media_type,media_url,thumbnail_url,permalink,caption,username,comments_count,likes_count,timestamp&access_token={ACCESS_TOKEN}"
    response = requests.get(MEDIA_URL)
    media_data = response.json()
    image_url = media_data['media_url'] if media_data['media_type'] == 'IMAGE' else media_data['thumbnail_url']
    return (image_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'])

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/me/media?fields=id,caption,timestamp&access_token={ACCESS_TOKEN}"
media = requests.get(media_url).text
media_df = extract_data(media)

# 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 like data and display the required information
    total_likes = get_total_counts("likes", selected_media_id)
    col1.metric('Total Likes', total_likes)
    impressions = 0  # Replace with actual impression data
    like_percentage = (total_likes / impressions) * 100 if impressions != 0 else 0
    col1.metric('Like Percentage', f"{like_percentage:.2f}%")

    # 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)
        break

    # 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])

'''

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

‘’‘
KeyError Traceback (most recent call last)
File ~/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py:3802, in Index.get_loc(self, key, method, tolerance)
3801 try:
-> 3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:

File ~/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/_libs/index.pyx:138, in pandas._libs.index.IndexEngine.get_loc()

File ~/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/_libs/index.pyx:165, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: ‘timestamp’

The above exception was the direct cause of the following exception:

KeyError Traceback (most recent call last)
Cell In[50], line 68
64 df[‘timestamp’] = pd.to_datetime(df[‘timestamp’]).dt.strftime(’%Y%m%d’)
66 return df
—> 68 df = get_instagram_data()
70 menu = [‘Content’, ‘Analytics’]
71 choice = st.sidebar.radio(‘Select Menu’, menu)

Cell In[50], line 64, in get_instagram_data()
52 df = pd.json_normalize(
53 output,
54 record_path=[‘comments’, ‘data’],
(…)
61 errors=‘ignore’
62 )
63 df.rename(columns={‘meta_timestamp’: ‘timestamp’}, inplace=True)
—> 64 df[‘timestamp’] = pd.to_datetime(df[‘timestamp’]).dt.strftime(‘%Y%m%d’)
66 return df

File ~/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/frame.py:3807, in DataFrame.getitem(self, key)
3805 if self.columns.nlevels > 1:
3806 return self._getitem_multilevel(key)
-> 3807 indexer = self.columns.get_loc(key)
3808 if is_integer(indexer):
3809 indexer = [indexer]

File ~/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py:3804, in Index.get_loc(self, key, method, tolerance)
3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
-> 3804 raise KeyError(key) from err
3805 except TypeError:
3806 # If we have a listlike key, _check_indexing_error will raise
3807 # InvalidIndexError. Otherwise we fall through and re-raise
3808 # the TypeError.
3809 self._check_indexing_error(key)

KeyError: ‘timestamp’
‘’’