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
from collections import defaultdict
環境変数または事前に入力された情報からアクセストークンとアカウントIDを設定
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": []}]
grouped_results = defaultdict(list)
for result in results:
grouped_results[result['timestamp'].split("T")[0]].append(result)
output = []
for timestamp in grouped_results.keys():
for idx, data in enumerate(grouped_results[timestamp], 1):
data["meta_date_id"] = f'{timestamp.replace("-", "")}{idx}'
output.append(data)
df = pd.json_normalize(
output,
record_path=['comments', 'data'],
meta=[
'id', 'media_type', 'media_url', 'thumbnail_url',
'permalink', 'caption', 'timestamp', 'like_count',
'comments_count', 'insights', 'meta_date_id'
],
meta_prefix='meta',
errors='ignore'
)
df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y%m%d')
return df
df = get_instagram_data()
menu = ['Content', 'Analytics']
choice = st.sidebar.radio('Select Menu', menu)
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
from collections import defaultdict
# 環境変数または事前に入力された情報からアクセストークンとアカウントIDを設定
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": []}]
grouped_results = defaultdict(list)
for result in results:
grouped_results[result['timestamp'].split("T")[0]].append(result)
output = []
for timestamp in grouped_results.keys():
for idx, data in enumerate(grouped_results[timestamp], 1):
data["meta_date_id"] = f'{timestamp.replace("-", "")}{idx}'
output.append(data)
df = pd.json_normalize(
output,
record_path=['comments', 'data
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:
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)
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)
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)
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:
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)