'''
import streamlit as st
import pandas as pd
import requests
import json
from PIL import Image
from io import BytesIO
from itertools import groupby
import instaloader
import datetime
import altair as alt

loader = instaloader.Instaloader()
loader.context.request_timeout = (9, 15)  # Increase request timeout
access_token = ""
account_id = ""

def load_media_info(access_token, account_id):
    base_url = f"https://graph.facebook.com/v11.0/{account_id}/media"
    params = {
    "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)",
    "access_token": access_token
    }

    items = []
    while base_url:
        response = requests.get(base_url, params=params)
        data = json.loads(response.text)

        items.extend(data["data"])

        if "paging" in data and "next" in data["paging"]:
            base_url = data["paging"]["next"]
            params = {}
        else:
            base_url = None

    return pd.DataFrame(items)

df = load_media_info(access_token, account_id)
if 'thumbnail_url' not in df.columns:
    df['thumbnail_url'] = df['media_url']
df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1)

df["id"] = df["timestamp"]
df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d"))

df = df.sort_values("timestamp", ascending=False)
df["id_rank"] = [f"＿＿{len(list(group))}" for _, group in groupby(df["id"])]
df["id"] += df["id_rank"]

menu = ["Content", "Analytics"]
choice = st.sidebar.radio("Menu", menu)

if choice == "Content":
    selected_id = st.sidebar.selectbox("Select Post", df["id"].unique())
    selected_data = df[df["id"] == selected_id].iloc[0]
    image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"]
    image_response = requests.get(image_url)
    image = Image.open(BytesIO(image_response.content))

    st.image(image, caption=selected_data["caption"], width=300)

    likes = selected_data["like_count"]

    if "insights" in selected_data.keys():
        try:
            impressions = selected_data["insights"][0]['values'][0]['value']
            percentage = (likes * 100) / impressions
            st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)")
        except (KeyError, IndexError):
            st.write(f"いいね: {likes}")
    else:
        st.write(f"いいね: {likes}")

    st.write(f"コメント数: {selected_data['comments_count']}")

    # Get comments and usernames
    try:
        shortcode = selected_data["permalink"].split("/")[-2]
        post = instaloader.Post.from_shortcode(loader.context, shortcode)
        comments = post.get_comments()

        for comment in comments:
            st.write(f"{comment.owner.username}: {comment.text}")
    except Exception as e:
        st.write("コメントの取得中にエラーが発生しました。")

elif choice == "Analytics":
    categories = ["フォロワー数", "いいね数", "コメント数"]
    selected_category = st.selectbox("Select metric", categories)

    if selected_category == "フォロワー数":
        metric = "follower_count"
    elif selected_category == "いいね数":
        metric = "like_count"
    elif selected_category == "コメント数":
        metric = "comments_count"
    
    chart_df = df[["id", "timestamp", metric]].copy()
    chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date
    
    chart = alt.Chart(chart_df).mark_line().encode(
        x="timestamp:T",
        y=metric + ":Q"
    ).properties(
        title=f"Time Series of {selected_category}",
        width=800,
        height=300
    )
    st.altair_chart(chart)

'''

上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。

①"Content"の右ペインの"いいね数"の隣に「インプレッション数と"いいね数"から計算された"いいね"実施率」を"(24.9%)"のように小数点第一位まで表示されていない

②"Content"の右ペインの"コメント数"の下に、実際のコメント一覧とコメントしたユーザ名が列挙されるリストが表示されない

③左ペインで"Analytics"を選択し、右ペインでリストから"metric"を選択した際に"フォロワー数"のみグラフが表示されない。この"フォロワー数"を選択した際の画面上のエラー表示は下記。

'''
KeyError: "['follower_count'] not in index"
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/その他/Instargram/instagram_analytics.py", line 99, in <module>
    chart_df = df[["id", "timestamp", metric]].copy()
File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/frame.py", line 3813, in __getitem__
    indexer = self.columns._get_indexer_strict(key, "columns")[1]
File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 6070, in _get_indexer_strict
    self._raise_if_missing(keyarr, indexer, axis_name)
File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 6133, in _raise_if_missing
    raise KeyError(f"{not_found} not in index")
'''

これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。