import os, tempfile, subprocess, uuid
from flask import Flask, request, jsonify, render_template_string, send_file
from faster_whisper import WhisperModel

app = Flask(__name__)
UPLOAD_DIR = "/tmp/whisper_uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)

print("Loading whisper model (base, cuda)...", flush=True)
model = WhisperModel("base", device="cuda", compute_type="float16")
print("Model ready.", flush=True)

HTML = r"""<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Whisper 转录</title>
<style>
body{font-family:system-ui,sans-serif;max-width:720px;margin:40px auto;padding:0 16px;background:#f7f7f8;color:#222}
#drop{border:2px dashed #aaa;border-radius:12px;padding:48px;text-align:center;color:#666;cursor:pointer;background:#fff}
#drop:hover{border-color:#4a90d9}
#result{white-space:pre-wrap;background:#fff;border:1px solid #ddd;border-radius:8px;padding:16px;margin-top:16px;min-height:120px}
button{padding:10px 20px;font-size:15px;border:none;border-radius:8px;background:#4a90d9;color:#fff;cursor:pointer;margin-top:12px}
button:disabled{background:#aaa}
#status{color:#666;margin-top:12px}
</style></head><body>
<h2>🎙️ Whisper 视频转录</h2>
<div id="drop">点击选择视频，或拖拽到此处，或按 <b>Ctrl+V</b> 粘贴</div>
<input type="file" id="file" accept="video/*,audio/*" style="display:none">
<div id="status"></div>
<div id="result">转录结果会显示在这里…</div>
<button id="copy" disabled>复制文本</button>
<script>
const drop=document.getElementById('drop'),file=document.getElementById('file'),
      status=document.getElementById('status'),result=document.getElementById('result'),
      copyBtn=document.getElementById('copy');
drop.onclick=()=>file.click();
file.onchange=()=>{if(file.files[0])upload(file.files[0])};
['dragover','drop'].forEach(e=>drop.addEventListener(e,ev=>{ev.preventDefault();
  if(e==='drop'&&ev.dataTransfer.files[0])upload(ev.dataTransfer.files[0])}));
document.addEventListener('paste',ev=>{
  const items=(ev.clipboardData&&ev.clipboardData.files)||[];
  for(const f of items){
    if(f.type.startsWith('video/')||f.type.startsWith('audio/')){
      if(confirm('检测到剪贴板中有视频/音频文件：'+f.name+'\n是否上传转录？'))upload(f);
      return;
    }
  }
});
function upload(f){
  status.textContent='上传转录中：'+f.name+' …';
  result.textContent='';copyBtn.disabled=true;
  const fd=new FormData();fd.append('file',f);
  fetch('/api/transcribe',{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
      if(d.error){status.textContent='出错：'+d.error;return}
      status.textContent='完成 ✓';
      result.textContent=d.text;copyBtn.disabled=false;
    }).catch(e=>{status.textContent='请求失败：'+e});
}
copyBtn.onclick=()=>{navigator.clipboard.writeText(result.textContent);copyBtn.textContent='已复制 ✓';setTimeout(()=>copyBtn.textContent='复制文本',1500)};
</script></body></html>"""

@app.route("/")
def index():
    return render_template_string(HTML)

def transcribe_file(path):
    wav = path + ".wav"
    subprocess.run(["ffmpeg","-y","-v","error","-i",path,"-ar","16000","-ac","1",wav],
                   check=True)
    segments, info = model.transcribe(wav, language="zh")
    text = "".join(s.text for s in segments).strip()
    os.remove(wav)
    return text, info.language

@app.route("/api/transcribe", methods=["POST"])
def api_transcribe():
    f = request.files.get("file")
    if not f:
        return jsonify({"error": "no file"}), 400
    name = uuid.uuid4().hex + "_" + (f.filename or "upload")
    path = os.path.join(UPLOAD_DIR, name)
    f.save(path)
    try:
        text, lang = transcribe_file(path)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        if os.path.exists(path):
            os.remove(path)
    return jsonify({"text": text, "language": lang})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8082, threaded=True)
