# 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
    
    def upload(self, pattern='qa', names=[]):
        """上传知识库
        """
        if pattern == 'qa':
            filename = askopenfilename(filetypes=[('QA', '*.xls')])
            self.handle_excel(filename, custom_sheets=names)
        elif pattern == 'ts':
            filename = askopenfilename(filetypes=[('测试标准', '*.xls')])
            self.handle_ts(filename, custom_sheets=names)

    def generate_testcases(self, *, filename=None, custom_sheets=None, savedir='.'):
        """Generating test cases from data of excel.
        
        custom_sheets 选择的子表格集合
        """
        assert filename is not None, "filename can not be None"
        data = read_excel(filename) # 读取已有excel-知识库
        data_sheets = data.sheet_names()
        if custom_sheets:
            sheet_names = list(set(data_sheets).intersection(set(custom_sheets)))
        else:
            sheet_names = data_sheets
            
        file = xlwt.Workbook() # 创建新excel-测试用例
        new_sheet = file.add_sheet("NluTest", cell_overwrite_ok=True) # 创建sheet
        keys = ["问题", "答案", "是否通过", "改进建议"]
        # 生成表头
        new_sheet.write(0, 0, "本地语义常见命令问答测试", set_excel_style('Arial Black', 220, True))
        for col, key in enumerate(keys):

# 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

    
    def upload(self, pattern='qa', names=[]):
        """上传知识库
        """
        if pattern == 'qa':
            filename = askopenfilename(filetypes=[('QA', '*.xls')])
            self.handle_excel(filename, custom_sheets=names)
        elif pattern == 'ts':
            filename = askopenfilename(filetypes=[('测试标准', '*.xls')])
            self.handle_ts(filename, custom_sheets=names)

    def generate_testcases(self, *, filename=None, custom_sheets=None, savedir='.'):
        """Generating test cases from data of excel.
        
        custom_sheets 选择的子表格集合
        """
        assert filename is not None, "filename can not be None"
        data = read_excel(filename) # 读取已有excel-知识库
        data_sheets = data.sheet_names()
        if custom_sheets:
            sheet_names = list(set(data_sheets).intersection(set(custom_sheets)))
        else:
            sheet_names = data_sheets
            
        file = xlwt.Workbook() # 创建新excel-测试用例
        new_sheet = file.add_sheet("NluTest", cell_overwrite_ok=True) # 创建sheet
        keys = ["问题", "答案", "是否通过", "改进建议"]
        # 生成表头
        new_sheet.write(0, 0, "本地语义常见命令问答测试", set_excel_style('Arial Black', 220, True))
        for col, key in enumerate(keys):

            new_sheet.write(1, col, key, set_excel_style('Arial Black', 220, True))