File size: 10,343 Bytes
597b3a4
 
 
 
3406afc
597b3a4
3406afc
597b3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
054b8ad
 
 
f9b0345
054b8ad
 
f9b0345
597b3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3406afc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597b3a4
 
 
054b8ad
623aea1
88ade99
597b3a4
 
 
 
 
 
3406afc
597b3a4
 
 
 
 
 
 
 
 
 
 
 
0694f48
597b3a4
 
 
 
623aea1
597b3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b193235
597b3a4
 
 
 
 
 
ce8a82a
 
8f3a7c3
ce8a82a
 
3406afc
 
623aea1
3406afc
 
623aea1
3406afc
 
 
 
 
 
 
623aea1
3406afc
 
 
 
623aea1
3406afc
 
 
 
623aea1
3406afc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623aea1
3406afc
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import requests
import streamlit as st
from bs4 import BeautifulSoup
from googleapiclient.discovery import build
import base64
from datetime import datetime, timedelta
from openai import OpenAI

# Function to fetch all videos from a YouTube playlist
def fetch_all_youtube_playlist_videos(api_key, playlist_id):
    youtube = build("youtube", "v3", developerKey=api_key)
    request = youtube.playlistItems().list(
        part="snippet",
        maxResults=50,  # Maximum results per request
        playlistId=playlist_id
    )
    response = request.execute()
    video_items = response['items']
    while 'nextPageToken' in response:
        nextPageToken = response['nextPageToken']
        request = youtube.playlistItems().list(
            part="snippet",
            maxResults=50,
            playlistId=playlist_id,
            pageToken=nextPageToken
        )
        response = request.execute()
        video_items.extend(response['items'])
    return video_items

# Function to extract video information from the playlist items
def extract_video_info(video_items):
    video_info = []
    for item in video_items:
        video_id = item['snippet']['resourceId']['videoId']
        title = item['snippet']['title']
        published_at = item['snippet']['publishedAt']
        video_info.append({'title': title, 'video_id': video_id, 'published_at': published_at})
    return video_info

# Function to set background image and logo
def set_bg_hack(main_bg_url, logo_url):
    main_bg_ext = main_bg_url.split(".")[-1]
    logo_ext = logo_url.split(".")[-1]

    main_bg_encoded = base64.b64encode(requests.get(main_bg_url).content).decode()
    logo_encoded = base64.b64encode(requests.get(logo_url).content).decode()

    st.markdown(
        f"""
        <style>
        .stApp {{
            background: url('data:image/{main_bg_ext};base64,{main_bg_encoded}');
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
        }}
        .logo {{
            background: url('data:image/{logo_ext};base64,{logo_encoded}');
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
            width: 100px;  # Adjust the width as needed
            height: 100px;  # Adjust the height as needed
            margin-bottom: 20px;  # Adjust the margin as needed
        }}
        .menu {{
            display: flex;
            list-style-type: none;
            padding: 0;
        }}
        .menu li {{
            margin-right: 20px;
            position: relative;
            cursor: pointer;
        }}
        .menu li:after {{
            content: "";
            position: absolute;
            left: 0;
            bottom: -5px;
            width: 100%;
            height: 2px;
            background-color: transparent;
            transition: background-color 0.3s ease;
        }}
        .menu li:hover:after {{
            background-color: green;
        }}
        </style>
        """,
        unsafe_allow_html=True
    )

# Function to get a restricted video link
def get_restricted_video_link(video_id):
    return f"https://www.youtube.com/embed/{video_id}?autoplay=1"

# Function to handle adding/uploading videos
def handle_video_upload():
    st.subheader("Add and Upload Videos")
    st.write("Use this interface to add and upload videos.")

    video_title = st.text_input("Video Title")
    video_url = st.text_input("YouTube Video URL")

    if st.button("Upload Video"):
        if video_title and video_url:
            st.write(f"Video '{video_title}' added successfully! Video URL: {video_url}")
            # Here you could add logic to store the video information, e.g., in a database or file

# Function to scrape live football scores from a website
def scrape_live_scores():
    URL = "https://www.goal.com/en-tza/live-scores"
    try:
        page = requests.get(URL)
        soup = BeautifulSoup(page.content, "html.parser")
        matches = soup.find_all("div", class_="match-row__data")
        live_scores = []
        for match in matches:
            home_team = match.find("div", class_="match-row__team-name match-row__team-name--home").text.strip()
            away_team = match.find("div", class_="match-row__team-name match-row__team-name--away").text.strip()
            score = match.find("div", class_="match-row__score").text.strip()
            live_scores.append(f"{home_team} {score} {away_team}")
        return "\n".join(live_scores) if live_scores else "No current live scores found."
    except Exception as e:
        return f"Failed to retrieve data: {str(e)}"

# Function to generate response using OpenAI GPT
def get_gpt_response(question, live_scores):
    client = OpenAI(api_key="sk-proj-WH7EctRQbK1zmJjyzCHwT3BlbkFJi2OyxNTMqSWORdpTGYw5")
    try:
        conversation_history = [
            {"role": "system", "content": "You are using an AI to get insights into today's live football scores."},
            {"role": "user", "content": live_scores},
            {"role": "user", "content": question}
        ]

        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=conversation_history,
            temperature=0.5,
            max_tokens=512
        )

        if response.choices and response.choices[0].message.content:
            chat_response = response.choices[0].message.content
        else:
            chat_response = "No response generated."
        return chat_response

    except Exception as e:
        return f"An error occurred: {str(e)}"

# Streamlit app layout
def main():
    # Set background image and logo
    set_bg_hack("https://huggingface.co/spaces/Nkuku/FVGC/blob/main/cover.png", "https://huggingface.co/spaces/Nkuku/FVGC/blob/main/logo.jpg")

    st.title("Wellcome To Football Videos goals clips  Channels")

    # Create a search input for users to search for a specific match
    search_input = st.text_input("Search for a match (e.g., Man City vs Arsenal):")

    # Create horizontal menu
    st.markdown("<div class='logo'></div>", unsafe_allow_html=True)
    st.markdown("<ul class='menu'><li><a href='#' onclick='handleHomeClick()'>Home</a></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)
    
    # Dictionary containing channel IDs and their corresponding playlist IDs
    channel_playlist_ids = {
        "Premier League": "UUG5qGWdu8nIRZqJ_GgDwQ-w",
        "Serie A": "UUBJeMCIeLQos7wacox4hmLQ",
        "Bundesliga": "UU6UL29enLNe4mqwTfAyeNuw",
        "LaLiga": "UUTv-XvfzLX3i4IGWAm4sbmA",
        "UEFA": "UUyGa1YEx9ST66rYrJTGIKOw",
        "CAF TV": "UUr5K057x3mHroPHsNk9OiwA"
    }

    # API key for accessing the YouTube Data API
    api_key = "AIzaSyBAFAhl15rrR5lQ1VA_wn15zuBgMqaOTpA"

    # Create a menu for selecting a channel
    selected_channel = st.sidebar.selectbox("Select a Channel", list(channel_playlist_ids.keys()))

    # Display latest videos for the selected channel
    st.header(f"Latest Videos from {selected_channel}")

    # Fetch all videos from the selected channel's playlist
    video_items = fetch_all_youtube_playlist_videos(api_key, channel_playlist_ids[selected_channel])

    # Filter videos based on the search input
    if search_input:
        filtered_video_items = [item for item in video_items if search_input.lower() in item['snippet']['title'].lower()]
    else:
        filtered_video_items = video_items

    # Extract video information and sort them based on publishing date
    video_info = extract_video_info(filtered_video_items)
    sorted_video_info = sorted(video_info, key=lambda x: x['published_at'], reverse=True)

    # Display the 10 latest videos in two columns
    col1, col2 = st.columns(2)
    for i, info in enumerate(sorted_video_info[:50]):
        restricted_video_link = get_restricted_video_link(info['video_id'])
        if i % 2 == 0:
            col1.video(restricted_video_link)
        else:
            col2.video(restricted_video_link)

    # Additional functionality to show live scores
    if st.button("Show Live Scores"):
        live_scores = scrape_live_scores();
        st.write(live_scores)

    # Handle adding/uploading videos
    handle_video_upload()

# Handle JavaScript function for clicking "Home"
st.markdown(
    """
    <script>
    function handleHomeClick() {
        const appElement = document.querySelector('.stApp');
        appElement.innerHTML = '';  // Clear app content
        const addVideoTitle = document.createElement('h2');
        addVideoTitle.textContent = 'Add and Upload Videos';
        appElement.appendChild(addVideoTitle);
        
        const videoTitleInput = document.createElement('input');
        videoTitleInput.setAttribute('type', 'text');
        videoTitleInput.setAttribute('placeholder', 'Video Title');
        appElement.appendChild(videoTitleInput);
        
        const videoUrlInput = document.createElement('input');
        videoUrlInput.setAttribute('type', 'text');
        videoUrlInput.setAttribute('placeholder', 'YouTube Video URL');
        appElement.appendChild(videoUrlInput);
        
        const uploadButton = document.createElement('button');
        uploadButton.textContent = 'Upload Video';
        uploadButton.addEventListener('click', () => {
            const videoTitle = videoTitleInput.value;
            const videoUrl = videoUrlInput.value;
            if (videoTitle && videoUrl) {
                const uploadedMessage = document.createElement('p');
                uploadedMessage.textContent = `Video '${videoTitle}' added successfully! Video URL: ${videoUrl}`;
                appElement.appendChild(uploadedMessage);
            } else {
                const errorAlert = document.createElement('p');
                errorAlert.textContent = 'Please provide both video title and YouTube video URL.';
                errorAlert.style.color = 'red';
                appElement.appendChild(errorAlert);
            }
        });
        appElement.appendChild(uploadButton);
    }
    </script>
    """,
    unsafe_allow_html=True
)

if __name__ == "__main__":
    main()