File size: 3,176 Bytes
18c7580
 
 
1b93e2c
 
 
 
 
18c7580
 
 
 
 
 
1b93e2c
 
 
 
 
18c7580
 
2202041
18c7580
 
2202041
18c7580
 
2202041
18c7580
 
 
 
 
 
 
1b93e2c
18c7580
 
09d03cf
18c7580
2202041
18c7580
 
 
 
1b93e2c
18c7580
 
 
1b93e2c
18c7580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05f8775
 
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
import requests
from bs4 import BeautifulSoup
import gradio as gr
import logging

# Configure logging for debugging purposes
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# Function to search YouTube without using the API
def youtube_search(query, max_results=10):
    # Create the YouTube search URL
    search_url = f"https://www.youtube.com/results?search_query={query.replace(' ', '+')}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
    }

    logging.debug(f"Starting YouTube search for query: {query}")

    try:
        response = requests.get(search_url, headers=headers)
        response.raise_for_status()  # Raise an error for bad status codes

        # Parse the HTML response using BeautifulSoup
        soup = BeautifulSoup(response.text, "html.parser")

        # Find all video entries
        videos = soup.find_all("a", {"href": lambda x: x and "/watch?v=" in x}, limit=max_results)

        gallery_items = []
        for video in videos:
            # Extract details
            video_id = video['href'].split('=')[1]
            video_title = video.get('title', 'No Title')
            video_url = f"https://www.youtube.com{video['href']}"
            thumbnail_url = f"https://i.ytimg.com/vi/{video_id}/hqdefault.jpg"

            # Append video details as a tuple for the gallery display
            gallery_items.append((thumbnail_url, video_title, video_url))

        return gallery_items, ""  # Return the list of gallery items and no error message

    except requests.exceptions.RequestException as e:
        error_message = f"Request error occurred: {e}"
        logging.error(error_message)
        return [], error_message
    except Exception as e:
        error_message = f"An unexpected error occurred: {e}"
        logging.error(error_message)
        return [], error_message

# Function to create a gallery for Gradio
def display_videos(query):
    gallery_items, error_message = youtube_search(query)
    if error_message:
        return gr.update(value=[], label="Error: Unable to fetch videos"), error_message

    # Display thumbnails and titles as gallery items
    formatted_gallery = [(f"<img src='{item[0]}' width='250'/>", f"<a href='{item[2]}' target='_blank'>{item[1]}</a>") for item in gallery_items]
    return formatted_gallery, ""

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("## YouTube Video Search (Without API)")
    with gr.Row():
        with gr.Column(scale=2):
            search_input = gr.Textbox(label="Search YouTube", placeholder="Enter your search query here")
            search_button = gr.Button("Search")
        with gr.Column(scale=4):
            search_output = gr.Gallery(label="Search Results", columns=2)
            error_output = gr.Textbox(label="Error Message", interactive=False, visible=False)

    # Define search button behavior
    search_button.click(display_videos, inputs=search_input, outputs=[search_output, error_output])

# Launch the Gradio interface with public sharing enabled
demo.launch(share=True)