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: requests.Response) -> pd.DataFrame:
    if response.status_code != 200:
        raise ValueError(f"API request failed with status code {response.status_code}")
        
    data = response.json()['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}"
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 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用のインデントを付与した修正コードを表示してください。


‘’‘
ValueError Traceback (most recent call last)
Cell In[55], line 53
51 media_url = f"https://graph.instagram.com/me/media?fields=id,caption,timestamp&access_token={ACCESS_TOKEN}“
52 response = requests.get(media_url)
—> 53 media_df = extract_data(response)
55 # Add post ID
56 post_creation_dates = []

Cell In[55], line 15, in extract_data(response)
13 def extract_data(response: requests.Response) -> pd.DataFrame:
14 if response.status_code != 200:
—> 15 raise ValueError(f"API request failed with status code {response.status_code}”)
17 data = response.json()[‘data’]
18 df = pd.DataFrame(data)

ValueError: API request failed with status code 400
‘’’