Skip to content

Instantly share code, notes, and snippets.

@amir16yp
Created January 20, 2024 21:24
Show Gist options
  • Save amir16yp/902dc6287d7975f50a386b28a20ac85b to your computer and use it in GitHub Desktop.
Save amir16yp/902dc6287d7975f50a386b28a20ac85b to your computer and use it in GitHub Desktop.
Visualize downloaded yt-dlp comments in HTML format
import json
from sys import argv
from datetime import datetime
header_html = """\
<!DOCTYPE html>
<html>
<head>
<title>Comment Data</title>
<style>
/* Add your CSS here */
body { font-family: Arial, sans-serif; }
.comment { margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; border-radius: 5px; }
.comment .meta { font-size: 0.85em; }
.comment .content { margin-top: 10px; }
.pinned { background-color: #f0f0f0; }
.reply { margin-left: 20px; }
</style>
</head>
<body>
"""
footer_html = """\
</body>
</html>
"""
def load_json_from_file(file_path):
try:
with open(file_path, "r") as json_file:
data = json.load(json_file)
return data
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
except Exception as e:
print(f"An error occurred: {e}")
def convert_timestamp(timestamp):
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def generate_comment_html(comment, is_reply=False):
comment_html = f"""
<div class="comment{' reply' if is_reply else ''}{' pinned' if comment.get('is_pinned', False) else ''}">
<div class="meta">
<img src="{comment['author_thumbnail']}" alt="Profile picture" width="50" height="50">
<a href="{comment['author_url']}">{comment['author']}</a>
commented on {convert_timestamp(comment['timestamp'])}
</div>
<div class="content">
{comment['text']}
<br> Likes: {comment.get('like_count', 0)}
</div>
</div>
"""
return comment_html
def main(data):
comment_data = data['comments']
comments_html = ""
reply_mapping = {}
# Organize comments and replies
for comment in comment_data:
comment_ids = comment['id'].split('.')
is_reply = len(comment_ids) > 1
if is_reply:
parent_id = comment_ids[0]
if parent_id not in reply_mapping:
reply_mapping[parent_id] = []
reply_mapping[parent_id].append(comment)
else:
comments_html += generate_comment_html(comment)
# Append replies to their respective parent comments
for parent_id, replies in reply_mapping.items():
for reply in replies:
comments_html += generate_comment_html(reply, is_reply=True)
# Generate final HTML
final_html = header_html + comments_html + footer_html
with open('comments.html', 'w', encoding='utf-8') as file:
file.write(final_html)
print("HTML file generated successfully.")
if __name__ == "__main__":
file_path = argv[1]
loaded_data = load_json_from_file(file_path)
if loaded_data:
main(loaded_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment