studio / app-backup6.py
seawolf2357's picture
Update app-backup6.py
1a0b15a verified
raw
history blame
35.3 kB
"""
Simple Video Editor - Canvas ๊ธฐ๋ฐ˜ ๋ Œ๋”๋ง
๋นˆ ํ”„๋ ˆ์ž„ ๋ฌธ์ œ ์™„์ „ ํ•ด๊ฒฐ + ์„œ๋ฒ„ ์‚ฌ์ด๋“œ MP4 ๋‚ด๋ณด๋‚ด๊ธฐ
"""
import gradio as gr
import base64
import os
import json
import subprocess
import tempfile
import shutil
import time
# ์„œ๋ฒ„ ์‚ฌ์ด๋“œ MP4 ๋‚ด๋ณด๋‚ด๊ธฐ์šฉ
UPLOAD_DIR = tempfile.mkdtemp()
uploaded_files = {} # {filename: filepath}
def get_editor_html(media_data="[]"):
return f'''<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<style>
*{{margin:0;padding:0;box-sizing:border-box}}
body{{font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#f5f5f7;font-size:13px}}
.editor{{display:flex;flex-direction:column;height:100vh}}
.toolbar{{height:44px;background:#fff;border-bottom:1px solid #ddd;display:flex;align-items:center;justify-content:space-between;padding:0 12px}}
.toolbar-title{{font-size:15px;font-weight:600}}
.btn{{padding:5px 10px;border:none;border-radius:5px;cursor:pointer;font-size:11px;font-weight:500}}
.btn-secondary{{background:#f0f0f0;color:#333}}
.btn-secondary:hover{{background:#e0e0e0}}
.btn-success{{background:#10b981;color:#fff}}
.btn-danger{{background:#ef4444;color:#fff}}
.main{{display:flex;flex:1;overflow:hidden}}
.library{{width:160px;background:#fff;border-right:1px solid #ddd;display:flex;flex-direction:column}}
.lib-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
.lib-content{{flex:1;overflow-y:auto;padding:6px}}
.lib-hint{{text-align:center;padding:15px;color:#999;font-size:10px}}
.media-grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:4px}}
.media-item{{aspect-ratio:16/9;background:#f0f0f0;border-radius:4px;overflow:hidden;cursor:grab;position:relative;border:1px solid #e0e0e0}}
.media-item:hover{{border-color:#6366f1}}
.media-item img{{width:100%;height:100%;object-fit:cover}}
.media-item-icon{{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:18px}}
.media-item-dur{{position:absolute;top:2px;right:2px;background:rgba(0,0,0,0.7);padding:1px 3px;border-radius:2px;font-size:8px;color:#fff}}
.preview-area{{flex:1;display:flex;flex-direction:column;background:#1a1a1a;margin:6px;border-radius:8px;overflow:hidden}}
.preview-box{{flex:1;display:flex;align-items:center;justify-content:center;background:#000}}
#previewCanvas{{max-width:100%;max-height:100%;background:#000}}
.controls{{height:45px;background:#222;display:flex;align-items:center;justify-content:center;gap:6px}}
.ctrl-btn{{width:28px;height:28px;border:none;border-radius:50%;background:rgba(255,255,255,0.1);color:#fff;cursor:pointer;font-size:12px}}
.ctrl-btn:hover{{background:rgba(255,255,255,0.2)}}
.ctrl-btn.play{{width:36px;height:36px;background:#6366f1}}
.time-display{{font-family:monospace;font-size:10px;color:#aaa;min-width:90px;text-align:center}}
.props{{width:140px;background:#fff;border-left:1px solid #ddd}}
.props-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
.props-content{{padding:8px}}
.no-sel{{color:#999;text-align:center;padding:15px;font-size:10px}}
.prop-group{{margin-bottom:10px}}
.prop-label{{font-size:9px;color:#666;margin-bottom:2px}}
.prop-input{{width:100%;padding:4px;border:1px solid #ddd;border-radius:3px;font-size:10px}}
.timeline{{height:140px;background:#fff;border-top:1px solid #ddd;display:flex;flex-direction:column}}
.tl-toolbar{{height:28px;background:#fafafa;border-bottom:1px solid #eee;display:flex;align-items:center;padding:0 6px;gap:4px}}
.tl-toolbar .btn{{padding:2px 6px;font-size:9px}}
.tl-zoom{{display:flex;align-items:center;gap:3px;margin-left:auto;font-size:9px;color:#666}}
.tl-zoom input{{width:50px}}
.tl-container{{flex:1;overflow-x:auto;position:relative}}
.tl-ruler{{height:18px;background:#fff;border-bottom:1px solid #eee}}
.tl-tracks{{position:relative}}
.tl-track{{height:45px;border-bottom:1px solid #eee;display:flex}}
.tl-track:nth-child(2){{background:#fffbeb}}
.track-label{{width:50px;padding:0 4px;font-size:8px;color:#666;background:#fafafa;display:flex;align-items:center;border-right:1px solid #eee}}
.track-content{{flex:1;position:relative;min-width:600px}}
.clip{{position:absolute;height:36px;top:4px;border-radius:4px;cursor:grab;display:flex;align-items:center;overflow:hidden}}
.clip:hover{{box-shadow:0 0 0 2px #6366f1}}
.clip.selected{{box-shadow:0 0 0 2px #6366f1}}
.clip.video{{background:linear-gradient(135deg,#818cf8,#6366f1)}}
.clip.image{{background:linear-gradient(135deg,#34d399,#10b981)}}
.clip.audio{{background:linear-gradient(135deg,#fbbf24,#f59e0b)}}
.clip-thumb{{width:36px;height:100%;object-fit:cover}}
.clip-info{{padding:0 4px;flex:1;overflow:hidden}}
.clip-name{{font-size:8px;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
.clip-dur{{font-size:7px;color:rgba(255,255,255,0.7)}}
.clip-handle{{position:absolute;top:0;bottom:0;width:8px;background:rgba(255,255,255,0.5);cursor:ew-resize;opacity:0}}
.clip:hover .clip-handle{{opacity:1}}
.clip-handle-l{{left:0;border-radius:4px 0 0 4px}}
.clip-handle-r{{right:0;border-radius:0 4px 4px 0}}
.playhead{{position:absolute;top:0;bottom:0;width:2px;background:#ef4444;z-index:10;pointer-events:none}}
.playhead::before{{content:"";position:absolute;top:0;left:-4px;border-left:5px solid transparent;border-right:5px solid transparent;border-top:7px solid #ef4444}}
.drop-zone{{background:rgba(99,102,241,0.1)!important;outline:2px dashed #6366f1!important}}
.status{{height:20px;background:#f5f5f5;border-top:1px solid #ddd;display:flex;align-items:center;padding:0 8px;font-size:9px;color:#666}}
.ctx-menu{{position:fixed;background:#fff;border:1px solid #ddd;border-radius:5px;padding:3px 0;min-width:100px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);display:none}}
.ctx-item{{padding:5px 10px;cursor:pointer;font-size:10px}}
.ctx-item:hover{{background:#f5f5f5}}
.ctx-item.danger{{color:#ef4444}}
.modal{{position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:1000}}
.modal-box{{background:#fff;border-radius:8px;padding:16px;min-width:240px;text-align:center}}
.modal-box h3{{margin-bottom:8px;font-size:13px}}
.progress{{height:5px;background:#eee;border-radius:3px;overflow:hidden;margin:10px 0}}
.progress-bar{{height:100%;background:#6366f1;transition:width 0.2s}}
.hidden-media{{position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0;pointer-events:none}}
</style>
</head>
<body>
<div class="editor">
<div class="toolbar">
<div class="toolbar-title">๐ŸŽฌ Video Editor</div>
<div style="display:flex;gap:4px">
<button class="btn btn-secondary" onclick="undo()">โ†ฉ ์‹คํ–‰์ทจ์†Œ</button>
<button class="btn btn-success" onclick="exportVideo()">๐Ÿ“ฅ ๋‚ด๋ณด๋‚ด๊ธฐ</button>
</div>
</div>
<div class="main">
<div class="library">
<div class="lib-header">๐Ÿ“ ๋ฏธ๋””์–ด</div>
<div class="lib-content">
<div class="lib-hint" id="hint">ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜์„ธ์š”</div>
<div class="media-grid" id="mediaGrid"></div>
</div>
</div>
<div class="preview-area">
<div class="preview-box">
<canvas id="previewCanvas" width="640" height="360"></canvas>
</div>
<div class="controls">
<button class="ctrl-btn" onclick="seek(0)">โฎ</button>
<button class="ctrl-btn" onclick="seek(S.time-5)">โช</button>
<button class="ctrl-btn play" onclick="togglePlay()" id="playBtn">โ–ถ</button>
<button class="ctrl-btn" onclick="seek(S.time+5)">โฉ</button>
<button class="ctrl-btn" onclick="seek(S.dur)">โญ</button>
<div class="time-display"><span id="curT">00:00.00</span> / <span id="totT">00:00.00</span></div>
<button class="ctrl-btn" onclick="toggleMute()" id="muteBtn">๐Ÿ”Š</button>
</div>
</div>
<div class="props">
<div class="props-header">โš™๏ธ ์†์„ฑ</div>
<div class="props-content" id="propsBox"><div class="no-sel">ํด๋ฆฝ ์„ ํƒ</div></div>
</div>
</div>
<div class="timeline">
<div class="tl-toolbar">
<button class="btn btn-secondary" onclick="splitClip()">โœ‚ ์ž๋ฅด๊ธฐ</button>
<button class="btn btn-secondary" onclick="dupeClip()">๐Ÿ“‹ ๋ณต์ œ</button>
<button class="btn btn-danger" onclick="delClip()">๐Ÿ—‘ ์‚ญ์ œ</button>
<div class="tl-zoom">๐Ÿ”<input type="range" min="0.5" max="3" step="0.1" value="1" oninput="setZoom(this.value)"></div>
</div>
<div class="tl-container" id="tlBox" onclick="tlClick(event)">
<div class="tl-ruler" id="ruler"></div>
<div class="tl-tracks">
<div class="tl-track"><div class="track-label">๐ŸŽฌ ์˜์ƒ</div><div class="track-content" id="t0"></div></div>
<div class="tl-track"><div class="track-label">๐ŸŽต ์˜ค๋””์˜ค</div><div class="track-content" id="t1"></div></div>
</div>
<div class="playhead" id="playhead" style="left:50px"></div>
</div>
</div>
<div class="status" id="status">์ค€๋น„๋จ</div>
</div>
<div class="ctx-menu" id="ctx">
<div class="ctx-item" onclick="splitClip()">โœ‚ ์ž๋ฅด๊ธฐ</div>
<div class="ctx-item" onclick="dupeClip()">๐Ÿ“‹ ๋ณต์ œ</div>
<div class="ctx-item danger" onclick="delClip()">๐Ÿ—‘ ์‚ญ์ œ</div>
</div>
<div class="modal" id="exportModal" style="display:none">
<div class="modal-box">
<h3>๐ŸŽฌ ์˜์ƒ ๋‚ด๋ณด๋‚ด๊ธฐ</h3>
<p id="exportMsg">์ค€๋น„์ค‘...</p>
<div class="progress"><div class="progress-bar" id="exportBar"></div></div>
<button class="btn btn-secondary" onclick="cancelExport()">์ทจ์†Œ</button>
</div>
</div>
<div id="hiddenMedia" class="hidden-media"></div>
<script>
var S={{
media:[],
clips:[],
sel:null,
playing:false,
muted:false,
time:0,
dur:0,
zoom:1,
pps:80,
history:[],
animId:null,
cancelled:false,
els:{{}},
canvas:null,
ctx:null,
lastClipId:null
}};
function init(){{
S.canvas=document.getElementById('previewCanvas');
S.ctx=S.canvas.getContext('2d');
drawPlaceholder();
}}
function id(){{return Math.random().toString(36).substr(2,9)}}
function fmt(t){{if(!t||isNaN(t))t=0;var m=Math.floor(t/60),s=Math.floor(t%60),ms=Math.floor((t%1)*100);return String(m).padStart(2,'0')+':'+String(s).padStart(2,'0')+'.'+String(ms).padStart(2,'0')}}
function r(n){{return Math.round(n*1000)/1000}}
function stat(m){{document.getElementById('status').textContent=m}}
function save(){{S.history.push(JSON.stringify(S.clips));if(S.history.length>30)S.history.shift()}}
function drawPlaceholder(){{
S.ctx.fillStyle='#000';
S.ctx.fillRect(0,0,640,360);
S.ctx.fillStyle='#444';
S.ctx.font='14px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('ํƒ€์ž„๋ผ์ธ์— ๋ฏธ๋””์–ด๋ฅผ ์ถ”๊ฐ€ํ•˜์„ธ์š”',320,180);
}}
function addMedia(name,type,url,filePath){{
var m={{id:id(),name:name,type:type,url:url,filePath:filePath||name,dur:type==='image'?5:0,thumb:type==='image'?url:null}};
S.media.push(m);
var container=document.getElementById('hiddenMedia');
if(type==='video'){{
var v=document.createElement('video');
v.src=url;
v.muted=true;
v.playsInline=true;
v.preload='auto';
v.crossOrigin='anonymous';
container.appendChild(v);
S.els[m.id]=v;
v.onloadedmetadata=function(){{
m.dur=r(v.duration);
renderLib();
v.currentTime=0.5;
}};
v.onseeked=function(){{
if(!m.thumb){{
try{{
var c=document.createElement('canvas');
c.width=160;c.height=90;
c.getContext('2d').drawImage(v,0,0,160,90);
m.thumb=c.toDataURL();
renderLib();
}}catch(e){{}}
}}
}};
}}else if(type==='audio'){{
var a=document.createElement('audio');
a.src=url;
a.preload='auto';
container.appendChild(a);
S.els[m.id]=a;
a.onloadedmetadata=function(){{m.dur=r(a.duration);renderLib()}};
}}else if(type==='image'){{
var img=new Image();
img.src=url;
img.crossOrigin='anonymous';
S.els[m.id]=img;
}}
renderLib();
stat('๋ฏธ๋””์–ด ์ถ”๊ฐ€: '+name);
setTimeout(function(){{addClip(m)}},400);
}}
function renderLib(){{
var g=document.getElementById('mediaGrid');
var h=document.getElementById('hint');
h.style.display=S.media.length?'none':'block';
g.innerHTML='';
S.media.forEach(function(m){{
var d=document.createElement('div');
d.className='media-item';
d.draggable=true;
d.ondblclick=function(){{addClip(m)}};
d.ondragstart=function(e){{e.dataTransfer.setData('mid',m.id)}};
var th=m.thumb?'<img src="'+m.thumb+'">':'<div class="media-item-icon">'+(m.type==='video'?'๐ŸŽฌ':m.type==='audio'?'๐ŸŽต':'๐Ÿ–ผ')+'</div>';
d.innerHTML=th+(m.dur?'<div class="media-item-dur">'+fmt(m.dur)+'</div>':'');
g.appendChild(d);
}});
}}
function trackEnd(tr){{
var end=0;
for(var i=0;i<S.clips.length;i++){{
var c=S.clips[i];
if(c.track===tr){{
var e=r(c.start+(c.te-c.ts));
if(e>end)end=e;
}}
}}
return end;
}}
function addClip(m,at){{
save();
var tr=m.type==='audio'?1:0;
var st=at!==undefined?r(at):trackEnd(tr);
S.clips.push({{
id:id(),
mid:m.id,
name:m.name,
type:m.type,
track:tr,
start:st,
dur:m.dur,
ts:0,
te:m.dur,
vol:1,
filePath:m.filePath
}});
renderTL();
updateDur();
stat('ํด๋ฆฝ ์ถ”๊ฐ€: '+m.name);
drawFrame();
}}
function renderTL(){{
['t0','t1'].forEach(function(tid){{document.getElementById(tid).innerHTML=''}});
S.clips.forEach(function(c){{
var tr=document.getElementById('t'+c.track);
var el=document.createElement('div');
el.className='clip '+c.type+(S.sel===c.id?' selected':'');
var len=r(c.te-c.ts);
el.style.left=r(c.start*S.pps*S.zoom)+'px';
el.style.width=Math.max(25,r(len*S.pps*S.zoom))+'px';
el.draggable=true;
el.onclick=function(e){{e.stopPropagation();selClip(c.id)}};
el.oncontextmenu=function(e){{e.preventDefault();selClip(c.id);showCtx(e.clientX,e.clientY)}};
el.ondragstart=function(e){{e.dataTransfer.setData('cid',c.id);e.dataTransfer.setData('ox',e.offsetX)}};
var m=S.media.find(function(x){{return x.id===c.mid}});
var th=m&&m.thumb?'<img class="clip-thumb" src="'+m.thumb+'">':'';
el.innerHTML=th+'<div class="clip-info"><div class="clip-name">'+c.name+'</div><div class="clip-dur">'+fmt(len)+'</div></div><div class="clip-handle clip-handle-l"></div><div class="clip-handle clip-handle-r"></div>';
el.querySelector('.clip-handle-l').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'l',e)}};
el.querySelector('.clip-handle-r').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'r',e)}};
tr.appendChild(el);
}});
renderRuler();
setupDrop();
}}
function renderRuler(){{
var ru=document.getElementById('ruler');
var w=Math.max(r(S.dur*S.pps*S.zoom)+150,600);
ru.style.width=w+'px';
var h='<svg width="100%" height="18" style="position:absolute;left:50px">';
var step=S.zoom<0.7?5:S.zoom<1.5?2:1;
for(var i=0;i<=S.dur+10;i+=step){{
var x=r(i*S.pps*S.zoom);
h+='<line x1="'+x+'" y1="13" x2="'+x+'" y2="18" stroke="#ccc"/>';
h+='<text x="'+x+'" y="10" fill="#999" font-size="8" text-anchor="middle">'+fmt(i)+'</text>';
}}
ru.innerHTML=h+'</svg>';
}}
function setupDrop(){{
['t0','t1'].forEach(function(tid,idx){{
var tr=document.getElementById(tid);
tr.ondragover=function(e){{e.preventDefault();tr.classList.add('drop-zone')}};
tr.ondragleave=function(){{tr.classList.remove('drop-zone')}};
tr.ondrop=function(e){{
e.preventDefault();
tr.classList.remove('drop-zone');
var rect=tr.getBoundingClientRect();
var t=r(Math.max(0,(e.clientX-rect.left)/(S.pps*S.zoom)));
var mid=e.dataTransfer.getData('mid');
var cid=e.dataTransfer.getData('cid');
var ox=parseFloat(e.dataTransfer.getData('ox')||0);
if(mid){{
var m=S.media.find(function(x){{return x.id===mid}});
if(m)addClip(m,t);
}}else if(cid){{
save();
var c=S.clips.find(function(x){{return x.id===cid}});
if(c){{
c.start=r(Math.max(0,t-ox/(S.pps*S.zoom)));
c.track=c.type==='audio'?1:idx;
renderTL();
updateDur();
drawFrame();
}}
}}
}};
}});
}}
var trimData=null;
function startTrim(cid,side,e){{
e.preventDefault();
var c=S.clips.find(function(x){{return x.id===cid}});
if(!c)return;
save();
trimData={{cid:cid,side:side,sx:e.clientX,ots:c.ts,ote:c.te,ost:c.start}};
document.addEventListener('mousemove',doTrim);
document.addEventListener('mouseup',endTrim);
}}
function doTrim(e){{
if(!trimData)return;
var c=S.clips.find(function(x){{return x.id===trimData.cid}});
if(!c)return;
var dx=e.clientX-trimData.sx;
var dt=r(dx/(S.pps*S.zoom));
if(trimData.side==='l'){{
var newTs=Math.max(0,Math.min(c.te-0.1,trimData.ots+dt));
c.ts=r(newTs);
c.start=r(trimData.ost+(newTs-trimData.ots));
}}else{{
c.te=r(Math.max(c.ts+0.1,Math.min(c.dur,trimData.ote+dt)));
}}
renderTL();
updateDur();
}}
function endTrim(){{
trimData=null;
document.removeEventListener('mousemove',doTrim);
document.removeEventListener('mouseup',endTrim);
}}
function selClip(cid){{S.sel=cid;renderTL();renderProps()}}
function renderProps(){{
var box=document.getElementById('propsBox');
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c){{box.innerHTML='<div class="no-sel">ํด๋ฆฝ ์„ ํƒ</div>';return}}
var len=r(c.te-c.ts);
box.innerHTML='<div class="prop-group"><div class="prop-label">์ด๋ฆ„</div><input class="prop-input" value="'+c.name+'" onchange="setProp(\\'name\\',this.value)"></div>'+
'<div class="prop-group"><div class="prop-label">์‹œ์ž‘</div><input class="prop-input" type="number" step="0.1" value="'+c.start+'" onchange="setProp(\\'start\\',parseFloat(this.value))"></div>'+
'<div class="prop-group"><div class="prop-label">๊ธธ์ด: '+fmt(len)+'</div></div>'+
(c.type!=='image'?'<div class="prop-group"><div class="prop-label">๋ณผ๋ฅจ '+Math.round(c.vol*100)+'%</div><input class="prop-input" type="range" min="0" max="1" step="0.05" value="'+c.vol+'" oninput="setProp(\\'vol\\',parseFloat(this.value))"></div>':'');
}}
function setProp(p,v){{
save();
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(c){{c[p]=p==='start'?r(v):v;renderTL();updateDur();renderProps();drawFrame()}}
}}
function splitClip(){{
if(!S.sel){{alert('ํด๋ฆฝ์„ ์„ ํƒํ•˜์„ธ์š”');return}}
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c)return;
var cEnd=r(c.start+c.te-c.ts);
if(S.time<=c.start||S.time>=cEnd){{alert('ํ”Œ๋ ˆ์ดํ—ค๋“œ๊ฐ€ ํด๋ฆฝ ์•ˆ์— ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค');return}}
save();
var splitAt=r(S.time-c.start);
var c2=JSON.parse(JSON.stringify(c));
c2.id=id();
c2.start=r(S.time);
c2.ts=r(c.ts+splitAt);
c.te=r(c.ts+splitAt);
S.clips.push(c2);
renderTL();updateDur();hideCtx();stat('ํด๋ฆฝ ๋ถ„ํ• ๋จ');
}}
function dupeClip(){{
if(!S.sel)return;
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c)return;
save();
var len=r(c.te-c.ts);
var nc=JSON.parse(JSON.stringify(c));
nc.id=id();
nc.start=r(c.start+len);
S.clips.push(nc);
renderTL();updateDur();hideCtx();stat('ํด๋ฆฝ ๋ณต์ œ๋จ');
}}
function delClip(){{
if(!S.sel)return;
save();
S.clips=S.clips.filter(function(x){{return x.id!==S.sel}});
S.sel=null;
renderTL();renderProps();updateDur();hideCtx();stat('ํด๋ฆฝ ์‚ญ์ œ๋จ');
drawFrame();
}}
function undo(){{if(S.history.length){{S.clips=JSON.parse(S.history.pop());renderTL();updateDur();stat('์‹คํ–‰์ทจ์†Œ');drawFrame()}}}}
function updateDur(){{
var mx=0;
for(var i=0;i<S.clips.length;i++){{
var c=S.clips[i];
var e=r(c.start+c.te-c.ts);
if(e>mx)mx=e;
}}
S.dur=mx;
document.getElementById('totT').textContent=fmt(mx);
}}
function togglePlay(){{
S.playing=!S.playing;
document.getElementById('playBtn').textContent=S.playing?'โธ':'โ–ถ';
if(S.playing)play();else stop();
}}
function play(){{
var last=performance.now();
function loop(now){{
if(!S.playing)return;
var dt=(now-last)/1000;
last=now;
S.time=S.time+dt;
if(S.time>=S.dur){{
S.time=0;
if(S.dur===0){{S.playing=false;document.getElementById('playBtn').textContent='โ–ถ';return}}
}}
updateHead();
drawFrame();
S.animId=requestAnimationFrame(loop);
}}
S.animId=requestAnimationFrame(loop);
}}
function stop(){{
if(S.animId){{cancelAnimationFrame(S.animId);S.animId=null}}
Object.keys(S.els).forEach(function(k){{
var el=S.els[k];
if(el&&el.pause)el.pause();
}});
}}
function seek(t){{
S.time=Math.max(0,Math.min(S.dur||0,t));
updateHead();
drawFrame();
}}
function updateHead(){{
document.getElementById('playhead').style.left=(50+S.time*S.pps*S.zoom)+'px';
document.getElementById('curT').textContent=fmt(S.time);
}}
function getClipAt(t,type){{
var sorted=S.clips.filter(function(c){{
if(type==='visual')return c.type==='video'||c.type==='image';
if(type==='audio')return c.type==='audio';
return true;
}}).sort(function(a,b){{return a.start-b.start}});
for(var i=0;i<sorted.length;i++){{
var c=sorted[i];
var cEnd=c.start+(c.te-c.ts);
if(t>=c.start&&t<cEnd)return c;
}}
return null;
}}
function drawFrame(){{
var t=S.time;
var vc=getClipAt(t,'visual');
S.ctx.fillStyle='#000';
S.ctx.fillRect(0,0,640,360);
if(vc){{
var el=S.els[vc.mid];
if(el){{
if(vc.type==='video'){{
var clipT=t-vc.start+vc.ts;
if(Math.abs(el.currentTime-clipT)>0.05){{
el.currentTime=clipT;
}}
if(S.playing&&el.paused)el.play().catch(function(){{}});
if(!S.playing&&!el.paused)el.pause();
el.volume=S.muted?0:vc.vol;
}}
try{{
var sw=el.videoWidth||el.naturalWidth||el.width||640;
var sh=el.videoHeight||el.naturalHeight||el.height||360;
var scale=Math.min(640/sw,360/sh);
var dw=sw*scale,dh=sh*scale;
var dx=(640-dw)/2,dy=(360-dh)/2;
S.ctx.drawImage(el,dx,dy,dw,dh);
}}catch(e){{}}
}}
}}else if(S.clips.length===0){{
S.ctx.fillStyle='#444';
S.ctx.font='14px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('ํƒ€์ž„๋ผ์ธ์— ๋ฏธ๋””์–ด๋ฅผ ์ถ”๊ฐ€ํ•˜์„ธ์š”',320,180);
}}
var audioClips=S.clips.filter(function(c){{
if(c.type!=='audio')return false;
var cEnd=c.start+(c.te-c.ts);
return t>=c.start&&t<cEnd;
}});
audioClips.forEach(function(ac){{
var el=S.els[ac.mid];
if(el){{
var clipT=t-ac.start+ac.ts;
if(Math.abs(el.currentTime-clipT)>0.1)el.currentTime=clipT;
el.volume=S.muted?0:ac.vol;
if(S.playing&&el.paused)el.play().catch(function(){{}});
if(!S.playing&&!el.paused)el.pause();
}}
}});
S.clips.forEach(function(c){{
if(c.type!=='audio')return;
var cEnd=c.start+(c.te-c.ts);
if(t<c.start||t>=cEnd){{
var el=S.els[c.mid];
if(el&&!el.paused)el.pause();
}}
}});
if(!vc&&!audioClips.length&&S.clips.length>0){{
S.ctx.fillStyle='#333';
S.ctx.font='12px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('์žฌ์ƒ ์œ„์น˜์— ๋ฏธ๋””์–ด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค',320,180);
}}
}}
function toggleMute(){{S.muted=!S.muted;document.getElementById('muteBtn').textContent=S.muted?'๐Ÿ”‡':'๐Ÿ”Š'}}
function setZoom(v){{S.zoom=parseFloat(v);renderTL();updateHead()}}
function tlClick(e){{
if(e.target.closest('.clip'))return;
var rect=document.getElementById('tlBox').getBoundingClientRect();
var scrollL=document.getElementById('tlBox').scrollLeft;
S.time=Math.max(0,Math.min(S.dur||0,(e.clientX-rect.left-50+scrollL)/(S.pps*S.zoom)));
updateHead();
drawFrame();
}}
function showCtx(x,y){{var m=document.getElementById('ctx');m.style.display='block';m.style.left=x+'px';m.style.top=y+'px'}}
function hideCtx(){{document.getElementById('ctx').style.display='none'}}
document.addEventListener('click',function(e){{if(!e.target.closest('.ctx-menu'))hideCtx()}});
function exportVideo(){{
if(!S.clips.length){{alert('ํด๋ฆฝ์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”');return}}
S.cancelled=false;
document.getElementById('exportModal').style.display='flex';
document.getElementById('exportBar').style.width='0%';
document.getElementById('exportMsg').textContent='๋…นํ™” ์ค€๋น„ ์ค‘...';
doExport();
}}
async function doExport(){{
// ๋ฉ”์ธ ์บ”๋ฒ„์Šค (MediaRecorder ์—ฐ๊ฒฐ์šฉ)
var canvas=document.createElement('canvas');
canvas.width=1280;canvas.height=720;
var ctx=canvas.getContext('2d');
// ์˜คํ”„์Šคํฌ๋ฆฐ ์บ”๋ฒ„์Šค (๋ Œ๋”๋ง์šฉ - ๋”๋ธ” ๋ฒ„ํผ๋ง)
var offCanvas=document.createElement('canvas');
offCanvas.width=1280;offCanvas.height=720;
var offCtx=offCanvas.getContext('2d');
// ์ดˆ๊ธฐ ๊ฒ€์€ ํ™”๋ฉด
ctx.fillStyle='#000';
ctx.fillRect(0,0,1280,720);
var stream=canvas.captureStream(30);
// ๊ณ ํ™”์งˆ ์„ค์ •
var opts={{mimeType:'video/webm;codecs=vp9',videoBitsPerSecond:8000000}};
if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
opts={{mimeType:'video/webm;codecs=vp8',videoBitsPerSecond:8000000}};
}}
if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
opts={{mimeType:'video/webm',videoBitsPerSecond:5000000}};
}}
var rec=new MediaRecorder(stream,opts);
var chunks=[];
rec.ondataavailable=function(e){{if(e.data.size>0)chunks.push(e.data)}};
document.getElementById('exportMsg').textContent='๋…นํ™” ์ค‘...';
rec.start(100);
var dur=S.dur;
var fps=30;
var frameInterval=1000/fps; // 33.33ms
var totalFrames=Math.ceil(dur*fps);
var startTime=performance.now();
// ์‹ค์‹œ๊ฐ„ ๊ธฐ๋ฐ˜ ๋ Œ๋”๋ง (์ •ํ™•ํ•œ ํƒ€์ด๋ฐ)
await new Promise(function(resolve){{
var frameCount=0;
var lastVideoEl=null;
var lastClipId=null;
function render(){{
if(S.cancelled){{rec.stop();resolve();return}}
var elapsed=performance.now()-startTime;
var t=elapsed/1000; // ํ˜„์žฌ ์‹œ๊ฐ„ (์ดˆ)
if(t>=dur){{
rec.stop();
setTimeout(resolve,100);
return;
}}
// ํ”„๋กœ๊ทธ๋ ˆ์Šค ์—…๋ฐ์ดํŠธ
document.getElementById('exportBar').style.width=(t/dur*100)+'%';
document.getElementById('exportMsg').textContent='๋…นํ™” ์ค‘... '+Math.round(t/dur*100)+'% ('+t.toFixed(1)+'/'+dur.toFixed(1)+'์ดˆ)';
// ์˜คํ”„์Šคํฌ๋ฆฐ ์บ”๋ฒ„์Šค์— ๋ Œ๋”๋ง
offCtx.fillStyle='#000';
offCtx.fillRect(0,0,1280,720);
var vc=getClipAt(t,'visual');
if(vc){{
var el=S.els[vc.mid];
if(el){{
if(vc.type==='video'){{
var clipT=t-vc.start+vc.ts;
// ํด๋ฆฝ์ด ๋ฐ”๋€Œ๋ฉด seekํ•˜๊ณ  ์žฌ์ƒ
if(lastClipId!==vc.id){{
el.currentTime=clipT;
el.play().catch(function(){{}});
lastClipId=vc.id;
lastVideoEl=el;
}}
// ์ด์ „ ๋น„๋””์˜ค ์ •์ง€
if(lastVideoEl&&lastVideoEl!==el&&!lastVideoEl.paused){{
lastVideoEl.pause();
}}
lastVideoEl=el;
}}
try{{
var sw=el.videoWidth||el.naturalWidth||el.width||1280;
var sh=el.videoHeight||el.naturalHeight||el.height||720;
var scale=Math.min(1280/sw,720/sh);
var dw=sw*scale,dh=sh*scale;
offCtx.drawImage(el,(1280-dw)/2,(720-dh)/2,dw,dh);
}}catch(e){{}}
}}
}}else{{
// ํด๋ฆฝ ์—†์œผ๋ฉด ์ด์ „ ๋น„๋””์˜ค ์ •์ง€
if(lastVideoEl&&!lastVideoEl.paused){{
lastVideoEl.pause();
lastClipId=null;
}}
}}
// ์™„์„ฑ๋œ ํ”„๋ ˆ์ž„์„ ๋ฉ”์ธ ์บ”๋ฒ„์Šค๋กœ ๋ณต์‚ฌ
ctx.drawImage(offCanvas,0,0);
requestAnimationFrame(render);
}}
requestAnimationFrame(render);
}});
// ๋ชจ๋“  ๋น„๋””์˜ค ์ •์ง€
Object.keys(S.els).forEach(function(k){{
var el=S.els[k];
if(el&&el.pause)el.pause();
}});
if(S.cancelled)return;
var webmBlob=new Blob(chunks,{{type:'video/webm'}});
if(webmBlob.size<1000){{document.getElementById('exportMsg').textContent='๋…นํ™” ์‹คํŒจ';return}}
document.getElementById('exportBar').style.width='100%';
document.getElementById('exportMsg').textContent='์™„๋ฃŒ! ('+Math.round(webmBlob.size/1024/1024*10)/10+'MB) - ์•„๋ž˜์—์„œ ๋‹ค์šด๋กœ๋“œ';
var downloadDiv=document.createElement('div');
downloadDiv.style.marginTop='10px';
var webmLink=document.createElement('a');
webmLink.href=URL.createObjectURL(webmBlob);
webmLink.download='video_'+Date.now()+'.webm';
webmLink.className='btn btn-success';
webmLink.textContent='๐Ÿ“ฅ WebM ๋‹ค์šด๋กœ๋“œ';
webmLink.style.marginRight='5px';
downloadDiv.appendChild(webmLink);
var copyBtn=document.createElement('button');
copyBtn.className='btn btn-secondary';
copyBtn.textContent='๐Ÿ“‹ MP4๋ณ€ํ™˜์šฉ ๋ณต์‚ฌ';
copyBtn.onclick=async function(){{
document.getElementById('exportMsg').textContent='๋ฐ์ดํ„ฐ ์ค€๋น„ ์ค‘...';
var reader=new FileReader();
reader.onload=function(){{
var base64=reader.result.split(',')[1];
navigator.clipboard.writeText(base64).then(function(){{
document.getElementById('exportMsg').textContent='๋ณต์‚ฌ ์™„๋ฃŒ! ์œ„ ์ž…๋ ฅ๋ž€์— ๋ถ™์—ฌ๋„ฃ๊ธฐ';
alert('๋ณต์‚ฌ ์™„๋ฃŒ!\\n\\nGradio์˜ "WebM ๋ฐ์ดํ„ฐ" ์ž…๋ ฅ๋ž€์— ๋ถ™์—ฌ๋„ฃ๊ธฐ(Ctrl+V) ํ›„\\n"MP4 ๋ณ€ํ™˜" ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜์„ธ์š”.');
}}).catch(function(){{
prompt('์•„๋ž˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณต์‚ฌํ•˜์„ธ์š”:', base64.substring(0,100)+'...');
}});
}};
reader.readAsDataURL(webmBlob);
}};
downloadDiv.appendChild(copyBtn);
document.querySelector('.modal-box').appendChild(downloadDiv);
}}
function cancelExport(){{S.cancelled=true;document.getElementById('exportModal').style.display='none'}}
document.addEventListener('keydown',function(e){{
if(e.target.tagName==='INPUT')return;
if(e.code==='Space'){{e.preventDefault();togglePlay()}}
else if(e.code==='Delete'){{e.preventDefault();delClip()}}
else if(e.code==='ArrowLeft'){{seek(S.time-0.1)}}
else if(e.code==='ArrowRight'){{seek(S.time+0.1)}}
}});
init();
renderTL();
stat('์ค€๋น„๋จ');
var initData={media_data};
if(initData&&initData.length)initData.forEach(function(m){{addMedia(m.name,m.type,m.dataUrl,m.filePath)}});
</script>
</body>
</html>'''
def process_file(files):
"""ํŒŒ์ผ ์ฒ˜๋ฆฌ ๋ฐ ์„œ๋ฒ„์— ์ €์žฅ"""
global uploaded_files
if not files:
return []
results = []
file_list = files if isinstance(files, list) else [files]
for f in file_list:
if not f:
continue
path = f.name if hasattr(f, 'name') else f
name = os.path.basename(path)
ext = name.lower().split('.')[-1]
if ext in ['mp4', 'webm', 'mov', 'avi', 'mkv']:
t, m = 'video', f'video/{ext}'
elif ext in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
t, m = 'image', f'image/{ext}'
elif ext in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
t, m = 'audio', f'audio/{ext}'
else:
continue
# ์„œ๋ฒ„์— ํŒŒ์ผ ๋ณต์‚ฌ (MP4 ๋‚ด๋ณด๋‚ด๊ธฐ์šฉ)
dst_path = os.path.join(UPLOAD_DIR, f"{int(time.time()*1000)}_{name}")
shutil.copy(path, dst_path)
uploaded_files[name] = dst_path
with open(path, 'rb') as fp:
d = base64.b64encode(fp.read()).decode()
results.append({'name': name, 'type': t, 'dataUrl': f'data:{m};base64,{d}', 'filePath': name})
return results
def make_iframe(data):
j = json.dumps(data, ensure_ascii=False)
h = get_editor_html(j).replace("'", "&#39;")
return f"<iframe srcdoc='{h}' style='width:100%;height:750px;border:none;border-radius:10px'></iframe>"
def export_mp4(export_json):
"""์„œ๋ฒ„ ์‚ฌ์ด๋“œ MP4 ๋‚ด๋ณด๋‚ด๊ธฐ"""
global uploaded_files
if not export_json or len(export_json) < 10:
return None
try:
data = json.loads(export_json)
clips = data.get('clips', [])
if not clips:
return None
video_clips = [c for c in clips if c['type'] in ['video', 'image']]
if not video_clips:
return None
temp_dir = tempfile.mkdtemp()
output_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
# ๋‹จ์ผ ํด๋ฆฝ
if len(video_clips) == 1:
clip = video_clips[0]
file_path = uploaded_files.get(clip['filePath'])
if not file_path or not os.path.exists(file_path):
return None
duration = clip['te'] - clip['ts']
if clip['type'] == 'image':
cmd = ['ffmpeg', '-y', '-loop', '1', '-i', file_path, '-c:v', 'libx264', '-t', str(duration), '-pix_fmt', 'yuv420p', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', output_path]
else:
cmd = ['ffmpeg', '-y', '-i', file_path, '-ss', str(clip['ts']), '-t', str(duration), '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', '-movflags', '+faststart', output_path]
subprocess.run(cmd, capture_output=True, timeout=300)
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
return output_path
return None
# ์—ฌ๋Ÿฌ ํด๋ฆฝ
temp_files = []
concat_file = os.path.join(temp_dir, 'concat.txt')
for i, clip in enumerate(sorted(video_clips, key=lambda x: x['start'])):
file_path = uploaded_files.get(clip['filePath'])
if not file_path or not os.path.exists(file_path):
continue
temp_out = os.path.join(temp_dir, f'temp_{i}.mp4')
duration = clip['te'] - clip['ts']
if clip['type'] == 'image':
cmd = ['ffmpeg', '-y', '-loop', '1', '-i', file_path, '-c:v', 'libx264', '-t', str(duration), '-pix_fmt', 'yuv420p', '-r', '30', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', temp_out]
else:
cmd = ['ffmpeg', '-y', '-i', file_path, '-ss', str(clip['ts']), '-t', str(duration), '-c:v', 'libx264', '-preset', 'fast', '-c:a', 'aac', '-r', '30', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', temp_out]
subprocess.run(cmd, capture_output=True, timeout=120)
if os.path.exists(temp_out):
temp_files.append(temp_out)
if not temp_files:
return None
with open(concat_file, 'w') as f:
for tf in temp_files:
f.write(f"file '{tf}'\n")
cmd = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_file, '-c:v', 'libx264', '-preset', 'fast', '-c:a', 'aac', '-movflags', '+faststart', output_path]
subprocess.run(cmd, capture_output=True, timeout=300)
for tf in temp_files:
try: os.remove(tf)
except: pass
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
return output_path
return None
except Exception as e:
print(f"[Export] Error: {e}")
return None
def convert_webm_to_mp4(webm_base64):
"""WebM base64 ๋ฐ์ดํ„ฐ๋ฅผ MP4๋กœ ๋ณ€ํ™˜"""
if not webm_base64 or len(webm_base64) < 100:
return None
try:
# base64 ๋””์ฝ”๋”ฉ
webm_data = base64.b64decode(webm_base64)
temp_dir = tempfile.mkdtemp()
webm_path = os.path.join(temp_dir, 'input.webm')
mp4_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
# WebM ํŒŒ์ผ ์ €์žฅ
with open(webm_path, 'wb') as f:
f.write(webm_data)
# FFmpeg๋กœ MP4 ๋ณ€ํ™˜
cmd = [
'ffmpeg', '-y',
'-i', webm_path,
'-c:v', 'libx264',
'-preset', 'fast',
'-crf', '23',
'-c:a', 'aac',
'-b:a', '128k',
'-movflags', '+faststart',
mp4_path
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
# WebM ํŒŒ์ผ ์‚ญ์ œ
try:
os.remove(webm_path)
except:
pass
if os.path.exists(mp4_path) and os.path.getsize(mp4_path) > 0:
return mp4_path
return None
except Exception as e:
print(f"[Convert] Error: {e}")
return None
with gr.Blocks() as demo:
gr.Markdown("## ๐ŸŽฌ Video Editor")
f = gr.File(label="๐Ÿ“ ํŒŒ์ผ ์—…๋กœ๋“œ", file_count="multiple", file_types=["video", "image", "audio"])
e = gr.HTML(value=make_iframe([]))
gr.Markdown("---")
gr.Markdown("### ๐Ÿ“ฅ MP4 ๋ณ€ํ™˜")
gr.Markdown("์—๋””ํ„ฐ์—์„œ '๋‚ด๋ณด๋‚ด๊ธฐ' โ†’ 'MP4๋ณ€ํ™˜์šฉ ๋ณต์‚ฌ' ํด๋ฆญ ํ›„ ์•„๋ž˜์— ๋ถ™์—ฌ๋„ฃ๊ธฐ")
with gr.Row():
webm_data = gr.Textbox(label="WebM ๋ฐ์ดํ„ฐ (base64)", placeholder="์—ฌ๊ธฐ์— ๋ถ™์—ฌ๋„ฃ๊ธฐ (Ctrl+V)", lines=2, scale=4)
convert_btn = gr.Button("๐ŸŽฌ MP4 ๋ณ€ํ™˜", variant="primary", scale=1)
mp4_output = gr.File(label="๐Ÿ“ฅ MP4 ๋‹ค์šด๋กœ๋“œ")
f.change(fn=lambda x: make_iframe(process_file(x)), inputs=[f], outputs=[e])
convert_btn.click(fn=convert_webm_to_mp4, inputs=[webm_data], outputs=[mp4_output])
if __name__ == "__main__":
demo.launch()