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//clip.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('/') 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)