File size: 1,524 Bytes
f774908
 
477d36a
f774908
477d36a
f774908
 
 
86b1a8c
f774908
86b1a8c
f774908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
from dotenv import load_dotenv
import os 
load_dotenv()


# API Setup
API_URL = "https://youtube138.p.rapidapi.com/search/"
HEADERS = {
    "x-rapidapi-key": os.getenv("Rapidapi"),
    "x-rapidapi-host": "youtube138.p.rapidapi.com"
}

# Core function
def search_youtube(query: str) -> str:
    params = {"q": query, "hl": "en", "gl": "US"}
    try:
        response = requests.get(API_URL, headers=HEADERS, params=params)
        response.raise_for_status()
        data = response.json()

        # Extract top 5 video titles + links
        videos = data.get("contents", [])
        results = []
        for video in videos:
            if "video" in video:
                v = video["video"]
                title = v.get("title", "")
                video_id = v.get("videoId", "")
                link = f"https://www.youtube.com/watch?v={video_id}"
                results.append(f"{title}\n{link}\n")
            if len(results) >= 5:
                break

        return "\n".join(results) if results else "No videos found."
    except Exception as e:
        return f"Error: {str(e)}"

# Gradio Interface
demo = gr.Interface(
    fn=search_youtube,
    inputs=gr.Textbox(placeholder="Enter search term...", label="YouTube Query"),
    outputs=gr.Textbox(label="Top 5 Results"),
    title="YouTube Search Tool",
    description="Search YouTube videos using the YouTube138 API (via RapidAPI)"
)

# MCP-compatible launch
if __name__ == "__main__":
    demo.launch(mcp_server=True)