Skip to content

Instantly share code, notes, and snippets.

@fulcrum6378
Last active June 25, 2024 03:24
Show Gist options
  • Save fulcrum6378/edf55f9f5068d4823e1b51094a59544e to your computer and use it in GitHub Desktop.
Save fulcrum6378/edf55f9f5068d4823e1b51094a59544e to your computer and use it in GitHub Desktop.
Reorganiser for the exported `like_posts.json` file of Instagram
import json
from datetime import date, datetime, timedelta
from typing import Dict, List, TextIO
import matplotlib.pyplot as plt
from persiantools.jdatetime import JalaliDate
from pytz import timezone
class Like:
def __init__(self, user: str, link: str, time: int):
self.user: str = user
self.link: str = link[26:-1]
self.date: datetime = datetime.fromtimestamp(time, tz=my_tz)
# Open "liked_posts.json" and collect data
delta = datetime.now()
print('Began reading...')
my_tz = timezone("Asia/Tehran")
likes: List[Like] = list()
for like in json.loads(open('liked_posts.json', 'r', encoding='utf-8').read())['likes_media_likes']:
try:
likes.append(
Like(
like['title'] if 'title' in like else '',
like['string_list_data'][0]['href'],
like['string_list_data'][0]['timestamp']
)
)
except Exception as e:
print('Parsing data:', like)
print(e.__repr__())
quit()
print('Finished reading in', datetime.now() - delta)
# Group the likes by day
print('Grouping...')
# noinspection PyShadowingNames
sorter = lambda like: like.date.timestamp()
asc = True
likes.sort(key=sorter, reverse=not asc) # the cache becomes unorganised after loading anyway
by_day: Dict[date, List[Like]] = dict()
inc, max_date = likes[0].date, likes[-1].date + timedelta(days=1)
while inc < max_date:
by_day[inc.date()] = list()
inc += timedelta(days=1)
for like in likes:
by_day[like.date.date()].append(like)
del likes
for key in by_day: # necessary
by_day[key].sort(key=sorter, reverse=not asc)
print()
z = lambda i: '0' + str(i) if i < 10 else str(i)
while True:
do = input('What to do now? (h => HTML, m => Matplotlib, q => quit): ')
if do == 'h':
delta = datetime.now()
print('Began writing...')
html: TextIO = open('output.html', 'w', encoding='utf-8')
html.write('''<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instagram Liked Posts</title>
<base href="https://www.instagram.com/" target="_blank">
<style>
body { background: #FBFBFB; }
div { padding: 14px 0; }
p { margin: 0; }
h4 { margin: 0 0 9px 0; }
h4, a { color: #333; }
a {
display: inline-block;
border: 0.5px solid #DDD;
border-radius: 3px;
padding: 5px;
margin: 2px 2px;
text-decoration: none;
}
a:hover { background-color: #6CA4FF; color: #FFF; border: 0.5px solid #6CA4FF; }
@media (prefers-color-scheme: dark) {
body { background: #222 !important; color: #EEE !important; }
h4, a { color: #EEE; }
}
</style>
</head>
<body>
''')
for day in by_day:
pd = JalaliDate(day)
html.write('<div><h4>' +
str(day.year) + '.' + z(day.month) + '.' + z(day.day) + ' - ' +
str(pd.year + 5000) + '.' + z(pd.month) + '.' + z(pd.day) +
' {' + str(len(by_day[day])) + '}</h4><p>\n')
for like in by_day[day]:
html.write('<a href="' + like.link + '">' +
z(like.date.hour) + ':' + z(like.date.minute) + ':' + z(like.date.second) +
' - ' + like.user + '</a>\n')
html.write('</p></div>\n')
html.write('''
</body>
</html>''')
html.close()
print('Data written to "./output.html" in', datetime.now() - delta)
if do == 'm':
x = list[date]()
y = list[int]()
for key in by_day:
x.insert(-1, key)
y.insert(-1, len(by_day[key]))
# noinspection PyTypeChecker
plt.plot(x, y)
plt.show()
if do == 'q':
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment