Commit c84029f6 authored by Kento HASEGAWA's avatar Kento HASEGAWA
Browse files

Merge branch 'comm-server' into 'comm'

Merge comm-server

See merge request adc2018/adc2018-system!10
parents 5e4c621e 18700dc5
Loading
Loading
Loading
Loading
+157 −6
Changes for comm/server/main.py: 157 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -60,18 +60,18 @@ def load_questions():
            "board_size": board_size,
            "line_num": line_num,
            "last_req": None,
            "answers": [],
            "answers": OrderedDict(),
            }

        update_answer_list(_name)

    # 既に回答されているものを読み込む
    answer_path = os.path.abspath(app_args["out"])
    answer_list = glob.glob("{}/T03_A*.txt".format(answer_path))
    answer_list = glob.glob("{}/submit/T01_A*.txt".format(answer_path))

    for v in answer_list:
        _ans_name = os.path.basename(v)
        m = re.search(r"T03_A([0-9A-Za-z]+)\.txt", _ans_name)
        m = re.search(r"T01_A([0-9A-Za-z]+)\.txt", _ans_name)
        if m:
            _name = "NL_Q{}.txt".format(m.group(1))
            with open(v, "r") as fp:
@@ -87,7 +87,7 @@ def update_answer_list(qname):
    global app_args
    global questions

    questions[qname]['answers'] = []
    questions[qname]['answers'] = OrderedDict()

    _folder_name = os.path.splitext(qname)[0]
    _answers_path = "{}/{}".format(app_args['out'], _folder_name)
@@ -97,9 +97,13 @@ def update_answer_list(qname):
        answer_log_file.reverse()

        for v2 in answer_log_file:
            json_name = os.path.basename(v2)
            with open(v2, "r") as fp:
                answer_log = json.load(fp)
            questions[qname]['answers'].append(answer_log)
            questions[qname]['answers'][json_name] = answer_log

            if questions[qname]['answer'] == answer_log['answer']:
                questions[qname]['best_json'] = json_name

@app.before_request
def before_request():
@@ -161,7 +165,7 @@ def post():
    if not os.path.isdir(save_path):
        os.makedirs(save_path)

    file_name = "{}-{}.json".format(receive_time_str, _client.replace(":", "."))
    file_name = "{}-{}.json".format(receive_time_str, _solver.replace(":", "."))
    save_file_path = "{}/{}".format(save_path, file_name)
    with open(save_file_path, "w") as fp:
        json.dump(dat, fp, indent=4)
@@ -282,6 +286,148 @@ def get_status():

    return json.dumps(res)

@app.route("/save", methods=["POST"])
def save_best_solution():
    """
    それぞれの問題に対し,解き終わった答えの中で最も品質の高い解を
    submitフォルダに出力する.
    """
    global questions
    global app_args

    qname = request.form["qname"]

    _best_score = -1
    _best_json = ""

    for k, v in questions[qname]['answers'].items():
        if v['nlcheck'] > _best_score:
            _best_socer = v['nlcheck']
            _best_json = k

    if _best_json != "":
        out_path = "{}/{}".format(app_args['out'], "submit")
        if not os.path.isdir(out_path):
            os.makedirs(out_path)

        qnumber = qname.replace("NL_Q", "").replace(".txt", "")
        out_file_path = "{}/T01_A{}.txt".format(out_path, qnumber)
        with open(out_file_path, 'w') as fp:
            fp.write(questions[qname]['answers'][_best_json]['answer'])

        questions[qname]['best_json'] = _best_json

        res = {"status": "OK"}
    else:
        res = {"status": "No answer is found"}

    return json.dumps(res)

