youtube-search / app.py
adarshajay's picture
Update app.py
716a0a3 verified
raw
history blame
2.83 kB
import gradio as gr
import requests
import numpy as np
import os
from pathlib import Path
from PIL import Image
from dotenv import load_dotenv
load_dotenv()
# YouTube Tool
API_URL = "https://youtube138.p.rapidapi.com/search/"
HEADERS = {
"x-rapidapi-key": os.getenv("Rapidapi"),
"x-rapidapi-host": "youtube138.p.rapidapi.com"
}
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()
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)}"
# Other Tools
def prime_factors(n):
n = int(n)
if n <= 1:
raise ValueError("Input must be an integer greater than 1.")
factors = []
while n % 2 == 0:
factors.append(2)
n //= 2
divisor = 3
while divisor * divisor <= n:
while n % divisor == 0:
factors.append(divisor)
n //= divisor
divisor += 2
if n > 1:
factors.append(n)
return factors
def generate_cheetah_image():
return Path(os.path.dirname(__file__)) / "cheetah.jpg"
def image_orientation(image: Image.Image) -> str:
return "Portrait" if image.height > image.width else "Landscape"
def sepia(input_img):
sepia_filter = np.array([
[0.393, 0.769, 0.189],
[0.349, 0.686, 0.168],
[0.272, 0.534, 0.131]
])
sepia_img = np.array(input_img).dot(sepia_filter.T)
sepia_img /= sepia_img.max()
return sepia_img
# Tabbed Tool Interface
demo = gr.TabbedInterface(
[
gr.Interface(search_youtube, gr.Textbox(label="YouTube Query"), gr.Textbox(label="Top 5 Results"), api_name="youtube_search"),
gr.Interface(prime_factors, gr.Textbox(), gr.Textbox(), api_name="prime_factors"),
gr.Interface(generate_cheetah_image, None, gr.Image(), api_name="generate_cheetah_image"),
gr.Interface(image_orientation, gr.Image(type="pil"), gr.Textbox(), api_name="image_orientation"),
gr.Interface(sepia, gr.Image(), gr.Image(), api_name="sepia"),
],
[
"YouTube Search",
"Prime Factors",
"Cheetah Image",
"Image Orientation Checker",
"Sepia Filter",
]
)
if __name__ == "__main__":
demo.launch(mcp_server=True)