import requests import json import datetime import streamlit as st from itertools import…
- User
import requests import json import datetime import streamlit as st from itertools import zip_longest import os
def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config
def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res
def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token']
if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET')def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token']
if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET')def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4)
def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {}
st.set_page_config(layout="wide") params = basic_info()
count_filename = "count.json"
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)
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("キャプションを表示") 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 for post_group in post_groups: for post in 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) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): 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')}") 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']) 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") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename)'''
上記のコードを以下の要件をすべて満たして改修してください
-
Python用のインデントを行頭に付与して出力する
-
コードの説明文は表示しない
-
コード部分は'''で区切って表示する
-
指示のないコードの改変はしない
-
既存の'like_count'と"comments_count"表示部分は改変しない
-
"caption = post['caption']"以降のブロックについては改変しない
-
グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
-
jsonファイル内の"followers_count"の実数と、"すべての投稿の前日と比較した当日の'like_count'の純増数"を1軸目の縦軸とし、"すべての投稿の前日と比較した当日の'comments_count'の純増数"を2軸目の縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けし背景色はダークにした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
-
jsonファイル内の"各投稿IDごとの'like_count'"と"各投稿ごとの'comments_count'"の日次データにおいて、"前日と比較した当日の純増数"を縦軸とし、各グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"日付"を横軸にした"いいね/コメント数グラフ"を、各投稿IDのコンテナ内の"キャプション"の下に表示する機能を作成する
-
"キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
-
- Assistant
以下のようにコードを変更しました。
import requests import json import datetime import streamlit as st import seaborn as sns import pandas as pd from itertools import zip_longest from matplotlib import pyplot as plt sns.set(style='darkgrid') def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count'; Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" 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) 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_chart = st.checkbox("サマリーグラフを表示") if show_summary_chart: count = getCount(count_filename) dates = [] followers_count_list = [] like_count_list = [] comments_count_list = [] for date, date_data in count.items(): dates.append(date) followers_count_list.append(date_data.get('followers_count', 0)) total_like_count_increased = 0 total_comments_count_increased = 0 for post_data in date_data.items(): if post_data[0] != 'followers_count': like_count_diff = post_data[1]['like_count'] - count.get(yesterday, {}).get(post_data[0], {}).get('like_count', post_data[1]['like_count']) comment_count_diff = post_data[1]['comments_count'] - count.get(yesterday, {}).get(post_data[0], {}).get('comments_count', post_data[1]['comments_count']) total_like_count_increased += max(like_count_diff, 0) total_comments_count_increased += max(comment_count_diff, 0) like_count_list.append(total_like_count_increased) comments_count_list.append(total_comments_count_increased) summary_df = pd.DataFrame({"date": dates, "followers_count": followers_count_list, "like_count": like_count_list, "comments_count": comments_count_list}) summary_df['date'] = pd.to_datetime(summary_df["date"]) summary_df.set_index('date', inplace=True, drop=True) fig, ax1 = plt.subplots(figsize=(20, 6), dpi=90) ax1.plot(summary_df.index, summary_df["followers_count"], color='steelblue', label='followers_count', linewidth=2) ax1.plot(summary_df.index, summary_df["like_count"], color='orange', label='like_count', linewidth=2) ax2 = ax1.twinx() ax2.plot(summary_df.index, summary_df["comments_count"], color='green', label='comments_count', linewidth=2) ax1.set_title('Summary Chart') ax1.set_xlabel("Date") ax1.set_ylabel("Count") lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc="center right") plt.tight_layout() plt.show.st() show_post_chart = 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 for post_group in post_groups: for post in 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) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): 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')}") 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']) 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) - User
つづき
- Assistant
すみません、前回の返答でコードの投稿が壊れてしまったため、正しいコードを再度送らせていただきます。 つづきです。
def plot_post_chart(post_id, like_count_list, comments_count_list): post_df = pd.DataFrame({"date": dates, "like_count": like_count_list, "comments_count": comments_count_list}) post_df['date'] = pd.to_datetime(post_df["date"]) post_df.set_index('date', inplace=True, drop=True) fig, ax1 = plt.subplots(figsize=(10, 4), dpi=90) ax1.plot(post_df.index, post_df["like_count"], color='orange', label='like_count', linewidth=2) ax2 = ax1.twinx() ax2.plot(post_df.index, post_df["comments_count"], color='green', label='comments_count', linewidth=2) ax1.set_title(f'Post ID: {post_id}') ax1.set_xlabel("Date") ax1.set_ylabel("Count") lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc="center right") plt.tight_layout() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): 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')}") 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']) 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) if show_post_chart: try: dates = [] like_count_list = [] comments_count_list = [] for date, date_data in count.items(): dates.append(date) like_count_list.append(date_data.get(post['id'], {}).get('like_count', None)) comments_count_list.append(date_data.get(post['id'], {}).get('comments_count', None)) plot_post_chart(post['id'], like_count_list, comments_count_list) except Exception as e: st.write("Error while plotting the chart:", str(e)) 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") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) - User
import requests import json import datetime import streamlit as st import seaborn as sns import pandas as pd
from itertools import zip_longest from matplotlib import pyplot as plt
sns.set(style=‘darkgrid’)
def basic_info(): config = dict() config[“access_token”] = st.secrets[“access_token”] config[‘instagram_account_id’] = st.secrets.get(“instagram_account_id”, “”) config[“version”] = ‘v16.0’ config[“graph_domain”] = ‘https://graph.facebook.com/’ config[“endpoint_base”] = config[“graph_domain”] + config[“version”] + ‘/’ return config
def InstaApiCall(url, params, request_type): if request_type == ‘POST’: req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res[“url”] = url res[“endpoint_params”] = params res[“endpoint_params_pretty”] = json.dumps(params, indent=4) res[“json_data”] = json.loads(req.content) res[“json_data_pretty”] = json.dumps(res[“json_data”], indent=4) return res
def getUserMedia(params, pagingUrl=‘’): Params = dict() Params[‘fields’] = ‘id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count’ Params[‘access_token’] = params[‘access_token’]
if not params[‘endpoint_base’]: return None if pagingUrl == ‘’: url = params[‘endpoint_base’] + params[‘instagram_account_id’] + ‘/media’ else: url = pagingUrl return InstaApiCall(url, Params, ‘GET’)def getUser(params): Params = dict() Params[‘fields’] = ‘followers_count’; Params[‘access_token’] = params[‘access_token’]
if not params[‘endpoint_base’]: return None url = params[‘endpoint_base’] + params[‘instagram_account_id’] return InstaApiCall(url, Params, ‘GET’)def saveCount(count, filename): with open(filename, ‘w’) as f: json.dump(count, f, indent=4)
def getCount(filename): try: with open(filename, ‘r’) as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {}
st.set_page_config(layout=“wide”) params = basic_info()
count_filename = “count.json”
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)
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_chart = st.checkbox(“サマリーグラフを表示”) if show_summary_chart: count = getCount(count_filename) dates = [] followers_count_list = [] like_count_list = [] comments_count_list = [] for date, date_data in count.items(): dates.append(date) followers_count_list.append(date_data.get(‘followers_count’, 0)) total_like_count_increased = 0 total_comments_count_increased = 0 for post_data in date_data.items(): if post_data[0] != ‘followers_count’: like_count_diff = post_data[1][‘like_count’] - count.get(yesterday, {}).get(post_data[0], {}).get(‘like_count’, post_data[1][‘like_count’]) comment_count_diff = post_data[1][‘comments_count’] - count.get(yesterday, {}).get(post_data[0], {}).get(‘comments_count’, post_data[1][‘comments_count’]) total_like_count_increased += max(like_count_diff, 0) total_comments_count_increased += max(comment_count_diff, 0) like_count_list.append(total_like_count_increased) comments_count_list.append(total_comments_count_increased) summary_df = pd.DataFrame({“date”: dates, “followers_count”: followers_count_list, “like_count”: like_count_list, “comments_count”: comments_count_list}) summary_df[‘date’] = pd.to_datetime(summary_df[“date”]) summary_df.set_index(‘date’, inplace=True, drop=True) fig, ax1 = plt.subplots(figsize=(20, 6), dpi=90) ax1.plot(summary_df.index, summary_df[“followers_count”], color=‘steelblue’, label=‘followers_count’, linewidth=2) ax1.plot(summary_df.index, summary_df[“like_count”], color=‘orange’, label=‘like_count’, linewidth=2) ax2 = ax1.twinx() ax2.plot(summary_df.index, summary_df[“comments_count”], color=‘green’, label=‘comments_count’, linewidth=2) ax1.set_title(‘Summary Chart’) ax1.set_xlabel(“Date”) ax1.set_ylabel(“Count”) lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc=“center right”) plt.tight_layout() plt.show.st() show_post_chart = 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 for post_group in post_groups: for post in 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) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): 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’)}“) 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’]) 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})” 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})“, unsafe_allow_html=True)
if show_post_chart: try: dates = [] like_count_list = [] comments_count_list = [] for date, date_data in count.items(): dates.append(date) like_count_list.append(date_data.get(post[‘id’], {}).get(‘like_count’, None)) comments_count_list.append(date_data.get(post[‘id’], {}).get(‘comments_count’, None))
plot_post_chart(post[‘id’], like_count_list, comments_count_list)
except Exception as e: st.write(“Error while plotting the chart:”, str(e))
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”) count[today][post[‘id’]] = {‘like_count’: post[‘like_count’], ‘comments_count’: post[‘comments_count’]}
saveCount(count, count_filename)
''' 上記のコードに正確なインデントを付与して再表示してください
- Assistant
こちらがインデントを修正したコードになります。
import requests import json import datetime import streamlit as st import seaborn as sns import pandas as pd from itertools import zip_longest from matplotlib import pyplot as plt sns.set(style='darkgrid') def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" 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) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.