import os import uuid from flask import Flask, render_template, request, send_file import subprocess app = Flask(__name__) UPLOAD_FOLDER = 'uploads' GENERATED_IMAGES_FOLDER = 'generated_images' ALLOWED_EXTENSIONS = {'csv'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['GENERATED_IMAGES_FOLDER'] = GENERATED_IMAGES_FOLDER # 確保目錄存在 os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(GENERATED_IMAGES_FOLDER, exist_ok=True) def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route("/") def index(): return render_template("index.html") @app.route("/hello") def hello(): return "Hello, World!" @app.route('/upload_csv', methods=['POST']) def upload_csv(): print("Received request to upload CSV file") if 'csvFile' not in request.files: return "No file part", 400 file = request.files['csvFile'] if file.filename == '': return "No selected file", 400 if file and allowed_file(file.filename): unique_filename = str(uuid.uuid4()) + '.csv' csv_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename) file.save(csv_path) print(f"CSV file saved to {csv_path}") try: # 呼叫外部 Python 腳本來生成圖片 subprocess.run([os.path.join(os.getcwd(), '.venv', 'Scripts', 'python'), 'generate_images.py', csv_path], check=True) except subprocess.CalledProcessError as e: print(f"Error generating images: {e}") return "Error generating images", 500 except FileNotFoundError as e: print(f"File not found: {e}") return "File not found", 404 except Exception as e: print(f"An unexpected error occurred: {e}") return "An unexpected error occurred", 500 return "File uploaded successfully", 200 if __name__ == '__main__': # 當在生產環境部署時,不建議使用 debug=True # 可以指定 host='0.0.0.0' 讓外部可訪問 (在防火牆允許的情況下) app.run(debug=True, host='127.0.0.1', port=5000)