import os
import whisper
import logging
import threading
import requests

from flask import jsonify,Flask,flash, request, redirect, url_for,send_file
from flask_cors import CORS
from werkzeug.utils import secure_filename


app_80 = Flask(__name__)
UPLOAD_FOLDER = '/home/mcse/projects/flask_80/tmp'
app_80.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app_80.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024  # 500MB


CORS(app_80)
def inserLog(message):
    logger = logging.getLogger('GPU recode')
    logger.setLevel(logging.DEBUG)
    
    handler = logging.FileHandler('/home/mcse/projects/flask_80/app.log')
    handler.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    logger.info(message)

def save_srt(result, srt_file):
    with open(srt_file, "w", encoding="utf-8") as f:
        for i, segment in enumerate(result["segments"]):
            # Write SRT segment number
            f.write(f"{i + 1}\n")
            
            # Format start and end times
            start = format_time(segment["start"])
            end = format_time(segment["end"])
            f.write(f"{start} --> {end}\n")
            
            # Write the text
            f.write(f"{segment['text']}\n\n")

# Helper function to format time for SRT
def format_time(seconds):
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds - int(seconds)) * 1000)
    return f"{hours:02}:{minutes:02}:{secs:02},{millis:03}"


def processFile(file,Ftype,file_path):
    inserLog(Ftype)
    model = whisper.load_model("base", device="cuda")  # 使用 CUDA 加速
     
    if Ftype=='txt':
      inserLog('start...txt')
      result = model.transcribe(file_path,task="transcribe", verbose=False)
      file_txt_path=os.path.join(app_80.config['UPLOAD_FOLDER'],file.filename.split('.')[0]+".txt");
      with open(file_txt_path, "w", encoding="utf-8") as f:
        f.write(result["text"])
    else:
      inserLog('start...srt')
      result = model.transcribe(file_path,  task="transcribe", verbose=False)
      file_srt_path=os.path.join(app_80.config['UPLOAD_FOLDER'],file.filename.split('.')[0]+".srt");
      save_srt(result,file_srt_path)



    
@app_80.route('/')
def home():
    return "HelloA, Flask with Apache!"
@app_80.route('/api/download/<ext>/<name>',methods=['GET'])
def download(ext,name):
  if(ext=='srt'):
    file_path=os.path.join(app_80.config['UPLOAD_FOLDER'],name+".srt");
    response=send_file(file_path, as_attachment=True);
    os.remove(file_path)
  elif(ext=='txt'):
    file_path = os.path.join(app_80.config['UPLOAD_FOLDER'],name+".txt");
    response=send_file(file_path, as_attachment=True);
    os.remove(file_path)
  return response

@app_80.route('/api/task-status/<ext>/<name>', methods=['GET'])
def taskStatus(ext,name):
  if(ext=='srt'):
    file_path=os.path.join(app_80.config['UPLOAD_FOLDER'],name+".srt");
    status="completed" if os.path.exists(file_path) else "incompleted";
    return jsonify({ 'status':status}),200;
  elif(ext=='txt'):
    file_path=os.path.join(app_80.config['UPLOAD_FOLDER'],name+".txt");
    status="completed" if os.path.exists(file_path) else "incompleted";
    return jsonify({ 'status':status}),200;


@app_80.route('/api', methods=['POST'])
def upload_file():
  if 'file' not in request.files:
    return 'error';
  file = request.files['file']
  file_type=request.form.get("type");
  filename = secure_filename(file.filename)
  file_path = os.path.join(app_80.config['UPLOAD_FOLDER'], file.filename)
  file.save(file_path)
        
  thread = threading.Thread(target=processFile, args=(file,file_type,file_path));
  thread.start()
  return jsonify({"message": "File uploaded and processing started", "filename": filename}), 200

if __name__ == '__main__':
    app_80.run()
