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(""" """, 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("""
Free media downloader
💡 Multiple links? Separate with spaces, commas, or newlines.
', 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('❌ Please enter at least one valid URL
', 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"""Audio Mode
No preview available