
import flask
from flask_cors import CORS
import json
import os
import sys

from mapnlp.pipe.dag import NLPTaskDAG
from mapnlp.pipe.chunker_pipe import ChunkerPipe
from mapnlp.pipe.dependency_parser_pipe import DependencyParserPipe
from mapnlp.pipe.tokenizer_pipe import TokenizerPipe

sys.path.append(os.path.dirname(__file__))

from chunker import IndependentRuleChunker
from parser import LastHeadDependencyParser
from tokenizer import SudachiTokenizer
from hierplaine_utils import convert2hierplain

app = flask.Flask(__name__)
CORS(app)

# setting up text analyzer
tok = TokenizerPipe.build("tok", {"alg_name": "sudachi"})
chunk = ChunkerPipe.build("chunk", {"alg_name": "independent-rule"})
parser = DependencyParserPipe.build("dep", {"alg_name": "last-head"})
dag = NLPTaskDAG("example")
dag.add_task_dep((NLPTaskDAG.INITIAL, tok))
dag.add_task_dep((tok, chunk))
dag.add_task_dep((tok, parser))


@app.route('/')
def hello_world():
    return 'This application is for easy to get the annotation generated by NLP analyzers'


@app.route('/text_analyze', methods=["POST"])
def text_analyze():
    raw_input_txt = flask.request.get_json().get("input_text")
    text_obj = dag.process(raw_input_txt)
    tree = convert2hierplain(text_obj.dump_as_dict(), "chunk", "dep")

    response = {
        "success": True,
        "Content-Type": "application/json",
        "tree": tree
    }

    return flask.jsonify(response)

if __name__ == "__main__":
    app.run(host='0.0.0.0')