Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

qa.py 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import re
  14. from copy import deepcopy
  15. from io import BytesIO
  16. from nltk import word_tokenize
  17. from openpyxl import load_workbook
  18. from rag.nlp import is_english, random_choices, find_codec
  19. from rag.nlp import rag_tokenizer
  20. from deepdoc.parser import ExcelParser
  21. class Excel(ExcelParser):
  22. def __call__(self, fnm, binary=None, callback=None):
  23. if not binary:
  24. wb = load_workbook(fnm)
  25. else:
  26. wb = load_workbook(BytesIO(binary))
  27. total = 0
  28. for sheetname in wb.sheetnames:
  29. total += len(list(wb[sheetname].rows))
  30. res, fails = [], []
  31. for sheetname in wb.sheetnames:
  32. ws = wb[sheetname]
  33. rows = list(ws.rows)
  34. for i, r in enumerate(rows):
  35. q, a = "", ""
  36. for cell in r:
  37. if not cell.value:
  38. continue
  39. if not q:
  40. q = str(cell.value)
  41. elif not a:
  42. a = str(cell.value)
  43. else:
  44. break
  45. if q and a:
  46. res.append((q, a))
  47. else:
  48. fails.append(str(i + 1))
  49. if len(res) % 999 == 0:
  50. callback(len(res) *
  51. 0.6 /
  52. total, ("Extract Q&A: {}".format(len(res)) +
  53. (f"{len(fails)} failure, line: %s..." %
  54. (",".join(fails[:3])) if fails else "")))
  55. callback(0.6, ("Extract Q&A: {}. ".format(len(res)) + (
  56. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  57. self.is_english = is_english(
  58. [rmPrefix(q) for q, _ in random_choices(res, k=30) if len(q) > 1])
  59. return res
  60. def rmPrefix(txt):
  61. return re.sub(
  62. r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  63. def beAdoc(d, q, a, eng):
  64. qprefix = "Question: " if eng else "问题:"
  65. aprefix = "Answer: " if eng else "回答:"
  66. d["content_with_weight"] = "\t".join(
  67. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  68. d["content_ltks"] = rag_tokenizer.tokenize(q)
  69. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  70. return d
  71. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  72. """
  73. Excel and csv(txt) format files are supported.
  74. If the file is in excel format, there should be 2 column question and answer without header.
  75. And question column is ahead of answer column.
  76. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  77. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  78. All the deformed lines will be ignored.
  79. Every pair of Q&A will be treated as a chunk.
  80. """
  81. eng = lang.lower() == "english"
  82. res = []
  83. doc = {
  84. "docnm_kwd": filename,
  85. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  86. }
  87. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  88. callback(0.1, "Start to parse.")
  89. excel_parser = Excel()
  90. for q, a in excel_parser(filename, binary, callback):
  91. res.append(beAdoc(deepcopy(doc), q, a, eng))
  92. return res
  93. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  94. callback(0.1, "Start to parse.")
  95. txt = ""
  96. if binary:
  97. encoding = find_codec(binary)
  98. txt = binary.decode(encoding)
  99. else:
  100. with open(filename, "r") as f:
  101. while True:
  102. l = f.readline()
  103. if not l:
  104. break
  105. txt += l
  106. lines = txt.split("\n")
  107. #is_english([rmPrefix(l) for l in lines[:100]])
  108. fails = []
  109. for i, line in enumerate(lines):
  110. arr = [l for l in line.split("\t") if len(l) > 1]
  111. if len(arr) != 2:
  112. fails.append(str(i))
  113. continue
  114. res.append(beAdoc(deepcopy(doc), arr[0], arr[1], eng))
  115. if len(res) % 999 == 0:
  116. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  117. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  118. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  119. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  120. return res
  121. raise NotImplementedError(
  122. "Excel and csv(txt) format files are supported.")
  123. if __name__ == "__main__":
  124. import sys
  125. def dummy(a, b):
  126. pass
  127. chunk(sys.argv[1], callback=dummy)