File size: 3,416 Bytes
8a86c2c
 
 
 
 
f106ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from waitress import serve
import os

# Hugging Face Spaces configuration
port = int(os.environ.get("PORT", 7860))
from flask import Flask, render_template, request, send_file, jsonify
from pytube import YouTube
from yt_dlp import YoutubeDL
import instaloader
import os
import uuid
import shutil

app = Flask(__name__)

# Create downloads directory if it doesn't exist
if not os.path.exists('downloads'):
    os.makedirs('downloads')

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/download', methods=['POST'])
def download():
    url = request.form.get('url')
    if not url:
        return jsonify({'error': 'No URL provided'}), 400

    try:
        if 'youtube.com' in url or 'youtu.be' in url:
            return download_youtube(url)
        elif 'instagram.com' in url:
            return download_instagram(url)
        elif 'tiktok.com' in url:
            return download_tiktok(url)
        else:
            return jsonify({'error': 'Unsupported platform'}), 400
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def download_youtube(url):
    try:
        yt = YouTube(url)
        stream = yt.streams.get_highest_resolution()
        filename = f"youtube_{uuid.uuid4().hex}.mp4"
        filepath = os.path.join('downloads', filename)
        stream.download(output_path='downloads', filename=filename)
        return send_file(filepath, as_attachment=True)
    except Exception as e:
        return jsonify({'error': f'YouTube download error: {str(e)}'}), 500

def download_instagram(url):
    try:
        L = instaloader.Instaloader()
        temp_dir = f"downloads/insta_{uuid.uuid4().hex}"
        os.makedirs(temp_dir, exist_ok=True)

        if "/reel/" in url:
            shortcode = url.split("/reel/")[1].split("/")[0]
        elif "/p/" in url:
            shortcode = url.split("/p/")[1].split("/")[0]
        else:
            raise ValueError("Invalid Instagram URL")

        post = instaloader.Post.from_shortcode(L.context, shortcode)
        L.download_post(post, target=temp_dir)

        for file in os.listdir(temp_dir):
            if file.endswith('.mp4'):
                filepath = os.path.join(temp_dir, file)
                return send_file(filepath, as_attachment=True)

        raise Exception("No video found")
    except Exception as e:
        return jsonify({'error': f'Instagram download error: {str(e)}'}), 500
    finally:
        if os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)

def download_tiktok(url):
    try:
        filename = f"tiktok_{uuid.uuid4().hex}.mp4"
        filepath = os.path.join('downloads', filename)
        
        ydl_opts = {
            'format': 'best',
            'outtmpl': filepath,
            'quiet': True
        }
        
        with YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            return send_file(filepath, as_attachment=True)
    except Exception as e:
        return jsonify({'error': f'TikTok download error: {str(e)}'}), 500

@app.after_request
def cleanup(response):
    # Clean up downloads directory
    for file in os.listdir('downloads'):
        filepath = os.path.join('downloads', file)
        try:
            if os.path.isfile(filepath):
                os.remove(filepath)
        except Exception:
            pass
    return response

if __name__ == "__main__":
    serve(app, host="0.0.0.0", port=port)