Spaces:
Configuration error

File size: 3,305 Bytes
720222a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

from flask import Flask, request, jsonify, send_from_directory, abort
import os, subprocess, uuid, shlex

app = Flask(__name__, static_folder='../frontend/build', static_url_path='/')

WORK = 'work'
os.makedirs(WORK, exist_ok=True)

PASSWORD = os.environ.get('PRIVATE_PASSWORD', '12345')

def run(cmd):
    print('> RUN:', cmd)
    res = subprocess.run(cmd, shell=True)
    if res.returncode != 0:
        raise RuntimeError(f'Command failed: {cmd} (rc={res.returncode})')

def get_direct_url(youtube_url):
    out = subprocess.check_output(['yt-dlp', '-g', youtube_url]).decode().strip().splitlines()
    if not out:
        raise RuntimeError('yt-dlp failed to extract media URL')
    return out[0]

@app.route('/api/process', methods=['POST'])
def process():
    data = request.json or {}
    if data.get('password') != PASSWORD:
        return jsonify({'error':'wrong password'}), 401
    url = data.get('youtube')
    if not url:
        return jsonify({'error':'no url provided'}), 400
    try:
        seconds = int(data.get('seconds', 12))
        clips = int(data.get('clips', 3))
    except:
        return jsonify({'error':'invalid seconds/clips'}), 400

    job = str(uuid.uuid4())
    outdir = os.path.join(WORK, job)
    os.makedirs(outdir, exist_ok=True)

    try:
        media_url = get_direct_url(url)
    except Exception as e:
        return jsonify({'error':'yt-dlp failed: ' + str(e)}), 500

    # try to probe duration (may fail for some streams)
    try:
        probe = subprocess.check_output([
            'ffprobe','-v','error','-show_entries','format=duration',
            '-of','default=noprint_wrappers=1:nokey=1', media_url
        ])
        duration = float(probe.decode().strip())
    except Exception:
        duration = clips * seconds * 1.0

    step = max(1, duration / clips)
    clips_list = []
    for i in range(clips):
        start = int(i * step)
        length = seconds
        out_clip = os.path.join(outdir, f'clip{i}.mp4')
        # stream-trim and transcode to TikTok 9:16 (1080x1920)
        vf = "scale=1080:-2, crop=1080:1920"
        cmd = (
            f"ffmpeg -y -ss {start} -t {length} -i {shlex.quote(media_url)} "
            f"-vf \"{vf}\" -c:v libx264 -preset veryfast -crf 23 -c:a aac -movflags +faststart {shlex.quote(out_clip)}"
        )
        try:
            run(cmd)
        except Exception as e:
            return jsonify({'error': f'ffmpeg failed for clip {i}: {e}'}), 500
        clips_list.append(f"/api/download/{job}/clip{i}.mp4")
    return jsonify({'clips': clips_list, 'job': job})

@app.route('/api/download/<job>/clip<int:i>.mp4')
def download_clip(job, i):
    folder = os.path.join(WORK, job)
    path = os.path.join(folder, f'clip{i}.mp4')
    if not os.path.exists(path):
        return jsonify({'error':'not found'}), 404
    return send_from_directory(folder, f'clip{i}.mp4', as_attachment=True)

# serve React app
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists(os.path.join(app.static_folder, path)):
        return send_from_directory(app.static_folder, path)
    return send_from_directory(app.static_folder, 'index.html')

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 7860))
    app.run(host='0.0.0.0', port=port)