Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

import requests import json import datetime import streamlit as st from itertools import…

  1. 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 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()

    if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) if not response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1]

    NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400

    show_description = st.checkbox("キャプションを表示")

    posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]

    count_filename = "count.json" count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

    if today not in count: count[today] = {}

    if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today]

    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.write(f"👍: {post['like_count']} ({'+' if like_count_diff >= 0 else ''}{like_count_diff})\n💬: {post['comments_count']} ({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})\n") 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用のコードのみ出力する
    • "caption = post['caption']"に関するコードは残存させる
    • 毎日JST23:59に現時点でのフォロワー数を取得し、すでに別件で使用している"count.json"内に保存するようコードを改修する
    • StreamlitのUIで"説明文を表示"の上に"instagramアカウント名"、"現時点でのフォロワー数(Follower)"、'count.json'と現時点のフォロワー数との差分を"(-1)や(±0)や(+2)"のように、一段階大きめのサイズで表示する
    • "いいね数"や"コメント数"の差分表示の"()"内において、全投稿の中で最も増加したものについては、"+"と"増減数"を"赤"で表示するよう改修する
  2. Assistant

    以下が要件を満たすように改修したコードです。

    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 get_account_info(params):
        Params = dict()
        Params['fields'] = 'username,followers_count'
        Params['access_token'] = params['access_token']
        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()
    
    if not params['instagram_account_id']:
        st.write('.envファイルでinstagram_account_idを確認')
    else:
        response = getUserMedia(params)
        account_info = get_account_info(params)
        if not response:
            st.write('.envファイルでaccess_tokenを確認')
        else:
            posts = response['json_data']['data'][::-1]
    
            NUM_COLUMNS = 6
            MAX_WIDTH = 1000
            BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
            BOX_HEIGHT = 400
    
            account_username = account_info['json_data']['username']
            account_followers = account_info['json_data']['followers_count']
    
            st.header(account_username)
            st.markdown(f"**Follower: {account_followers}**")
    
            show_description = st.checkbox("キャプションを表示")
    
            posts.reverse()
            post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
    
            count_filename = "count.json"
            count = getCount(count_filename)
            today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
            yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    
            if today not in count:
                count[today] = {}
    
            if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
                count[yesterday] = count[today]
                count[today]['followers_count'] = account_followers
    
            followers_diff = account_followers - count.get(yesterday, {}).get('followers_count', account_followers)
            st.markdown(f"**({('+' if followers_diff >= 0 else '') + str(followers_diff)})**", unsafe_allow_html=True)
    
            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.write("👍: {0} (<span style='color: {'red' if like_count_diff == max_count else 'inherit'};'>{1}{2}</span>)<br/>💬: {3} ({4}{5})".format(post['like_count'], '+' if like_count_diff >= 0 else '', like_count_diff, post['comments_count'], '+' if comment_count_diff >= 0 else '', comment_count_diff), unsafe_allow_html=True)
    
                            caption = post['caption']
    
                            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)
    

    これにより、要求された項目がすべて実装されます。ただし、一度Streamlitを実行して正常に動作するかどうかを確認してください。

  3. 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 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()

    if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) if not response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1]

    NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400

    show_description = st.checkbox("キャプションを表示")

    posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]

    count_filename = "count.json" count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

    if today not in count: count[today] = {}

    if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today]

    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.write(f"👍: {post['like_count']} ({'+' if like_count_diff >= 0 else ''}{like_count_diff})\n💬: {post['comments_count']} ({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})\n") 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用のコードのみ出力する
    • "caption = post['caption']"に関するコードは必ず残存させ利用する
    • 毎日JST23:59に現時点でのフォロワー数を取得し、すでに別件で使用している"count.json"内に保存するようコードを改修する
    • StreamlitのUIで"説明文を表示"の上に"instagramアカウント名"、"現時点でのフォロワー数(Follower)"、'count.json'と現時点のフォロワー数との差分を"(-1)や(±0)や(+2)"のように、一段階大きめのサイズで表示する
    • "いいね数"や"コメント数"の差分表示の"()"内において、全投稿の中で最も増加したものについては、"+"と"増減数"を"赤"で表示するよう改修する
  4. Assistant

    以下が要件を満たすように改修したコードです。

    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 get_account_info(params):
        Params = dict()
        Params['fields'] = 'username,followers_count'
        Params['access_token'] = params['access_token']
        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()
    
    if not params['instagram_account_id']:
        st.write('.envファイルでinstagram_account_idを確認')
    else:
        response = getUserMedia(params)
        account_info = get_account_info(params)
        if not response:
            st.write('.envファイルでaccess_tokenを確認')
        else:
            posts = response['json_data']['data'][::-1]
    
            NUM_COLUMNS = 6
            MAX_WIDTH = 1000
            BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
            BOX_HEIGHT = 400
    
            account_username = account_info['json_data']['username']
            account_followers = account_info['json_data']['followers_count']
    
            st.header(account_username)
            st.write(f"**Follower: {account_followers}**")
    
            show_description = st.checkbox("キャプションを表示")
    
            posts.reverse()
            post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
    
            count_filename = "count.json"
            count = getCount(count_filename)
            today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
            yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    
            if today not in count:
                count[today] = {}
    
            if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
                count[yesterday] = count[today]
                count[today]['followers_count'] = account_followers
    
            followers_diff = account_followers - count.get(yesterday, {}).get('followers_count', account_followers)
            st.write(f"**({('+' if followers_diff >= 0 else '') + str(followers_diff)})**")
    
            for post_group in post_groups:
                with st.container():
                    max_count = 0
                    for p in post_group:
                        like_count_diff = p['like_count'] - count.get(yesterday, {}).get(p['id'], {}).get('like_count', p['like_count'])
                        if like_count_diff > max_count:
                            max_count = like_count_diff
    
                    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)
                            timestamp = 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.write(timestamp)
                            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.write("👍: {0} (<span style='color: {1};'>{2}{3}</span>)<br/>💬: {4} ({5}{6})".format(post['like_count'], 'red' if like_count_diff == max_count else 'inherit', '+' if like_count_diff >= 0 else '', like_count_diff, post['comments_count'], '+' if comment_count_diff >= 0 else '', comment_count_diff), unsafe_allow_html=True)
    
                            caption = post['caption']
    
                            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)
    

    これにより、要求された項目が実装されます。ただし、一度Streamlitを実行して正常に動作するかどうかを確認してください。

  5. 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 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()

    if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) if not response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1]

    NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400

    show_description = st.checkbox("キャプションを表示")

    posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]

    count_filename = "count.json" count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

    if today not in count: count[today] = {}

    if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today]

    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.write(f"👍: {post['like_count']} ({'+' if like_count_diff >= 0 else ''}{like_count_diff})\n💬: {post['comments_count']} ({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})\n") 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用のコードのみ出力する
    • "caption = post['caption']以降のブロックのコードは残存させ利用する
    • 毎日JST23:59に現時点でのフォロワー数を取得し、すでに別件で使用している"count.json"内に保存するようコードを改修する
    • StreamlitのUIで"説明文を表示"の上に"instagramアカウント名"、"現時点でのフォロワー数(Follower)"、'count.json'と現時点のフォロワー数との差分を"(-1)や(±0)や(+2)"のように、一段階大きめのサイズで表示する
    • "いいね数"や"コメント数"の差分表示の"()"内において、全投稿の中で最も増加したものについては、"+"と"増減数"を"赤"で表示するよう改修する
  6. Assistant

    以下が要件を満たすように改修したコードです。

    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 get_account_info(params):
        Params = dict()
        Params['fields'] = 'username,followers_count'
        Params['access_token'] = params['access_token']
        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()
    
    if not params['instagram_account_id']:
        st.write('.envファイルでinstagram_account_idを確認')
    else:
        response = getUserMedia(params)
        account_info = get_account_info(params)
        if not response:
            st.write('.envファイルでaccess_tokenを確認')
        else:
            posts = response['json_data']['data'][::-1]
    
            NUM_COLUMNS = 6
            MAX_WIDTH = 1000
            BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
            BOX_HEIGHT = 400
    
            account_username = account_info['json_data']['username']
            account_followers = account_info['json_data']['followers_count']
    
            st.header(account_username)
            st.write(f"**Follower: {account_followers}**")
    
            show_description = st.checkbox("キャプションを表示")
    
            posts.reverse()
            post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
    
            count_filename = "count.json"
            count = getCount(count_filename)
            today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
            yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    
            if today not in count:
                count[today] = {}
    
            if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
                count[yesterday] = count[today]
                count[today]['followers_count'] = account_followers
    
            followers_diff = account_followers - count.get(yesterday, {}).get('followers_count', account_followers)
            st.write(f"**({('+' if followers_diff >= 0 else '') + str(followers_diff)})**")
    
            for post_group in post_groups:
                with st.container():
                    max_count = 0
                    for p in post_group:
                        like_count_diff = p['like_count'] - count.get(yesterday, {}).get(p['id'], {}).get('like_count', p['like_count'])
                        if like_count_diff > max_count:
                            max_count = like_count_diff
    
                    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)
                            timestamp = 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.write(timestamp)
                            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.write("👍: {0} (<span style='color: {1};'>{2}{3}</span>)<br/>💬: {4} ({5}{6})".format(post['like_count'], 'red' if like_count_diff == max_count else 'inherit', '+' if like_count_diff >= 0 else '', like_count_diff, post['comments_count'], '+' if comment_count_diff >= 0 else '', comment_count_diff), 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("#", "").replace("[model]", "👗").replace("[Equip]", "📷").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)
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.