import os

from flask import Flask, request, jsonify
from image_search_class import ImageSearchClass
import time

app = Flask(__name__)

image_search_obj = ImageSearchClass()

@app.route('/image_search', methods=['POST'])
def search():
    print(request.form)  # 打印所有表单数据

    site_name = request.form.get('site_name', 'us')  # 默认值为 'us'
    search_key = request.form.get('search_key', 'file')  # 默认值为 'file'
    search_value = request.form.get('search_value', '')  # 默认值为 ''
    top_k = int(request.form.get('top_k', 100))  # 默认值为 100
    print(site_name, search_key, search_value, top_k)

    # 获取文件并存储
    file_path = ''
    if 'file' in request.files:
        file = request.files['file']  # 获取名为 "file" 的文件流参数
        timestamp = time.time()
        milli_timestamp = round(timestamp * 1000)  # 将秒级的时间戳转换为毫秒级
        file_path = f'/mnt/data/img_data/tmp_img/{milli_timestamp}.jpg'
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        file.save(file_path)
        print("file, file_path:", file, file_path)
    else:
        print("No file part in the request")
        # return jsonify({"error": "No file provided"}), 400

    similarities_dict = image_search_obj.search_api(
        site_name=site_name, search_key=search_key,
        search_value=search_value, top_k=top_k, file_path=file_path
    )  # 进行搜索

    return jsonify(
        {
            "similarities_dict": similarities_dict,
        }
    )

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9998)