@app.route("/board-data", methods=["POST"])
def get_board_data():

    global questions

    qname = request.form['qname']
    json_name = request.form['jname']

    lines = questions[qname]['answers'][json_name]['answer'].split("\n")
    quality = questions[qname]['answers'][json_name]['nlcheck']

    # board_size = [int(v) for v in lines[1].rstrip().split()[1].split("X")]
    board_size = [int(v) for v in questions[qname]['board_size'].split("X")]

    raw_data = [[[0 for x in range(board_size[0])] for y in range(board_size[1])] for z in range(board_size[2])]
    data = []

    max_line_num = 0

    for l in lines[1:]:
        if l.rstrip() == "":
            continue
        elif l.startswith("LAYER"):
            z = int(l.rstrip().split()[1])-1
            y = 0
            continue
        else:
            ldat = l.rstrip().split(",")
            for x, v in enumerate(ldat):
                raw_data[z][y][x] = int(v)
                max_line_num = max(max_line_num, int(v))
            y += 1

    terminals = [[] for v in range(max_line_num+1)]

    for z in range(board_size[2]):
        for y in range(board_size[1]):
            for x in range(board_size[0]):
                line_num = raw_data[z][y][x]

                if line_num == 0:
                    continue

                adj_cnt = 0
                if((0 <= x-1 < board_size[0]) and (raw_data[z][y][x-1] == line_num)):
                    adj_cnt += 1
                if((0 <= x+1 < board_size[0]) and (raw_data[z][y][x+1] == line_num)):
                    adj_cnt += 1
                if((0 <= y-1 < board_size[1]) and (raw_data[z][y-1][x] == line_num)):
                    adj_cnt += 1
                if((0 <= y+1 < board_size[1]) and (raw_data[z][y+1][x] == line_num)):
                    adj_cnt += 1
                if((0 <= z-1 < board_size[2]) and (raw_data[z-1][y][x] == line_num)):
                    adj_cnt += 1
                if((0 <= z+1 < board_size[2]) and (raw_data[z+1][y][x] == line_num)):
                    adj_cnt += 1

                if adj_cnt == 1:
                    terminals[line_num].append((x, y, z))

    lines = {}

    for i in range(1, max_line_num+1):
        if len(terminals[i]) != 2:
            continue
        start = terminals[i][0]
        goal = terminals[i][1]

        lines[i] = []
        lines[i].append(start)
        lines[i].append(start)

        now = start
        _next = (0, 0, 0)
        while now != goal:
            x, y, z = now

            adj_cnt = 0
            if((0 <= x-1 < board_size[0]) and (raw_data[z][y][x-1] == i) and (lines[i][-2] != (x-1, y, z))):
                _next = (x-1, y, z)
            elif((0 <= x+1 < board_size[0]) and (raw_data[z][y][x+1] == i) and (lines[i][-2] != (x+1, y, z))):
                _next = (x+1, y, z)
            elif((0 <= y-1 < board_size[1]) and (raw_data[z][y-1][x] == i) and (lines[i][-2] != (x, y-1, z))):
                _next = (x, y-1, z)
            elif((0 <= y+1 < board_size[1]) and (raw_data[z][y+1][x] == i) and (lines[i][-2] != (x, y+1, z))):
                _next = (x, y+1, z)
            elif((0 <= z-1 < board_size[2]) and (raw_data[z-1][y][x] == i) and (lines[i][-2] != (x, y, z-1))):
                _next = (x, y, z-1)
            elif((0 <= z+1 < board_size[2]) and (raw_data[z+1][y][x] == i) and (lines[i][-2] != (x, y, z+1))):
                _next = (x, y, z+1)
            else:
                print("Error: Not found an adjacent node")
                _next = goal

            lines[i].append(_next)
            now = _next

    res = {
        'line': lines,
        'board': board_size,
        'quality': quality,
    }

    return json.dumps(res)

@app.route("/get_clients")
def get_clients():
    global clients
@@ -294,6 +440,11 @@ def get_clients():

    return json.dumps(res)

@app.route("/board-viewer", methods=["GET"])
def show_board_viewer():

    return render_template("board-viewer.html")

@app.route("/get_question_table")
def question_table():

+17 −0
Changes for comm/server/static/css/pynq-manager.css: 17 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -40,6 +40,9 @@ body{
#question-table-wrapper tr.question-row.q-selected{
    background-color: rgba(200, 100, 100, .3);
}
#question-table-wrapper tr.question-row:hover{
    background-color: rgba(200, 100, 100, .15);
}

#client-control-pane{
    height: 330px;
@@ -58,3 +61,17 @@ body{
#question-control-pane h3{
    display: inline-block;
}

#client-control-pane tr.answer-detail-row, 
#client-control-pane tr.answer-detail-row td{
    cursor: pointer;
}

#client-control-pane tr.answer-detail-row:hover{
    background-color: rgba(200, 100, 100, .15);
}

#client-control-pane tr.answer-detail-row.submit-answer{
    background-color: rgba(100, 200, 100, .3);
}
+1051 −0

File added.

Preview size limit exceeded, changes collapsed.

+18 −0
Changes for comm/server/static/js/pynq-manager.js: 18 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -166,6 +166,24 @@ $(function(){
            $("#client-control-pane").find(".stop-button").eq(0).click(function(){
                pm.sendStop();
            });
            $("#client-control-pane").find(".save-button").eq(0).click(function(){
                var qname = $(this).data("qname");
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/save",
                    data: {qname: qname}
                }).done((data) => {
                    alert(data['status']);
                });
            });

            $(".answer-detail-row td").click(function(){
                var json_name = $(this).parent("tr").data("json");
                var qname = $(this).parent("tr").data("qname");
                var viewer_url = "/board-viewer#" + qname + "," + json_name
                window.open(viewer_url, "_blank");
            })
        });
    }

+949 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading