2025-06-25 21:17:49 +08:00

99 lines
3.4 KiB
Python

import os
import uuid
from flask import Flask, render_template, request, send_file
import subprocess
from datetime import datetime
import zipfile
import io
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():
search_str = 'e771'
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):
uuid_str = str(uuid.uuid4())[:4]
unique_filename = datetime.now().strftime("%Y%m%d_%H%M")+ '_' + uuid_str
csv_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename+'.csv')
file.save(csv_path)
print(f"CSV file saved to {csv_path}")
try:
#subprocess.run([os.path.join(os.getcwd(), '.venv', 'Scripts', 'python'), 'generate_images.py', csv_path, unique_filename ], check=True)
subprocess.run(['python', 'generate_images.py', csv_path, unique_filename ], check=True)
folder = app.config['GENERATED_IMAGES_FOLDER']
matched_files = [f for f in os.listdir(folder) if uuid_str in f and f.endswith('.png')]
print(f"Matched files: {matched_files}")
# 壓縮所有圖片到一個 zip
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
for filename in matched_files:
file_path = os.path.join(folder, filename)
zip_file.write(file_path, arcname=filename)
zip_buffer.seek(0)
# 刪除生成的圖片文件
for filename in matched_files:
file_path = os.path.join(folder, filename)
os.remove(file_path)
print(f"Deleted file: {file_path}")
# 刪除 CSV 文件
os.remove(csv_path)
return send_file(
zip_buffer,
mimetype='application/zip',
as_attachment=True,
download_name=f'{unique_filename}_images.zip'
)
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='0.0.0.0', port=5000)