from flask import Flask, jsonify
from flask_cors import CORS
from flask_restful import Api, Resource, reqparse
from utils import get_log
from task.image_interpretability import ImageInterpretability
import ast

app = Flask(__name__, static_folder='', static_url_path='')
app.config['UPLOAD_FOLDER'] = "./upload_data"
cors = CORS(app, resources={r"*": {"origins": "*"}})
api = Api(app)


class Interpretability2Image(Resource):

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('image_name', type=str, required=True, default='', help='')
        parser.add_argument('image_path', type=str, required=True, default='', help='')
        parser.add_argument('Interpretability_method', type=str, required=True, default='textfooler', help='')
        parser.add_argument('model_info', type=str, required=True, default={}, help='')
        parser.add_argument('output_path', type=str, required=True, default='', help='')
        parser.add_argument('kwargs', type=str, required=True, default={}, help='')
        args = parser.parse_args()
        print(args)

        args.model_info = ast.literal_eval(args.model_info)
        args.dataset_info = ast.literal_eval(args.dataset_info)

        Interpretability = ImageInterpretability()
        rst = Interpretability.perform(
            image_name=args.model_info.image_name,
            image_path=args.model_info.image_path,
            Interpretability_method=args.Interpretability_method,
            model_name=args.model_info.model_name,
            output_path=args.output_path,
            **args.kwargs
        )
        return jsonify(rst)

    def get(self):
        msg = get_log(log_path=Interpretability2Image.LOG_PATH)
        if msg:
            return jsonify({'status': 1, 'log': msg})
        else:
            return jsonify({'status': 0, 'log': None})


api.add_resource(Interpretability2Image, '/Interpretability2Image')

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