{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from openai import OpenAI\n", "import os\n", "import requests\n", "from dotenv import load_dotenv\n", "from langchain_openai import ChatOpenAI\n", "from tavily import TavilyClient\n", "from langchain_core.prompts.prompt import PromptTemplate\n", "from langchain_core.output_parsers import StrOutputParser, JsonOutputParser\n", "from loguru import logger\n", "import concurrent.futures\n", "import json\n", "load_dotenv()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")\n", "llm = ChatOpenAI(model=\"gpt-4o\")\n", "API_KEY = os.getenv('PERPLEXITY_AI_API')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def perplexity_data(prompt, api_key=API_KEY):\n", " url = \"https://api.perplexity.ai/chat/completions\"\n", "\n", " payload = {\n", " \"model\": \"llama-3.1-sonar-huge-128k-online\",\n", " \"messages\": [\n", " {\n", " \"role\": \"system\",\n", " \"content\": \"Be precise and concise.\"\n", " },\n", " {\n", " \"role\": \"user\",\n", " \"content\": prompt\n", " }\n", " ],\n", " \"temperature\": 0.2,\n", " \"top_p\": 0.9,\n", " \"return_citations\": True,\n", " \"search_domain_filter\": [\"perplexity.ai\"],\n", " \"return_images\": False,\n", " \"return_related_questions\": False,\n", " \"search_recency_filter\": \"month\",\n", " \"top_k\": 0,\n", " \"stream\": False,\n", " \"presence_penalty\": 0,\n", " \"frequency_penalty\": 1\n", " }\n", " \n", " headers = {\n", " \"Authorization\": f\"Bearer {api_key}\",\n", " \"Content-Type\": \"application/json\"\n", " }\n", " \n", " response = requests.post(url, json=payload, headers=headers)\n", " \n", " # Check if the request was successful\n", " if response.status_code == 200:\n", " response_data = response.json()\n", " try:\n", " # Extract the message content\n", " message_content = response_data['choices'][0]['message']['content']\n", " return message_content\n", " except (KeyError, IndexError):\n", " return \"Unexpected response format.\"\n", " else:\n", " return f\"Request failed with status code: {response.status_code}\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To do: \n", "\n", "1. Collect the top 5 links of influencer social media platforms \n", "\n", "2. The total number of posts made on each platform so far \n", "\n", "3. Total number of views on each platform\n", "\n", "4. Engagement reach (Total views/Total number of posts made) \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "prompt= \"\"\"\n", " Nina Gelbke is a Health & Fitness influencer, I need you to help me get the following information about this influencer: \n", " 1. The links to Nina Gelbke top five facebook posts. \n", " 2. The links to Nina Gelbke top five instagram posts. \n", " 3. The links to Nina Gelbke top five Youtube videos. \n", " Return in a dictionary. Just answers alone, no explanations. Search deeply.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "result = perplexity_data(prompt)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Based on the provided search results, it\\'s not possible to obtain the specific links to Nina Gelbke\\'s top posts on Facebook, Instagram, and YouTube as the information provided does not include these details. However, I can guide you on how to find this information or provide general information about Nina Gelbke from the available sources:\\n\\n1. **Facebook Posts**: The search results do not provide links to Nina Gelbke\\'s Facebook posts. To find her top Facebook posts, you would need to visit her Facebook page directly and sort her posts by engagement or popularity.\\n\\n2. **Instagram Posts**: The search results mention Nina Gelbke\\'s Instagram handle (@naturally_nina_) but do not provide links to her top posts. To find her top Instagram posts, you would need to visit her Instagram profile and sort her posts by engagement or use third-party tools to analyze her content.\\n\\n3. **YouTube Videos**: The search results do not provide links to Nina Gelbke\\'s YouTube videos. To find her top YouTube videos, you would need to visit her YouTube channel and sort her videos by view count or engagement.\\n\\nGiven the limitations, here is a dictionary with the information that can be provided based on the search results:\\n\\n```python\\nnina_gelbke_info = {\\n \"Instagram Handle\": \"@naturally_nina_\",\\n \"Instagram Followers\": \"154.8K\",\\n \"Type\": \"Macro\",\\n \"Gender\": \"Female\",\\n \"Email Contact\": \"****@outlook.com\",\\n \"Additional Information\": \"Coach @unitviiidunsborough, Athlete @lskd NINA-TEAMLSKD\"\\n}\\n```\\n\\nTo obtain the specific links to her top posts and videos, you would need to access her social media profiles directly or use third-party analytics tools.'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "prompt= \"\"\"\n", " Nina Gelbke is a Health & Fitness influencer, I need you to help me get the following information about this influencer: \n", " 1. The total number of facebook posts made by Nina Gelbke. \n", " 2. The total number of instagram posts made by Nina Gelbk. \n", " 3. The total number of Youtube videos made by Nina Gelbk. \n", " Return in a dictionary. Just answers alone, no explanations. Search deeply.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "result = perplexity_data(prompt)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Based on the provided search results, the requested information about Nina Gelbke\\'s social media posts cannot be found. The available data only includes her Instagram handle and follower count, but not the number of posts on Facebook, Instagram, or YouTube videos.\\n\\n```python\\n{\\n \"facebook_posts\": \"Not Available\",\\n \"instagram_posts\": \"Not Available\",\\n \"youtube_videos\": \"Not Available\"\\n}\\n```'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "prompt= \"\"\"\n", " Nina Gelbke is a Health & Fitness influencer, I need you to help me get the following information about this influencer: \n", " 1. The average number of facebook posts viewers of by Nina Gelbke. \n", " 2. The average number of instagram posts viewers of Nina Gelbk. \n", " 3. The average number of Youtube videos viwers of Nina Gelbk. \n", " Return in a dictionary. Just answers alone, no explanations. Search deeply.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "result = perplexity_data(prompt)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the provided search results, the requested information about Nina Gelbke's social media activity cannot be found. The available data only includes her Instagram handle and follower count, but not the number of posts on Facebook, Instagram, or YouTube videos. Therefore, the information cannot be provided as requested.\n", "\n", "However, to follow the format and provide a response:\n", "\n", "```python\n", "{\n", " \"facebook_posts\": \"Not Available\",\n", " \"instagram_posts\": \"Not Available\",\n", " \"youtube_videos\": \"Not Available\"\n", "}\n", "```\n" ] } ], "source": [ "print(result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Title': 'AyoAjewole Woliagba-YPM',\n", " 'Description': 'This is Official Woli Agba Official YouTube parish members (YPM) Channel....',\n", " 'Subscribers': '697000',\n", " 'Total Views': '161317239',\n", " 'Total Videos': '1400'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import requests\n", "\n", "def get_youtube_channel_info(channel_name: str):\n", " API_KEY = 'AIzaSyBlC2ArLJ6fvc1G6oxmfGx19gb6InSk_As' # Replace with your API key\n", "\n", " url = 'https://www.googleapis.com/youtube/v3/search'\n", " params = {\n", " 'part': 'id',\n", " 'q': channel_name,\n", " 'type': 'channel',\n", " 'key': API_KEY\n", " }\n", "\n", " response = requests.get(url, params=params)\n", "\n", " if response.status_code == 200:\n", " data = response.json()\n", " if 'items' in data and len(data['items']) > 0:\n", " channel_id = data['items'][0]['id']['channelId']\n", " channel_info_url = 'https://www.googleapis.com/youtube/v3/channels'\n", " channel_info_params = {\n", " 'part': 'snippet,statistics',\n", " 'id': channel_id,\n", " 'key': API_KEY\n", " }\n", " channel_info_response = requests.get(channel_info_url, params=channel_info_params)\n", "\n", " if channel_info_response.status_code == 200:\n", " channel_info_data = channel_info_response.json()\n", " if 'items' in channel_info_data and len(channel_info_data['items']) > 0:\n", " channel_info = channel_info_data['items'][0]\n", " title = channel_info['snippet']['title']\n", " description = channel_info['snippet']['description']\n", " subscriber_count = channel_info['statistics']['subscriberCount']\n", " view_count = channel_info['statistics']['viewCount']\n", " video_count = channel_info['statistics']['videoCount']\n", " return {\n", " \"Title\": title,\n", " \"Description\": description,\n", " \"Subscribers\": subscriber_count,\n", " \"Total Views\": view_count,\n", " \"Total Videos\": video_count\n", " }\n", " else:\n", " return \"Channel not found.\"\n", " else:\n", " return f\"Error: {channel_info_response.status_code}\"\n", " else:\n", " return \"Channel not found.\"\n", " else:\n", " return f\"Error: {response.status_code}\"\n", " \n", "get_youtube_channel_info(\"woliagba\")\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Channel Title: AyoAjewole Woliagba-YPM\n", "Channel ID: UCIwUNuYEcZiiJqjU04yN30A\n" ] } ], "source": [ "from googleapiclient.discovery import build\n", "from googleapiclient.errors import HttpError\n", "\n", "def get_channel_id_by_name(api_key, channel_name):\n", " try:\n", " # Build the YouTube service object\n", " youtube = build('youtube', 'v3', developerKey=api_key)\n", "\n", " # Call the search.list method to find the channel\n", " search_response = youtube.search().list(\n", " q=channel_name,\n", " type='channel',\n", " part='id,snippet',\n", " maxResults=1\n", " ).execute()\n", "\n", " # Extract the channel ID from the response\n", " items = search_response.get('items')\n", " if items:\n", " channel_id = items[0]['id']['channelId']\n", " channel_title = items[0]['snippet']['title']\n", " print(f\"Channel Title: {channel_title}\")\n", " print(f\"Channel ID: {channel_id}\")\n", " return channel_id\n", " else:\n", " print(\"No channel found with that name.\")\n", " return None\n", "\n", " except HttpError as e:\n", " print(f\"An HTTP error occurred: {e}\")\n", " return None\n", "\n", "# Example usage\n", "if __name__ == \"__main__\":\n", " API_KEY = 'AIzaSyBlC2ArLJ6fvc1G6oxmfGx19gb6InSk_As' # Replace with your API key\n", " CHANNEL_NAME = 'Woliagba' # Replace with the channel name you're searching for\n", " get_channel_id_by_name(API_KEY, CHANNEL_NAME)\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['https://www.youtube.com/watch?v=yD_Fb76W9Zo', 'https://www.youtube.com/watch?v=QZ5lVAh-hWE', 'https://www.youtube.com/watch?v=qvYPeQAqhAU', 'https://www.youtube.com/watch?v=gBYCpo3r4JE', 'https://www.youtube.com/watch?v=LIKk7BYYHFI']\n" ] } ], "source": [ "from googleapiclient.discovery import build\n", "from googleapiclient.errors import HttpError\n", "\n", "def get_channel_videos(channel_name, max_results=5):\n", " try:\n", " API_KEY = 'AIzaSyBlC2ArLJ6fvc1G6oxmfGx19gb6InSk_As' \n", " # Build the YouTube service object\n", " youtube = build('youtube', 'v3', developerKey=API_KEY)\n", "\n", " # Search for the channel by name\n", " search_response = youtube.search().list(\n", " q=channel_name,\n", " type='channel',\n", " part='id',\n", " maxResults=1\n", " ).execute()\n", "\n", " # Extract the channel ID\n", " items = search_response.get('items')\n", " if not items:\n", " print(\"No channel found with that name.\")\n", " return []\n", "\n", " channel_id = items[0]['id']['channelId']\n", "\n", " # Retrieve the uploads playlist ID\n", " channels_response = youtube.channels().list(\n", " part='contentDetails',\n", " id=channel_id\n", " ).execute()\n", "\n", " uploads_playlist_id = channels_response['items'][0]['contentDetails']['relatedPlaylists']['uploads']\n", "\n", " # Retrieve the videos from the uploads playlist\n", " playlist_items_response = youtube.playlistItems().list(\n", " part='snippet',\n", " playlistId=uploads_playlist_id,\n", " maxResults=max_results\n", " ).execute()\n", "\n", " # Extract video URLs\n", " video_urls = []\n", " for item in playlist_items_response['items']:\n", " video_id = item['snippet']['resourceId']['videoId']\n", " video_url = f\"https://www.youtube.com/watch?v={video_id}\"\n", " video_urls.append(video_url)\n", "\n", " return video_urls\n", "\n", " except HttpError as e:\n", " print(f\"An HTTP error occurred: {e}\")\n", " return []\n", "\n", "# Example usage\n", "if __name__ == \"__main__\": \n", " CHANNEL_NAME = 'Woliagba' # Replace with the channel name you're searching for\n", " video_links = get_channel_videos(CHANNEL_NAME)\n", " print(video_links)\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Title': 'AyoAjewole Woliagba-YPM',\n", " 'Description': 'This is Official Woli Agba Official YouTube parish members (YPM) Channel....',\n", " 'Subscribers': '696000',\n", " 'Total Views': '161245084',\n", " 'Total Videos': '1400',\n", " 'recent_videos': ['https://www.youtube.com/watch?v=yD_Fb76W9Zo',\n", " 'https://www.youtube.com/watch?v=QZ5lVAh-hWE',\n", " 'https://www.youtube.com/watch?v=qvYPeQAqhAU',\n", " 'https://www.youtube.com/watch?v=gBYCpo3r4JE',\n", " 'https://www.youtube.com/watch?v=LIKk7BYYHFI']}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def get_channel_details(channel_name):\n", " channel_info = get_youtube_channel_info(channel_name)\n", " recent_videos = get_channel_videos(channel_name)\n", " channel_info['recent_videos'] = recent_videos\n", " return channel_info\n", "\n", "get_channel_details(\"Woliagba\")\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error: 400 - {\"error\":{\"message\":\"Unsupported get request. Object with ID 'annanystrom120' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https:\\/\\/developers.facebook.com\\/docs\\/graph-api\",\"type\":\"GraphMethodException\",\"code\":100,\"error_subcode\":33,\"fbtrace_id\":\"Az5diARiNO93X8HkpPgmlAp\"}}\n", "User ID: None\n" ] } ], "source": [ "import requests\n", "\n", "def get_facebook_user_id(username, access_token):\n", " url = f\"https://graph.facebook.com/{username}\"\n", " params = {\n", " 'access_token': access_token\n", " }\n", " response = requests.get(url, params=params)\n", " if response.status_code == 200:\n", " user_data = response.json()\n", " return user_data.get('id')\n", " else:\n", " print(f\"Error: {response.status_code} - {response.text}\")\n", " return None\n", "\n", "# Example usage\n", "fb_username = 'annanystrom120' # Replace with the actual username\n", "fb_access_token = '1421765342544303|RjjfymfPIf88lTC7Aqi0oyCLWJQ' # Replace with your access token\n", "user_id = get_facebook_user_id(fb_username, fb_access_token)\n", "print(f\"User ID: {user_id}\")\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Access Token Response:\n", "{'access_token': '1421765342544303|RjjfymfPIf88lTC7Aqi0oyCLWJQ', 'token_type': 'bearer'}\n" ] } ], "source": [ "import requests\n", "\n", "# URL with query parameters\n", "url = \"https://graph.facebook.com/oauth/access_token\"\n", "params = {\n", " \"client_id\": \"1421765342544303\",\n", " \"client_secret\": \"3ce252673497d17036c7556ed55d7a2e\",\n", " \"grant_type\": \"client_credentials\"\n", "}\n", "\n", "# Sending the GET request\n", "response = requests.get(url, params=params)\n", "\n", "# Handling and printing the response\n", "if response.status_code == 200:\n", " print(\"Access Token Response:\")\n", " print(response.json()) # or response.text for raw text\n", "else:\n", " print(\"Error:\", response.status_code)\n", " print(response.text)\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "{'error': {'message': \"(#100) Object does not exist, cannot be loaded due to missing permission or reviewable feature, or does not support this operation. This endpoint requires the 'pages_read_engagement' permission or the 'Page Public Content Access' feature or the 'Page Public Metadata Access' feature. Refer to https://developers.facebook.com/docs/apps/review/login-permissions#manage-pages, https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS and https://developers.facebook.com/docs/apps/review/feature#page-public-metadata-access for details.\", 'type': 'OAuthException', 'code': 100, 'fbtrace_id': 'ACdSS4yBLEX5vv0-sIq53cF'}}\n" ] } ], "source": [ "import requests\n", "\n", "# Set up the access token and user ID\n", "access_token = '1421765342544303|RjjfymfPIf88lTC7Aqi0oyCLWJQ'\n", "user_id = 'melrobbins'\n", "\n", "# Facebook API example (Get user data)\n", "facebook_url = f'https://graph.facebook.com/v15.0/{user_id}?fields=id,name,followers_count,posts&access_token={access_token}'\n", "response = requests.get(facebook_url)\n", "facebook_data = response.json()\n", "\n", "# Instagram API example (Get user data)\n", "instagram_url = f'https://graph.instagram.com/{user_id}?fields=id,username,followers_count,media_count&access_token={access_token}'\n", "response = requests.get(instagram_url)\n", "print(response)\n", "\n", "print(facebook_data)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "ai_env", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.10" } }, "nbformat": 4, "nbformat_minor": 2 }