Spaces:
Sleeping
Sleeping
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) | |