Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
192 lines (165 loc) · 7.26 KB
/
Copy pathmain.py
File metadata and controls
192 lines (165 loc) · 7.26 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from flask import Flask, request, jsonify, send_file
import subprocess, requests, base64, os, tempfile, shutil, math
app = Flask(__name__)
CHUNK = 1024 * 1024 # 1 MB
DOWNLOAD_TIMEOUT = 180 # seconds
def stream_download(url, dest_path):
"""Download a URL to disk in chunks so the whole file never sits in RAM."""
with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT) as r:
r.raise_for_status()
with open(dest_path, "wb") as f:
for chunk in r.iter_content(chunk_size=CHUNK):
if chunk:
f.write(chunk)
def probe_duration(path):
try:
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", path],
capture_output=True, text=True)
return float(out.stdout.strip())
except Exception:
return 0.0
def probe_dims(path):
try:
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=s=x:p=0", path],
capture_output=True, text=True)
w, h = out.stdout.strip().split("x")
return int(w), int(h)
except Exception:
return 1080, 1920
def _ass_time(t):
if t < 0:
t = 0
cs = int(round(t * 100))
h = cs // 360000; cs %= 360000
m = cs // 6000; cs %= 6000
s = cs // 100; cs %= 100
return "%d:%02d:%02d.%02d" % (h, m, s, cs)
def build_ass(text, dur, w, h, words_per_cue=3):
"""Build an .ass subtitle string, spreading the text across the duration."""
text = " ".join(str(text).split()).replace("{", "(").replace("}", ")")
words = [x for x in text.split(" ") if x]
cues = [" ".join(words[i:i + words_per_cue]) for i in range(0, len(words), words_per_cue)]
if not cues:
cues = [""]
if dur <= 0:
dur = 30.0
total = sum(max(1, len(c)) for c in cues)
fs = max(30, int(h * 0.046))
outline = max(2, int(h * 0.0045))
marginv = max(40, int(h * 0.13))
head = (
"[Script Info]\n"
"ScriptType: v4.00+\n"
"PlayResX: %d\nPlayResY: %d\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n"
"[V4+ Styles]\n"
"Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, "
"Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
"Style: Def,DejaVu Sans,%d,&H00FFFFFF,&H00000000,&H80000000,1,0,1,%d,2,2,60,60,%d,1\n\n"
"[Events]\n"
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, Effect, Text\n"
% (w, h, fs, outline, marginv)
)
lines, t = [], 0.0
for c in cues:
d = dur * (max(1, len(c)) / total)
st, en = t, t + d
t = en
lines.append("Dialogue: 0,%s,%s,Def,,0,0,0,,%s" % (_ass_time(st), _ass_time(en), c))
return head + "\n".join(lines) + "\n"
@app.route("/", methods=["GET"])
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok"})
@app.route("/merge", methods=["POST"])
def merge():
data = request.get_json(force=True, silent=True) or {}
video_url = data.get("video_url")
audio_url = data.get("audio_url")
audio_base64 = data.get("audio_base64")
subtitle_text = data.get("subtitle_text") # optional: burn captions
resp_format = (data.get("format") or "base64").lower()
if not video_url or (not audio_url and not audio_base64):
return jsonify({
"error": "eksik alan: 'video_url' ve ('audio_url' veya 'audio_base64') gerekli",
"received_keys": list(data.keys()),
}), 400
tmpdir = tempfile.mkdtemp()
video_path = os.path.join(tmpdir, "video.mp4")
audio_path = os.path.join(tmpdir, "audio.input")
subs_path = os.path.join(tmpdir, "subs.ass")
output_path = os.path.join(tmpdir, "output.mp4")
def cleanup():
shutil.rmtree(tmpdir, ignore_errors=True)
try:
# 1) Inputs -> disk (streamed)
try:
stream_download(video_url, video_path)
except Exception as e:
cleanup(); return jsonify({"error": f"video indirilemedi: {e}"}), 502
if audio_url:
try:
stream_download(audio_url, audio_path)
except Exception as e:
cleanup(); return jsonify({"error": f"ses indirilemedi: {e}"}), 502
else:
try:
with open(audio_path, "wb") as f:
f.write(base64.b64decode(audio_base64))
except Exception as e:
cleanup(); return jsonify({"error": f"audio_base64 cozulemedi: {e}"}), 400
# 2) Build the ffmpeg command. Loop the (short) video a FINITE number of
# times to comfortably cover the audio, then -shortest trims to audio.
# Infinite -stream_loop -1 + filter_complex + -shortest can deadlock.
adur = probe_duration(audio_path)
vdur = probe_duration(video_path)
loops = 4
if adur > 0 and vdur > 0:
loops = max(0, int(math.ceil(adur / vdur)))
if subtitle_text:
# Burn captions -> must re-encode the video
w, h = probe_dims(video_path)
with open(subs_path, "w", encoding="utf-8") as f:
f.write(build_ass(subtitle_text, adur, w, h))
scale = ("[0:v]scale='min(1080,iw)':'min(1920,ih)':"
"force_original_aspect_ratio=decrease:force_divisible_by=2,"
"ass=%s[v]" % subs_path)
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-nostats",
"-stream_loop", str(loops), "-i", video_path,
"-i", audio_path,
"-filter_complex", scale,
"-map", "[v]", "-map", "1:a:0",
"-c:v", "libx264", "-preset", "ultrafast", "-crf", "23",
"-pix_fmt", "yuv420p", "-threads", "2",
"-c:a", "aac", "-b:a", "128k",
"-movflags", "+faststart", "-shortest", output_path]
else:
# No captions -> fast stream copy (no re-encode)
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-nostats",
"-stream_loop", str(loops), "-i", video_path,
"-i", audio_path,
"-map", "0:v:0", "-map", "1:a:0",
"-c:v", "copy", "-c:a", "aac", "-b:a", "128k",
"-movflags", "+faststart", "-shortest", output_path]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0 or not os.path.exists(output_path):
tail = (proc.stderr or "")[-1500:]
cleanup(); return jsonify({"error": "ffmpeg basarisiz", "ffmpeg_stderr": tail}), 500
# 3) Return
if resp_format == "base64":
with open(output_path, "rb") as f:
video_b64 = base64.b64encode(f.read()).decode()
cleanup()
return jsonify({"video": video_b64})
resp = send_file(output_path, mimetype="video/mp4",
as_attachment=True, download_name="output.mp4")
resp.call_on_close(cleanup)
return resp
except Exception as e:
cleanup()
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))