Spaces:
t
Sleeping

t / src /streamlit_app.py
kam3ikaze's picture
Update src/streamlit_app.py
ad69ba9 verified
Raw History Blame Contribute Delete
16.6 kB
import streamlit as st
import yt_dlp
import re
import time
import os
import tempfile
import base64
from io import BytesIO
# تنظيف متغيرات البيئة المتعارضة
import os
os.environ.pop('HF_ENDPOINT', None)
os.environ.pop('HTTP_PROXY', None)
os.environ.pop('HTTPS_PROXY', None)
os.environ.pop('http_proxy', None)
os.environ.pop('https_proxy', None)
os.environ.pop('CURL_CA_BUNDLE', None) # إضافة CURL_CA_BUNDLE
# إعداد الصفحة
st.set_page_config(
page_title="DownKaze - Free Media Downloader",
page_icon="🎬",
layout="centered",
initial_sidebar_state="collapsed"
)
# CSS مخصص للتصميم
st.markdown("""
<style>
/* Fonts */
@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=DM+Mono:wght@400;500&display=swap');
/* Main container */
.main > div {
max-width: 700px;
margin: 0 auto;
}
/* Brand styling */
.brand {
text-align: center;
margin-bottom: 2rem;
}
.brand h1 {
font-family: 'Instrument Serif', serif;
font-size: 4rem;
font-weight: 400;
letter-spacing: -0.03em;
line-height: 1;
color: #3a3a38;
margin-bottom: 0;
}
.brand h1 em {
font-style: italic;
color: #e85d2a;
}
.brand p {
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: #9c9889;
letter-spacing: 0.04em;
text-transform: uppercase;
margin-top: 0.5rem;
}
/* URL textarea */
.stTextArea textarea {
font-family: 'DM Mono', monospace;
font-size: 0.85rem;
border: 1.5px solid #e2ded6;
border-radius: 14px;
}
.stTextArea textarea:focus {
border-color: #e85d2a;
box-shadow: 0 0 0 2px rgba(232, 93, 42, 0.1);
}
/* Hint text */
.hint {
font-family: 'DM Mono', monospace;
font-size: 0.7rem;
color: #9c9889;
margin-top: -0.5rem;
margin-bottom: 1rem;
}
/* Buttons */
.stButton button {
font-family: 'DM Mono', monospace;
font-size: 0.8rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
border-radius: 10px;
transition: all 0.2s ease;
}
.stButton button:active {
transform: scale(0.98);
}
/* Success message */
.success-msg {
background-color: rgba(45, 138, 78, 0.1);
border-left: 3px solid #2d8a4e;
padding: 0.5rem 1rem;
border-radius: 8px;
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: #2d8a4e;
}
/* Error message */
.error-msg {
background-color: rgba(196, 61, 61, 0.05);
border-left: 3px solid #c43d3d;
padding: 0.5rem 1rem;
border-radius: 8px;
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
color: #c43d3d;
}
/* Format pills */
.format-pills {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}
.format-pill {
font-family: 'DM Mono', monospace;
font-size: 0.75rem;
padding: 0.4rem 1.2rem;
border: 1.5px solid #e2ded6;
border-radius: 10px;
background: white;
cursor: pointer;
transition: all 0.2s;
text-transform: uppercase;
}
.format-pill.active {
background: #3a3a38;
color: #f4f1eb;
border-color: #3a3a38;
}
/* Footer */
.footer {
margin-top: 3rem;
text-align: center;
font-family: 'DM Mono', monospace;
font-size: 0.65rem;
color: #9c9889;
text-transform: uppercase;
letter-spacing: 0.05em;
line-height: 1.8;
border-top: 1px solid #e2ded6;
padding-top: 2rem;
}
/* Spinner animation */
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
display: inline-block;
width: 12px;
height: 12px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
vertical-align: middle;
margin-right: 8px;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'downloads' not in st.session_state:
st.session_state.downloads = []
if 'format' not in st.session_state:
st.session_state.format = 'video'
def parse_urls(text):
"""Parse URLs from text input"""
urls = re.split(r'[\s,]+', text.strip())
return [u for u in urls if u.startswith('http')]
def get_video_info(url):
"""Get video information using yt-dlp"""
ydl_opts = {
'quiet': True,
'no_warnings': True,
'extract_flat': False,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
# Extract available formats
formats = []
seen_heights = set()
for f in info.get('formats', []):
height = f.get('height')
if height and height not in seen_heights:
seen_heights.add(height)
formats.append({
'format_id': f['format_id'],
'label': f"{height}p",
'height': height,
'ext': f.get('ext', 'mp4')
})
# Sort by height descending
formats.sort(key=lambda x: x['height'], reverse=True)
return {
'success': True,
'title': info.get('title', 'Untitled'),
'thumbnail': info.get('thumbnail', ''),
'duration': info.get('duration'),
'uploader': info.get('uploader', 'Unknown'),
'formats': formats,
'url': url
}
except Exception as e:
error_msg = str(e)
# Friendly error messages
if 'Unsupported URL' in error_msg:
error_msg = '❌ This URL format is not supported'
elif 'Private video' in error_msg:
error_msg = '🔒 This video is private'
elif 'Video unavailable' in error_msg:
error_msg = '🚫 Video is unavailable or has been removed'
elif 'copyright' in error_msg.lower():
error_msg = '©️ Video blocked due to copyright'
elif 'geo' in error_msg.lower():
error_msg = '🌍 Video not available in your region'
elif 'timed out' in error_msg.lower():
error_msg = '⏱️ Request timed out — please try again'
elif 'network' in error_msg.lower():
error_msg = '🌐 Network error — check your connection'
return {
'success': False,
'error': error_msg,
'url': url
}
def download_media(url, format_type, format_id=None, title=""):
"""Download media using yt-dlp"""
with tempfile.TemporaryDirectory() as temp_dir:
output_template = os.path.join(temp_dir, '%(title)s.%(ext)s')
ydl_opts = {
'quiet': True,
'no_warnings': True,
'outtmpl': output_template,
'noplaylist': True,
}
if format_type == 'audio':
ydl_opts.update({
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
})
elif format_id:
ydl_opts['format'] = f"{format_id}+bestaudio/best"
else:
ydl_opts['format'] = 'bestvideo+bestaudio/best'
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
# Find the downloaded file
for file in os.listdir(temp_dir):
filepath = os.path.join(temp_dir, file)
if os.path.isfile(filepath):
with open(filepath, 'rb') as f:
return {
'success': True,
'data': f.read(),
'filename': file,
'title': info.get('title', title)
}
return {'success': False, 'error': 'No file was generated'}
except Exception as e:
return {'success': False, 'error': str(e)}
# Brand header
st.markdown("""
<div class="brand">
<h1>Down<em>Kaze</em></h1>
<p>Free media downloader</p>
</div>
""", unsafe_allow_html=True)
# URL input
url_input = st.text_area(
"",
placeholder="Paste one or more URLs...\nExample: https://youtube.com/watch?v=...",
height=100,
key="url_input"
)
st.markdown('<p class="hint">💡 Multiple links? Separate with spaces, commas, or newlines.</p>', unsafe_allow_html=True)
# Format selector
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
format_choice = st.radio(
"Format",
["🎥 Video (MP4)", "🎵 Audio (MP3)"],
horizontal=True,
label_visibility="collapsed",
key="format_radio"
)
st.session_state.format = 'audio' if 'Audio' in format_choice else 'video'
# Fetch button
if st.button("🔍 Fetch Media", type="primary", use_container_width=True):
urls = parse_urls(url_input)
if not urls:
st.markdown('<p class="error-msg">❌ Please enter at least one valid URL</p>', unsafe_allow_html=True)
else:
with st.spinner("📡 Fetching video information..."):
st.session_state.downloads = []
for url in urls:
info = get_video_info(url)
st.session_state.downloads.append(info)
st.rerun()
# Display downloads
if st.session_state.downloads:
st.markdown("---")
for idx, download in enumerate(st.session_state.downloads):
if not download['success']:
# Error card
st.markdown(f"""
<div style="border: 1.5px solid #e2ded6; border-radius: 14px; background: white; padding: 1rem; margin-bottom: 0.75rem;">
<div style="display: flex; gap: 1rem; align-items: center;">
<div style="min-width: 60px; height: 60px; background: rgba(196,61,61,0.08); border-radius: 8px; display: flex; align-items: center; justify-content: center;">
<span style="font-size: 1.5rem;">⚠️</span>
</div>
<div style="flex: 1;">
<div style="font-family: 'Instrument Serif', serif; font-size: 1rem; color: #c43d3d;">Failed to fetch</div>
<div style="font-family: 'DM Mono', monospace; font-size: 0.7rem; color: #c43d3d;">{download['error']}</div>
<div style="font-family: 'DM Mono', monospace; font-size: 0.65rem; color: #9c9889; word-break: break-all;">{download['url'][:60]}...</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
continue
# Success card
duration_str = ""
if download.get('duration'):
mins = int(download['duration'] // 60)
secs = int(download['duration'] % 60)
duration_str = f" · {mins}:{secs:02d}"
with st.expander(f"📹 {download['title'][:80]}", expanded=True):
col1, col2 = st.columns([1, 2])
with col1:
if st.session_state.format == 'audio':
st.markdown("""
<div style="background: rgba(232,93,42,0.08); border-radius: 12px; padding: 1rem; text-align: center;">
<span style="font-size: 2rem;">🎵</span>
<p style="font-family: monospace; font-size: 0.7rem; margin-top: 0.5rem;">Audio Mode</p>
</div>
""", unsafe_allow_html=True)
else:
if download.get('thumbnail'):
st.image(download['thumbnail'], use_container_width=True)
else:
st.markdown("""
<div style="background: #e2ded6; border-radius: 12px; padding: 2rem; text-align: center;">
<span style="font-size: 2rem;">🎬</span>
<p style="font-family: monospace; font-size: 0.7rem;">No preview available</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown(f"### {download['title']}")
st.caption(f"👤 {download['uploader']}{duration_str}")
# Quality selector for video
selected_format_id = None
if st.session_state.format == 'video' and download.get('formats'):
quality_options = {f"{f['label']}": f["format_id"] for f in download['formats']}
selected_label = st.selectbox(
"Select Quality",
options=list(quality_options.keys()),
key=f"quality_{idx}"
)
selected_format_id = quality_options[selected_label]
# Download button for this item
if st.button(f"⬇️ Download", key=f"download_{idx}", use_container_width=True):
with st.spinner(f"Downloading {download['title'][:50]}..."):
result = download_media(
download['url'],
st.session_state.format,
selected_format_id,
download['title']
)
if result['success']:
st.markdown('<div class="success-msg">✅ Download complete!</div>', unsafe_allow_html=True)
# Provide download button
b64 = base64.b64encode(result['data']).decode()
href = f'<a href="data:application/octet-stream;base64,{b64}" download="{result["filename"]}" style="display: inline-block; background: #2d8a4e; color: white; padding: 10px 20px; border-radius: 10px; text-decoration: none; font-family: monospace; margin-top: 10px; text-align: center; width: 100%;">💾 Save File ({result["filename"]})</a>'
st.markdown(href, unsafe_allow_html=True)
else:
st.markdown(f'<div class="error-msg">❌ Download failed: {result["error"][:100]}</div>', unsafe_allow_html=True)
# Download All button
ready_downloads = [d for d in st.session_state.downloads if d.get('success')]
if len(ready_downloads) > 1:
st.markdown("---")
if st.button("📦 Download All", use_container_width=True):
for idx, download in enumerate(ready_downloads):
with st.spinner(f"Downloading {idx + 1}/{len(ready_downloads)}: {download['title'][:40]}..."):
result = download_media(
download['url'],
st.session_state.format,
None,
download['title']
)
if result['success']:
st.success(f"✅ {download['title'][:40]} downloaded")
b64 = base64.b64encode(result['data']).decode()
href = f'<a href="data:application/octet-stream;base64,{b64}" download="{result["filename"]}">💾 Save {result["filename"]}</a>'
st.markdown(href, unsafe_allow_html=True)
else:
st.error(f"❌ Failed: {download['title'][:40]}")
st.balloons()
st.success("🎉 All downloads completed!")
# Footer
st.markdown("""
<div class="footer">
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook · Vimeo · Twitch<br>
Dailymotion · SoundCloud · Loom · Streamable · Pinterest · Tumblr · LinkedIn<br>
<strong>1000+ supported platforms</strong>
</div>
""", unsafe_allow_html=True)