results = []
while base_url:
response = requests.get(base_url, params=params)
data = json.loads(response.text)
results.extend(data['data'])
if 'paging' in data and 'next' in data['paging']:
base_url = data['paging']['next']
else:
base_url = None
for result in results:
# If 'comments' does not exist in result, add an empty 'data' list to it
if not result.get('comments'):
result['comments'] = {'data': []}
df = pd.json_normalize(
results,
record_path=['comments', 'data'],
meta=[
'id', 'media_type', 'media_url', 'thumbnail_url',
'permalink', 'caption', 'timestamp', 'like_count',
'comments_count', 'insights'
],
meta_prefix='meta_', # Add a prefix to the metadata to avoid conflicts
errors='ignore' # Ignore errors and use NaN for thumbnail images that do not exist
)
return df
df = get_instagram_data()
menu = ['Content', 'Analytics']
choice = st.sidebar.radio('Menu', menu)
上記コードを実行するとエラーは表示されませんが、分析対象のコンテンツ画像をInstagramから自動でダウンロードして表示する機能がうまく動作せずに、すべての画像が"Image not found"となってしまいます。また、"Likes"数の脇に表示されるパーセンテージが全てのコンテンツにおいて"0.00%"となっててしまっており、インプレッション数に対してのLike数の割合が正常に表示されておりません。この問題の修正案についてインデントを全角スペースで表現した修正コードを表示してください。
import streamlit as st
import pandas as pd
import requests
import json
import plotly.express as px
from PIL import Image
from io import BytesIO
access_token =""
account_id =""
def get_instagram_data():
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,comments{username,profile_picture_url,text},insights.metric(impressions,engagement)',
'access_token': access_token
}
results = []
while base_url:
response = requests.get(base_url, params=params)
data = json.loads(response.text)
results.extend(data['data'])
if 'paging' in data and 'next' in data['paging']:
base_url = data['paging']['next']
else:
base_url = None
for result in results:
if not result.get('comments'):
result['comments'] = {'data': []}
if not "insights" in result:
result["insights"] = [{"values": []}]
df = pd.json_normalize(
results,
record_path=['comments', 'data'],
meta=[
'id', 'media_type', 'media_url', 'thumbnail_url',
'permalink', 'caption', 'timestamp', 'like_count',
'comments_count', 'insights'
],
meta_prefix='meta_',
errors='ignore'
)
return df
df = get_instagram_data()
menu = ['Content', 'Analytics']
choice = st.sidebar.radio('Menu', menu)
if choice == 'Content':
selected_id = st.sidebar.selectbox('Select Post', df['meta_id'].unique())
selected_data = df[df['meta_id'] == selected_id].iloc[0]
image_url = selected_data['meta_media_url'] if selected_data['meta_media_type'] == 'IMAGE' else selected_data['meta_thumbnail_url']
if pd.notna(image_url):
image_response = requests.get(image_url)
image = Image.open(BytesIO(image_response.content))
st.image(image, use_column_width=True)
else:
st.write('Image not found')
meta_insights = selected_data.get('meta_insights')
try:
if meta_insights and len(meta_insights) > 0 and len(meta_insights[0]["values"]) > 0:
impressions_value = meta_insights[0]["values"][0].get("value", 0)
likes_follows_percentage = (float(selected_data['meta_like_count']) / float(impressions_value)) * 100
else:
likes_follows_percentage = 0
except KeyError:
likes_follows_percentage = 0
st.write(f'Likes: {selected_data["meta_like_count"]} ({likes_follows_percentage:.2f}%)')
st.write(f'Comments: {selected_data["meta_comments_count"]}')
comments_df = df[df['meta_id'] == selected_id]
st.write(comments_df[['username', 'text']])
elif choice == 'Analytics':
categories = ['Impressions', 'Engagement']
selected_category = st.selectbox('Select metric', categories)
if selected_category == 'Impressions':
pass
elif selected_category == 'Engagement':
pass
User
上記コードを実行するとエラーは表示されませんが、分析対象のコンテンツ画像をInstagramから自動でダウンロードして表示する機能がうまく動作せずに、すべての画像が"Image not found"となってしまいます。また、"Likes"数の脇に表示されるパーセンテージが全てのコンテンツにおいて"0.00%"となってしまっており、インプレッション数に対してのLike数の割合が正常に表示されておりません。さらに、各コンテンツが識別IDで表示されていますが、これを"YYYYMMDD_1"というように投稿日として表示されるようにしたうえで、先の問題を含めた修正案について修正コードを表示してください。
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: 'meta_timestamp '
The above exception was the direct cause of the following exception:
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)
上記コードを実行するとエラーは表示されませんが、①以前としてUIに表示させたいコンテンツの画像がInstargramから取得できておらず、"Image not found"が表示されてしまう点と、②以前として、"Likes"脇に表示させたいインプレッション数からのLike率の表示がすべて"0.00%"となってしまっている点があります。また、③個別コンテンツのIDを"YYYYMMDD_1"という表示にしましたが、この"_1"が現在はコメントと紐づいてコメント数に応じて増加する状況ですが、同日に複数の投稿があった際に識別できるように用意した補助的なもので、同日の複数投稿がない場合には"_1"のみを用いるように改修希望です。
Assistant
上記のご指摘に対応するために、以下の修正を加えたコードを提供します。
"Image not found"の問題に対処するために、media_urlまたはthumbnail_urlがない場合はデータフレームから除外します。