# Path: chat/mytools.py
# def read_excel(filepath):
#     """Get excel source.
# 
#     Args:
#         filepath: The full path of excel file. Excel 文件完整路径。
# 
#     Returns:
#         data: Data of excel. Excel 数据。
#     """
#     is_valid = False
#     try:
#         if os.path.isfile(filepath):
#             filename = os.path.basename(filepath)
#             if filename.split('.')[1] in ['xls', 'xlsx']:
#                 is_valid = True
#         data = None
#         if is_valid:
#             data = xlrd.open_workbook(filepath)
#     except Exception as xls_error:
#         raise TypeError("Can't get data from excel!") from xls_error
#     return data
# 
# def write_excel(filename="demo.xlsx", sheets=None):
#     """Write excel from data.
#     """
#     file = xlwt.Workbook() # 创建工作簿
#     for sheet in sheets:
#         new_sheet = file.add_sheet(sheet["name"], cell_overwrite_ok=True) # 创建sheet
#         info = sheet["info"]
#         # 原始方案：键值没有固定顺序导出 excel
#         # 生成表头
#         # for col, key in enumerate(info.keys()):
#             # new_sheet.write(0, col, info[key], set_excel_style('Arial Black', 220, True))
#             # new_sheet.write(1, col, key, set_excel_style('Arial Black', 220, True))
#         # 生成内容
#         # for index, item in enumerate(sheet["items"]):
#             # for col, key in enumerate(info.keys()):
#                 # new_sheet.write(index+2, col, item['n'][key])
# 
#         # Modify：使键值按照指定顺序导出 excel (2018-1-8)
#         for col, key in enumerate(info):
#             new_sheet.write(0, col, key[1], set_excel_style('Arial Black', 220, True))
#             new_sheet.write(1, col, key[0], set_excel_style('Arial Black', 220, True))
#         for index, item in enumerate(sheet["items"]):
#             for col, key in enumerate(info):
#                 new_sheet.write(index+2, col, item['n'][key[0]])
#     file.save(filename) # 保存文件
# 
# def set_excel_style(name, height, bold=False):
#     """Set excel style.
#     """
#     style = xlwt.XFStyle() # 初始化样式
#     font = xlwt.Font() # 为样式创建字体
#     font.name = name # 例如'Times New Roman'
#     font.bold = bold
#     font.color_index = 4
#     font.height = height
#     if bold:
#         borders = xlwt.Borders()
#         borders.left = 6
#         borders.right = 6
#         borders.top = 6
#         borders.bottom = 6
#         style.borders = borders
#     style.font = font
#     return style
# 
# Path: chat/semantic.py
# def get_tag(sentence, config):
#     """Get semantic tag of sentence. 获取句子语义标签。
#     """
#     iquestion = sentence.format(**config)
#     try:
#         keywords = analyse.extract_tags(iquestion, topK=1)
#         keyword = keywords[0]
#     except IndexError:
#         keyword = iquestion
#     tags = synonym_cut(keyword, 'wf') # tuple list
#     if tags:
#         tag = tags[0][1]
#         if not tag:
#             tag = keyword
#     else:
#         tag = keyword
#     return tag


import os
import string
import xlwt
from collections import OrderedDict
from py2neo import Graph, Node, Relationship, NodeSelector
from tkinter.filedialog import askopenfilename
from .mytools import read_excel, write_excel, set_excel_style
from .semantic import get_tag
                # 2.Select specified column
                col_format = ['A', 'B', 'C', 'D', 'E', 'F']
                try:
                    nrows = table.nrows
                    # ncols = table.ncols
                    str_upcase = [i for i in string.ascii_uppercase]
                    i_upcase = range(len(str_upcase))
                    ncols_dir = dict(zip(str_upcase, i_upcase))
                    col_index = [ncols_dir.get(i) for i in col_format]
                    # 前两行为表头
                    for i in range(2, nrows):
                        question = table.cell(i, col_index[0]).value
                        content = table.cell(i, col_index[1]).value
                        context = table.cell(i, col_index[2]).value
                        behavior = table.cell(i, col_index[3]).value
                        parameter = table.cell(i, col_index[4]).value
                        url = table.cell(i, col_index[5]).value
                        self.add_ts(question=question, content=content, context=context, \
                        behavior=behavior, parameter=parameter, url=url)
                except Exception as error:
                    print('Error: %s' %error)
                    return None
            else:
                print('Error! Data of %s is empty!' %sheet_name)
                return None

    def handle_excel(self, filename=None, custom_sheets=[]):
        """Processing data of excel.
        """
        assert filename is not None, "filename can not be None"

