Video-Analysis / streamlit_app.py
Matias Macias Gomez
update to add video password options
2c035b6
raw
history blame
4.4 kB
import os
import uuid
import yt_dlp
import string
import ffmpeg
from glob import glob
import streamlit as st
# Config
if "videos" not in st.session_state:
st.session_state["videos"] = ""
if "downloaded" not in st.session_state:
st.session_state["downloaded"] = []
# Callbacks
def _remove_video():
if st.session_state["videos"]:
try:
os.remove(st.session_state["videos"])
st.session_state["videos"] = ""
except FileNotFoundError:
print("Couldn't delete file")
def _remove_all_videos():
videos = (
glob(os.path.join(".", "data", "*.mp4"))
+ glob(os.path.join(".", "data", "*.webm"))
+ glob(os.path.join(".", "data", "*.mov"))
+ glob(os.path.join(".", "data", "*.m4a"))
+ glob(os.path.join(".", "data", "*.mkv"))
)
for video in videos:
try:
os.remove(video)
except FileNotFoundError:
print("Couldn't delete file:", video)
# --- Main Functions ---
def download_video(url: str, save_path: str, **kwargs):
video_id = url.split("/")[-1]
if len(video_id) < 1:
video_id = url.split("/")[-2]
ydl_opts = {
"outtmpl": f"{save_path}/{video_id}.%(ext)s",
}
for opt in kwargs.keys():
ydl_opts[opt] = kwargs[opt]
print(ydl_opts)
if st.session_state["ig_cookie"]:
ydl_opts["cookies"] = st.session_state["ig_cookie"]
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(url)
videos = glob(os.path.join(".", "data", f"{video_id}.*"))
print("videos found:", videos)
for video in videos:
if video_id in video:
video_path = video
converted_video_path = convert_video_to_mp4(video_path)
return converted_video_path
def convert_video_to_mp4(video_path):
target_path = f"{os.path.splitext(video_path)[0]}.mp4"
if not os.path.exists(target_path): # Convert only if target doesn't exist
(ffmpeg.input(video_path).output(target_path).run(overwrite_output=True))
try:
os.remove(video_path)
except FileNotFoundError:
print("Couldn't delete file:", video_path)
return target_path
# --- Streamlit App ---
st.title("Download Any* Video")
# Side bar content
with st.sidebar:
st.subheader("Cookies! :cookie:")
st.write(
"For some websites that have a more strict bot control it's necessary to upload a cookie file to download content from them"
)
st.file_uploader(
label="**Upload Instagram Cookie** :cookie:",
type=["txt", "json"],
accept_multiple_files=False,
key="ig_cookie",
)
st.file_uploader(
label="**Upload TikTok Cookie** :cookie:",
type=["txt", "json"],
accept_multiple_files=False,
key="tt_cookie",
)
st.button(
"Clear Videos",
on_click=_remove_all_videos,
type="secondary",
help="Clear all downloaded videos",
)
# Main content
st.text_input(
"Video URL",
key="url",
placeholder="Enter Video URL and Hit Enter",
on_change=_remove_video,
)
with st.expander("Options", expanded=False):
st.text_input("Video Password", key="video-password", placeholder="Enter Video Password")
if st.session_state["url"]:
download = st.button("Load Video")
if download:
download_options = {}
if st.session_state["video-password"]:
download_options["videopassword"] = st.session_state["video-password"]
video_path = download_video(
st.session_state["url"], save_path=os.path.join(".", "data"), **download_options
)
st.session_state["videos"] = video_path
if st.session_state["videos"]:
st.write("**Title**:", st.session_state["videos"].split("/")[-1])
try:
st.video(st.session_state["videos"])
except Exception as e:
st.write("Couldn't show video")
try:
video_file = open(st.session_state["videos"], "rb")
st.download_button(
"**Download Video ๐Ÿ“**",
data=video_file,
file_name=f"{st.session_state['videos'].lower().translate(str.maketrans('', '', string.punctuation)).replace(' ', '_')}.mp4",
mime="video/mp4",
type="primary",
)
except Exception as e:
st.error("Failed downloading the video", icon="๐Ÿ˜”")