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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 io import BytesIO
  15. from nltk import word_tokenize
  16. from openpyxl import load_workbook
  17. from deepdoc.parser import is_english, random_choices
  18. from rag.nlp import huqie, stemmer
  19. from deepdoc.parser import ExcelParser
  20. class Excel(ExcelParser):
  21. def __call__(self, fnm, binary=None, callback=None):
  22. if not binary:
  23. wb = load_workbook(fnm)
  24. else:
  25. wb = load_workbook(BytesIO(binary))
  26. total = 0
  27. for sheetname in wb.sheetnames:
  28. total += len(list(wb[sheetname].rows))
  29. res, fails = [], []
  30. for sheetname in wb.sheetnames:
  31. ws = wb[sheetname]
  32. rows = list(ws.rows)
  33. for i, r in enumerate(rows):
  34. q, a = "", ""
  35. for cell in r:
  36. if not cell.value:
  37. continue
  38. if not q:
  39. q = str(cell.value)
  40. elif not a:
  41. a = str(cell.value)
  42. else:
  43. break
  44. if q and a:
  45. res.append((q, a))
  46. else:
  47. fails.append(str(i + 1))
  48. if len(res) % 999 == 0:
  49. callback(len(res) *
  50. 0.6 /
  51. total, ("Extract Q&A: {}".format(len(res)) +
  52. (f"{len(fails)} failure, line: %s..." %
  53. (",".join(fails[:3])) if fails else "")))
  54. callback(0.6, ("Extract Q&A: {}. ".format(len(res)) + (
  55. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  56. self.is_english = is_english(
  57. [rmPrefix(q) for q, _ in random_choices(res, k=30) if len(q) > 1])
  58. return res
  59. def rmPrefix(txt):
  60. return re.sub(
  61. r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  62. def beAdoc(d, q, a, eng):
  63. qprefix = "Question: " if eng else "问题:"
  64. aprefix = "Answer: " if eng else "回答:"
  65. d["content_with_weight"] = "\t".join(
  66. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  67. if eng:
  68. d["content_ltks"] = " ".join([stemmer.stem(w)
  69. for w in word_tokenize(q)])
  70. else:
  71. d["content_ltks"] = huqie.qie(q)
  72. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  73. return d
  74. def chunk(filename, binary=None, callback=None, **kwargs):
  75. """
  76. Excel and csv(txt) format files are supported.
  77. If the file is in excel format, there should be 2 column question and answer without header.
  78. And question column is ahead of answer column.
  79. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  80. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  81. All the deformed lines will be ignored.
  82. Every pair of Q&A will be treated as a chunk.
  83. """
  84. res = []
  85. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  86. callback(0.1, "Start to parse.")
  87. excel_parser = Excel()
  88. for q, a in excel_parser(filename, binary, callback):
  89. res.append(beAdoc({}, q, a, excel_parser.is_english))
  90. return res
  91. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  92. callback(0.1, "Start to parse.")
  93. txt = ""
  94. if binary:
  95. txt = binary.decode("utf-8")
  96. else:
  97. with open(filename, "r") as f:
  98. while True:
  99. l = f.readline()
  100. if not l:
  101. break
  102. txt += l
  103. lines = txt.split("\n")
  104. eng = is_english([rmPrefix(l) for l in lines[:100]])
  105. fails = []
  106. for i, line in enumerate(lines):
  107. arr = [l for l in line.split("\t") if len(l) > 1]
  108. if len(arr) != 2:
  109. fails.append(str(i))
  110. continue
  111. res.append(beAdoc({}, arr[0], arr[1], eng))
  112. if len(res) % 999 == 0:
  113. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  114. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  115. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  116. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  117. return res
  118. raise NotImplementedError(
  119. "file type not supported yet(pptx, pdf supported)")
  120. if __name__ == "__main__":
  121. import sys
  122. def dummy(a, b):
  123. pass
  124. chunk(sys.argv[1], callback=dummy)