import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
Assistant
User
Assistant
code
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_charts = st.checkbox("サマリーグラフを表示")
show_charts = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
chart_data = []
chart_data_likes = {}
chart_data_comments = {}
for key, value in count.items():
for c in value:
if c != 'followers_count':
post = count[list(count.keys())[-1]][c]
like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count'])
comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count'])
total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count')
total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count')
if 'followers_count' in value:
chart_data_likes[key] = total_likes_count_diff
chart_data_comments[key] = total_comments_count_diff
chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff])
if show_summary_charts:
df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"])
df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d")
fig, ax1 = plt.subplots(figsize=(15, 6))
sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1)
ax1.set(ylabel="followers_count")
ax2 = ax1.twinx()
sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2)
sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2)
ax2.set(ylabel="total_likes_count & total_comments_count")
plt.title("Summary Chart")
sns.despine()
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_charts:
days = list(chart_data_likes.keys())
likes = [chart_data_likes[d] for d in days]
comments = [chart_data_comments[d] for d in days]
df_like_data = pd.DataFrame({"Date": days, "likes_count": likes})
df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments})
fig, ax1 = plt.subplots(figsize=(5, 3))
sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1)
sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1)
plt.xticks(rotation=90)
plt.title("Like and Comment Counts")
sns.despine()
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)