from flask import Flask, request, jsonify, render_template
import subprocess
import os 
import tempfile
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)
processing = False

# 日志配置
if not os.path.exists('logs'):
   os.mkdir('logs')
file_handler = RotatingFileHandler('logs/app.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
   '%(asctime)s %(levelname)s: %(message)s'
))
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)

@app.route('/')
def home():
   return render_template('index.html')

@app.route('/evaluate', methods=['POST'])
def evaluate():
    global processing
    
    app.logger.info(f'收到请求: {request.files}')  # 添加日志
    
    if processing:
        return jsonify({'error': '正在处理其他文件,请等待'}), 400
        
    if 'file' not in request.files:
        app.logger.error('没有文件字段')  # 添加日志
        return jsonify({'error': '请选择文件'}), 400
        
    file = request.files['file']
    app.logger.info(f'文件名: {file.filename}')  # 添加日志
    
    try:
       with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as temp_csv:
           file.save(temp_csv.name)
           
           # 执行处理脚本
           subprocess.run(['python', 'convert_to_para.py', temp_csv.name, 'pred.para', 'gold.para'], check=True)
           subprocess.run(['python', 'parallel_to_m2.py', '-f', 'gold.para', '-o', 'gold.m2', '-g', 'char'], check=True)
           subprocess.run(['python', 'parallel_to_m2.py', '-f', 'pred.para', '-o', 'pred.m2', '-g', 'char'], check=True)
           
           result = subprocess.run(
               ['python', 'compare_m2_for_evaluation.py', '-hyp', 'pred.m2', '-ref', 'gold.m2'],
               capture_output=True,
               text=True,
               check=True
           )
           
           app.logger.info(f'文件处理完成: {file.filename}')
           return jsonify({'result': result.stdout})
           
    except subprocess.CalledProcessError as e:
       error_msg = f'脚本执行错误: {str(e)}'
       app.logger.error(error_msg)
       return jsonify({'error': error_msg}), 500
       
    except Exception as e:
       error_msg = f'处理错误: {str(e)}'
       app.logger.error(error_msg)
       return jsonify({'error': error_msg}), 500
       
    finally:
       processing = False
       cleanup_files(temp_csv.name)

def cleanup_files(temp_csv):
   os.unlink(temp_csv)
   for f in ['pred.para', 'gold.para', 'pred.m2', 'gold.m2']:
       if os.path.exists(f):
           os.remove(f)
           

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=8000, debug=True)