import os import json import pandas as pd import streamlit as st from googleapiclient.discovery import build class YouTube: def __init__(self, api_key, channel_id): self.api_key = api_key self.channel_id = channel_id self.youtube = build("youtube", "v3", developerKey=api_key) def get_general_channel_info(self): try: request = self.youtube.channels().list( part="snippet,statistics", id=self.channel_id ) response = request.execute() channel_info = response["items"][0] channel_stats = { "subscribers": channel_info["statistics"]["subscriberCount"], "views": channel_info["statistics"]["viewCount"], "total_videos": channel_info["statistics"]["videoCount"], "title": channel_info["snippet"]["title"], "description": channel_info["snippet"]["description"], "cover": channel_info["snippet"]["thumbnails"]["high"]["url"], "url": f"https://www.youtube.com/channel/{self.channel_id}", } return pd.DataFrame(channel_stats, index=[0]) except Exception as e: st.error(f"An error occurred: {e}") return pd.DataFrame() def get_video_data(self): try: # Get the playlist ID of the channel's uploaded videos. channel_response = ( self.youtube.channels() .list(part="contentDetails", id=self.channel_id) .execute() ) playlist_id = channel_response["items"][0]["contentDetails"][ "relatedPlaylists" ]["uploads"] # Get all videos in the uploads playlist. videos = [] next_page_token = None while True: playlist_items_response = ( self.youtube.playlistItems() .list( part="snippet", maxResults=50, # Maximum is 50 per request playlistId=playlist_id, pageToken=next_page_token, ) .execute() ) videos.extend(playlist_items_response["items"]) next_page_token = playlist_items_response.get("nextPageToken") if next_page_token is None: break # Extracting relevant data from each video. video_data = [] for video in videos: video_id = video["snippet"]["resourceId"]["videoId"] video_details = ( self.youtube.videos() .list(part="statistics,snippet", id=video_id) .execute() ) if video_details["items"]: video_info = video_details["items"][0] snippet = video_info["snippet"] statistics = video_info["statistics"] video_data.append( { "thumbnail": snippet["thumbnails"]["high"]["url"], "publishedAt": snippet["publishedAt"], "url": f"https://www.youtube.com/watch?v={video_id}", "title": snippet["title"], "viewCount": statistics.get("viewCount", 0), "likeCount": statistics.get("likeCount", 0), "commentCount": statistics.get("commentCount", 0), } ) # Convert to DataFrame df = pd.DataFrame(video_data) return df except Exception as e: st.error(f"An error occurred: {e}") return pd.DataFrame() api_key = os.environ.get("API_KEY") with open("scheme.json") as f: scheme = json.load(f) st.set_page_config(page_title="Social Media Analytics", page_icon="🧊", layout="wide") if __name__ == "__main__": selected_category = st.selectbox("Select Channel", scheme.keys()) platform = st.selectbox("Select Platform", scheme[selected_category].keys()) chanell_id = scheme[selected_category][platform] if st.button("Run"): if platform == "youtube": youtube_account = YouTube(api_key, chanell_id) with st.status("Fetching general channel info...", expanded=True) as status: statistics = youtube_account.get_general_channel_info() with st.status("Fetching video data...", expanded=True) as status: video_data = youtube_account.get_video_data() st.balloons() if not statistics.empty: st.image(statistics["cover"][0], width=200) st.write(f"[Channel URL]({statistics['url'][0]})") st.write( statistics[["title", "subscribers", "views", "total_videos"]], unsafe_allow_html=True, ) video_data["url"] = video_data["url"].apply( lambda x: f'{x}' ) video_data['thumbnail'] = video_data['thumbnail'].apply(lambda x: f'') st.write( video_data.to_html(escape=False, index=False), unsafe_allow_html=True )