youtube / app.py
ahmedJaafari's picture
Update app.py
5215aa8 verified
# prompt: make a gradio app with one input video_url
import json
import requests
import gradio as gr
import os
import requests
URL = f"https://youtube.googleapis.com/youtube/v3/search?part=id&key={os.getenv('SECRET_YTB_TOKEN')}"
def get_channel(URL, channel_name):
URL += f"&q={channel_name}&type=channel"
response = requests.get(URL)
response.raise_for_status()
return response.json()["items"][0]["id"]["channelId"]
def get_videos(URL, channel_id, pageToken=None, maxResults=20):
URL += f"&order=date&maxResults={maxResults}&type=video&channelId={channel_id}"
if pageToken:
URL += f"&pageToken={pageToken}"
response = requests.get(URL)
response.raise_for_status()
return response.json()
def get_all_videos(URL, channel_id):
videos = []
pageToken = None
response = get_videos(URL, channel_id, pageToken)
for item in response["items"]:
videos.append(item["id"]["videoId"])
pageToken = response.get("nextPageToken")
return videos
def submit_video(video_url):
url = os.getenv("URL")
payload = {"video_url": video_url}
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization":
f"Basic {os.getenv('SECRET_TOKEN')}",
"Connection": "keep-alive",
"Content-Type": "application/json"
}
response = requests.request("POST",
url,
headers=headers,
data=json.dumps(payload))
try:
return f"Task Successfully Submited. Task ID: {response.json()['task_id']}"
except:
return "Error"
def submit_job(video_url, channel_id) :
if video_url != "":
return submit_video(video_url)
channel_id = get_channel(URL, channel_id)
results = get_all_videos(URL, channel_id)
for video in results:
submit_video("https://www.youtube.com/watch?v="+video)
return "Channel Successfully Submitted"
demo = gr.Interface(fn=submit_job, inputs=[{"name": "text", "label": "Video URL"}, {"name": "text", "label": "Channel ID"}], outputs=[{"name": "text", "label": "Task ID"}])
demo.launch()