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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import base64
|
| 3 |
+
import os
|
| 4 |
+
from googleapiclient.discovery import build
|
| 5 |
+
import requests
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
|
| 9 |
+
# Function to fetch all videos from a YouTube playlist
|
| 10 |
+
def fetch_all_youtube_playlist_videos(api_key, playlist_id):
|
| 11 |
+
youtube = build("youtube", "v3", developerKey=api_key)
|
| 12 |
+
request = youtube.playlistItems().list(
|
| 13 |
+
part="snippet",
|
| 14 |
+
maxResults=50, # Maximum results per request
|
| 15 |
+
playlistId=playlist_id
|
| 16 |
+
)
|
| 17 |
+
response = request.execute()
|
| 18 |
+
video_items = response['items']
|
| 19 |
+
while 'nextPageToken' in response:
|
| 20 |
+
nextPageToken = response['nextPageToken']
|
| 21 |
+
request = youtube.playlistItems().list(
|
| 22 |
+
part="snippet",
|
| 23 |
+
maxResults=50,
|
| 24 |
+
playlistId=playlist_id,
|
| 25 |
+
pageToken=nextPageToken
|
| 26 |
+
)
|
| 27 |
+
response = request.execute()
|
| 28 |
+
video_items.extend(response['items'])
|
| 29 |
+
return video_items
|
| 30 |
+
|
| 31 |
+
# Function to extract video information from the playlist items
|
| 32 |
+
def extract_video_info(video_items):
|
| 33 |
+
video_info = []
|
| 34 |
+
for item in video_items:
|
| 35 |
+
video_id = item['snippet']['resourceId']['videoId']
|
| 36 |
+
title = item['snippet']['title']
|
| 37 |
+
published_at = item['snippet']['publishedAt']
|
| 38 |
+
video_info.append({'title': title, 'video_id': video_id, 'published_at': published_at})
|
| 39 |
+
return video_info
|
| 40 |
+
|
| 41 |
+
# Function to set background image and logo
|
| 42 |
+
def set_bg_hack(main_bg_url, logo_url):
|
| 43 |
+
main_bg_ext = main_bg_url.split(".")[-1]
|
| 44 |
+
logo_ext = logo_url.split(".")[-1]
|
| 45 |
+
|
| 46 |
+
main_bg_encoded = base64.b64encode(requests.get(main_bg_url).content).decode()
|
| 47 |
+
logo_encoded = base64.b64encode(requests.get(logo_url).content).decode()
|
| 48 |
+
|
| 49 |
+
st.markdown(
|
| 50 |
+
f"""
|
| 51 |
+
<style>
|
| 52 |
+
.stApp {{
|
| 53 |
+
background: url('data:image/{main_bg_ext};base64,{main_bg_encoded}');
|
| 54 |
+
background-size: cover;
|
| 55 |
+
background-repeat: no-repeat;
|
| 56 |
+
background-position: center;
|
| 57 |
+
}}
|
| 58 |
+
.logo {{
|
| 59 |
+
background: url('data:image/{logo_ext};base64,{logo_encoded}');
|
| 60 |
+
background-size: contain;
|
| 61 |
+
background-repeat: no-repeat;
|
| 62 |
+
background-position: center;
|
| 63 |
+
width: 100px; # Adjust the width as needed
|
| 64 |
+
height: 100px; # Adjust the height as needed
|
| 65 |
+
margin-bottom: 20px; # Adjust the margin as needed
|
| 66 |
+
}}
|
| 67 |
+
.menu {{
|
| 68 |
+
display: flex;
|
| 69 |
+
list-style-type: none;
|
| 70 |
+
padding: 0;
|
| 71 |
+
}}
|
| 72 |
+
.menu li {{
|
| 73 |
+
margin-right: 20px;
|
| 74 |
+
position: relative;
|
| 75 |
+
cursor: pointer;
|
| 76 |
+
}}
|
| 77 |
+
.menu li:after {{
|
| 78 |
+
content: "";
|
| 79 |
+
position: absolute;
|
| 80 |
+
left: 0;
|
| 81 |
+
bottom: -5px;
|
| 82 |
+
width: 100%;
|
| 83 |
+
height: 2px;
|
| 84 |
+
background-color: transparent;
|
| 85 |
+
transition: background-color 0.3s ease;
|
| 86 |
+
}}
|
| 87 |
+
.menu li:hover:after {{
|
| 88 |
+
background-color: green;
|
| 89 |
+
}}
|
| 90 |
+
</style>
|
| 91 |
+
""",
|
| 92 |
+
unsafe_allow_html=True
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# Function to get a restricted video link
|
| 96 |
+
def get_restricted_video_link(video_id):
|
| 97 |
+
return f"https://www.youtube.com/embed/{video_id}?autoplay=1"
|
| 98 |
+
|
| 99 |
+
# Function to handle video upload from local device
|
| 100 |
+
def handle_video_upload():
|
| 101 |
+
st.subheader("Upload Videos")
|
| 102 |
+
uploaded_files = st.file_uploader("Choose videos to upload", accept_multiple_files=True)
|
| 103 |
+
|
| 104 |
+
if uploaded_files:
|
| 105 |
+
for file in uploaded_files:
|
| 106 |
+
file_details = {"FileName": file.name, "FileType": file.type, "FileSize": file.size}
|
| 107 |
+
st.write(file_details)
|
| 108 |
+
|
| 109 |
+
# Optionally save the file or process it further
|
| 110 |
+
# Example: Save uploaded file to a directory
|
| 111 |
+
# with open(os.path.join("uploads", file.name), "wb") as f:
|
| 112 |
+
# f.write(file.getbuffer())
|
| 113 |
+
|
| 114 |
+
# Streamlit app layout
|
| 115 |
+
def main():
|
| 116 |
+
# Set background image and logo
|
| 117 |
+
set_bg_hack("https://huggingface.co/spaces/Nkuku/FVGC/blob/main/cover.png", "https://huggingface.co/spaces/Nkuku/FVGC/blob/main/logo.jpg")
|
| 118 |
+
|
| 119 |
+
st.title("Display Latest Videos from YouTube Channels")
|
| 120 |
+
|
| 121 |
+
# Create a search input for users to search for a specific match
|
| 122 |
+
search_input = st.text_input("Search for a match (e.g., Man City vs Arsenal):")
|
| 123 |
+
|
| 124 |
+
# Create horizontal menu
|
| 125 |
+
st.markdown("<div class='logo'></div>", unsafe_allow_html=True)
|
| 126 |
+
st.markdown("<ul class='menu'><li onclick='handleHomeClick()'>Home</li><li>About</li><li>Videos</li><li><a href='https://www.fotmob.com/'>Matches</a></li><li><a href='https://www.fotmob.com/'>Live Games</a></li><li><a href='https://t.me/skysports_goals'>Popular</a></li></ul>", unsafe_allow_html=True)
|
| 127 |
+
|
| 128 |
+
# Dictionary containing channel IDs and their corresponding playlist IDs
|
| 129 |
+
channel_playlist_ids = {
|
| 130 |
+
"Premier League": "UUG5qGWdu8nIRZqJ_GgDwQ-w",
|
| 131 |
+
"Serie A": "UUBJeMCIeLQos7wacox4hmLQ",
|
| 132 |
+
"Bundesliga": "UU6UL29enLNe4mqwTfAyeNuw",
|
| 133 |
+
"LaLiga": "UUTv-XvfzLX3i4IGWAm4sbmA",
|
| 134 |
+
"UEFA": "UUyGa1YEx9ST66rYrJTGIKOw",
|
| 135 |
+
"CAF TV": "UUr5K057x3mHroPHsNk9OiwA"
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
# API key for accessing the YouTube Data API
|
| 139 |
+
api_key = "YOUR_YOUTUBE_API_KEY_HERE"
|
| 140 |
+
|
| 141 |
+
# Create a menu for selecting a channel
|
| 142 |
+
selected_channel = st.sidebar.selectbox("Select a Channel", list(channel_playlist_ids.keys()))
|
| 143 |
+
|
| 144 |
+
# Display latest videos for the selected channel
|
| 145 |
+
st.header(f"Latest Videos from {selected_channel}")
|
| 146 |
+
|
| 147 |
+
# Fetch all videos from the selected channel's playlist
|
| 148 |
+
video_items = fetch_all_youtube_playlist_videos(api_key, channel_playlist_ids[selected_channel])
|
| 149 |
+
|
| 150 |
+
# Filter videos based on the search input
|
| 151 |
+
if search_input:
|
| 152 |
+
filtered_video_items = [item for item in video_items if search_input.lower() in item['snippet']['title'].lower()]
|
| 153 |
+
else:
|
| 154 |
+
filtered_video_items = video_items
|
| 155 |
+
|
| 156 |
+
# Extract video information and sort them based on publishing date
|
| 157 |
+
video_info = extract_video_info(filtered_video_items)
|
| 158 |
+
sorted_video_info = sorted(video_info, key=lambda x: x['published_at'], reverse=True)
|
| 159 |
+
|
| 160 |
+
# Display the 10 latest videos in two columns
|
| 161 |
+
col1, col2 = st.columns(2)
|
| 162 |
+
for i, info in enumerate(sorted_video_info[:10]):
|
| 163 |
+
restricted_video_link = get_restricted_video_link(info['video_id'])
|
| 164 |
+
if i % 2 == 0:
|
| 165 |
+
col1.video(restricted_video_link)
|
| 166 |
+
else:
|
| 167 |
+
col2.video(restricted_video_link)
|
| 168 |
+
|
| 169 |
+
# Additional functionality to show live scores
|
| 170 |
+
if st.button("Show Live Scores"):
|
| 171 |
+
live_scores = scrape_live_scores()
|
| 172 |
+
st.write(live_scores)
|
| 173 |
+
|
| 174 |
+
# Handle video upload
|
| 175 |
+
if st.sidebar.checkbox("Upload Videos"):
|
| 176 |
+
handle_video_upload()
|
| 177 |
+
|
| 178 |
+
# Set up the OpenAI client with your API Key
|
| 179 |
+
client = OpenAI(api_key="YOUR_OPENAI_API_KEY_HERE")
|
| 180 |
+
|
| 181 |
+
# URL for scraping live football scores
|
| 182 |
+
URL = "https://www.goal.com/en-tza/live-scores"
|
| 183 |
+
|
| 184 |
+
def scrape_live_scores():
|
| 185 |
+
"""Scrape live scores from the web page."""
|
| 186 |
+
try:
|
| 187 |
+
page = requests.get(URL)
|
| 188 |
+
soup = BeautifulSoup(page.content, "html.parser")
|
| 189 |
+
matches = soup.find_all("div", class_="match-row__data")
|
| 190 |
+
live_scores = []
|
| 191 |
+
for match in matches:
|
| 192 |
+
home_team = match.find("div", class_="match-row__team-name match-row__team-name--home").text.strip()
|
| 193 |
+
away_team = match.find("div", class_="match-row__team-name match-row__team-name--away").text.strip()
|
| 194 |
+
score = match.find("div", class_="match-row__score").text.strip()
|
| 195 |
+
live_scores.append(f"{home_team} {score} {away_team}")
|
| 196 |
+
return "\n".join(live_scores) if live_scores else "No current live scores found."
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return f"Failed to retrieve data: {str(e)}"
|
| 199 |
+
|
| 200 |
+
def get_gpt_response(question, live_scores):
|
| 201 |
+
"""
|
| 202 |
+
Generate a response using GPT-4 based on the scraped live scores.
|
| 203 |
+
"""
|
| 204 |
+
try:
|
| 205 |
+
conversation_history = [
|
| 206 |
+
{"role": "system", "content": "You are using an AI to get insights into today's live football scores."},
|
| 207 |
+
{"role": "user", "content": live_scores},
|
| 208 |
+
{"role": "user", "content": question}
|
| 209 |
+
]
|
| 210 |
+
|
| 211 |
+
response = client.chat.completions.create(
|
| 212 |
+
model="gpt-3.5-turbo",
|
| 213 |
+
messages=conversation_history,
|
| 214 |
+
temperature=0.5,
|
| 215 |
+
max_tokens=512
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
if response.choices and response.choices[0].message.content:
|
| 219 |
+
chat_response = response.choices[0].message.content
|
| 220 |
+
else:
|
| 221 |
+
chat_response = "No response generated."
|
| 222 |
+
return chat_response
|
| 223 |
+
|
| 224 |
+
except Exception as e:
|
| 225 |
+
return f"An error occurred: {str(e)}"
|
| 226 |
+
|
| 227 |
+
def process_question(question):
|
| 228 |
+
"""Process the user's question and return the AI's response."""
|
| 229 |
+
live_scores = scrape_live_scores()
|
| 230 |
+
return get_gpt_response(question, live_scores);
|
| 231 |
+
|
| 232 |
+
# JavaScript function to handle 'Home' click
|
| 233 |
+
js_code = """
|
| 234 |
+
<script>
|
| 235 |
+
function handleHomeClick() {
|
| 236 |
+
const appElement = document.querySelector('.stApp');
|
| 237 |
+
appElement.innerHTML = ''; // Clear app content
|
| 238 |
+
|
| 239 |
+
// Example: Implement your home page functionality
|
| 240 |
+
const addVideoTitle = document.createElement('h2');
|
| 241 |
+
addVideoTitle.textContent = 'Add and Upload Videos';
|
| 242 |
+
appElement.appendChild(addVideoTitle);
|
| 243 |
+
|
| 244 |
+
const videoTitleInput = document.createElement('input');
|
| 245 |
+
videoTitleInput.setAttribute('type', 'text');
|
| 246 |
+
videoTitleInput.setAttribute('placeholder', 'Video Title');
|
| 247 |
+
appElement.appendChild(videoTitleInput);
|
| 248 |
+
|
| 249 |
+
const videoUrlInput = document.createElement('input');
|
| 250 |
+
videoUrlInput.setAttribute('type', 'text');
|
| 251 |
+
videoUrlInput.setAttribute('placeholder', 'YouTube Video URL');
|
| 252 |
+
appElement.appendChild(videoUrlInput);
|
| 253 |
+
|
| 254 |
+
const uploadButton = document.createElement('button');
|
| 255 |
+
uploadButton.textContent = 'Upload Video';
|
| 256 |
+
uploadButton.addEventListener('click', () => {
|
| 257 |
+
const videoTitle = videoTitleInput.value;
|
| 258 |
+
const videoUrl = videoUrlInput.value;
|
| 259 |
+
if (videoTitle && videoUrl) {
|
| 260 |
+
const uploadedMessage = document.createElement('p');
|
| 261 |
+
uploadedMessage.textContent = `Video '${videoTitle}' added successfully! Video URL: ${videoUrl}`;
|
| 262 |
+
appElement.appendChild(uploadedMessage);
|
| 263 |
+
} else {
|
| 264 |
+
const errorAlert = document.createElement('p');
|
| 265 |
+
errorAlert.textContent = 'Please provide both video title and YouTube video URL.';
|
| 266 |
+
errorAlert.style.color = 'red';
|
| 267 |
+
appElement.appendChild(errorAlert);
|
| 268 |
+
}
|
| 269 |
+
});
|
| 270 |
+
appElement.appendChild(uploadButton);
|
| 271 |
+
}
|
| 272 |
+
</script>
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
# Main Streamlit application
|
| 276 |
+
if __name__ == "__main__":
|
| 277 |
+
st.markdown(js_code, unsafe_allow_html=True)
|
| 278 |
+
main()
|