# Path: chat/mytools.py
# def read_excel(filepath):
#     """Get excel source.
# 
#     Args:
#         filepath: The full path of excel file. Excel 文件完整路径。
# 
#     Returns:
#         data: Data of excel. Excel 数据。
#     """
#     is_valid = False
#     try:
#         if os.path.isfile(filepath):
#             filename = os.path.basename(filepath)
#             if filename.split('.')[1] in ['xls', 'xlsx']:
#                 is_valid = True
#         data = None
#         if is_valid:
#             data = xlrd.open_workbook(filepath)
#     except Exception as xls_error:
#         raise TypeError("Can't get data from excel!") from xls_error
#     return data
# 
# def write_excel(filename="demo.xlsx", sheets=None):
#     """Write excel from data.
#     """
#     file = xlwt.Workbook() # 创建工作簿
#     for sheet in sheets:
#         new_sheet = file.add_sheet(sheet["name"], cell_overwrite_ok=True) # 创建sheet
#         info = sheet["info"]
#         # 原始方案：键值没有固定顺序导出 excel
#         # 生成表头
#         # for col, key in enumerate(info.keys()):
#             # new_sheet.write(0, col, info[key], set_excel_style('Arial Black', 220, True))
#             # new_sheet.write(1, col, key, set_excel_style('Arial Black', 220, True))
#         # 生成内容
#         # for index, item in enumerate(sheet["items"]):
#             # for col, key in enumerate(info.keys()):
#                 # new_sheet.write(index+2, col, item['n'][key])
# 
#         # Modify：使键值按照指定顺序导出 excel (2018-1-8)
#         for col, key in enumerate(info):
#             new_sheet.write(0, col, key[1], set_excel_style('Arial Black', 220, True))
#             new_sheet.write(1, col, key[0], set_excel_style('Arial Black', 220, True))
#         for index, item in enumerate(sheet["items"]):
#             for col, key in enumerate(info):
#                 new_sheet.write(index+2, col, item['n'][key[0]])
#     file.save(filename) # 保存文件
# 
# def set_excel_style(name, height, bold=False):
#     """Set excel style.
#     """
#     style = xlwt.XFStyle() # 初始化样式
#     font = xlwt.Font() # 为样式创建字体
#     font.name = name # 例如'Times New Roman'
#     font.bold = bold
#     font.color_index = 4
#     font.height = height
#     if bold:
#         borders = xlwt.Borders()
#         borders.left = 6
#         borders.right = 6
#         borders.top = 6
#         borders.bottom = 6
#         style.borders = borders
#     style.font = font
#     return style
# 
# Path: chat/semantic.py
# def get_tag(sentence, config):
#     """Get semantic tag of sentence. 获取句子语义标签。
#     """
#     iquestion = sentence.format(**config)
#     try:
#         keywords = analyse.extract_tags(iquestion, topK=1)
#         keyword = keywords[0]
#     except IndexError:
#         keyword = iquestion
#     tags = synonym_cut(keyword, 'wf') # tuple list
#     if tags:
#         tag = tags[0][1]
#         if not tag:
#             tag = keyword
#     else:
#         tag = keyword
#     return tag


# Path: chat/graph.py
import os
import string
import xlwt
from collections import OrderedDict
from py2neo import Graph, Node, Relationship, NodeSelector
from tkinter.filedialog import askopenfilename
from .mytools import read_excel, write_excel, set_excel_style
from .semantic import get_tag

                # 2.Select specified column
                col_format = ['A', 'B', 'C', 'D', 'E', 'F']
                try:
                    nrows = table.nrows
                    # ncols = table.ncols
                    str_upcase = [i for i in string.ascii_uppercase]
                    i_upcase = range(len(str_upcase))
                    ncols_dir = dict(zip(str_upcase, i_upcase))
                    col_index = [ncols_dir.get(i) for i in col_format]
                    # 前两行为表头
                    for i in range(2, nrows):
                        question = table.cell(i, col_index[0]).value
                        content = table.cell(i, col_index[1]).value
                        context = table.cell(i, col_index[2]).value
                        behavior = table.cell(i, col_index[3]).value
                        parameter = table.cell(i, col_index[4]).value
                        url = table.cell(i, col_index[5]).value
                        self.add_ts(question=question, content=content, context=context, \
                        behavior=behavior, parameter=parameter, url=url)
                except Exception as error:
                    print('Error: %s' %error)
                    return None
            else:
                print('Error! Data of %s is empty!' %sheet_name)
                return None

    def handle_excel(self, filename=None, custom_sheets=[]):
        """Processing data of excel.
        """
        assert filename is not None, "filename can not be None"

        data = read_excel(filename)