You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

qa.py 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import random
  2. import re
  3. from io import BytesIO
  4. from nltk import word_tokenize
  5. from openpyxl import load_workbook
  6. from rag.parser import is_english
  7. from rag.nlp import huqie, stemmer
  8. class Excel(object):
  9. def __call__(self, fnm, binary=None, callback=None):
  10. if not binary:
  11. wb = load_workbook(fnm)
  12. else:
  13. wb = load_workbook(BytesIO(binary))
  14. total = 0
  15. for sheetname in wb.sheetnames:
  16. total += len(list(wb[sheetname].rows))
  17. res, fails = [], []
  18. for sheetname in wb.sheetnames:
  19. ws = wb[sheetname]
  20. rows = list(ws.rows)
  21. for i, r in enumerate(rows):
  22. q, a = "", ""
  23. for cell in r:
  24. if not cell.value: continue
  25. if not q: q = str(cell.value)
  26. elif not a: a = str(cell.value)
  27. else: break
  28. if q and a: res.append((q, a))
  29. else: fails.append(str(i+1))
  30. if len(res) % 999 == 0:
  31. callback(len(res)*0.6/total, ("Extract Q&A: {}".format(len(res)) + (f"{len(fails)} failure, line: %s..."%(",".join(fails[:3])) if fails else "")))
  32. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  33. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  34. self.is_english = is_english([rmPrefix(q) for q, _ in random.choices(res, k=30) if len(q)>1])
  35. return res
  36. def rmPrefix(txt):
  37. return re.sub(r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  38. def beAdoc(d, q, a, eng):
  39. qprefix = "Question: " if eng else "问题:"
  40. aprefix = "Answer: " if eng else "回答:"
  41. d["content_with_weight"] = "\t".join([qprefix+rmPrefix(q), aprefix+rmPrefix(a)])
  42. if eng:
  43. d["content_ltks"] = " ".join([stemmer.stem(w) for w in word_tokenize(q)])
  44. else:
  45. d["content_ltks"] = huqie.qie(q)
  46. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  47. return d
  48. def chunk(filename, binary=None, callback=None, **kwargs):
  49. res = []
  50. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  51. callback(0.1, "Start to parse.")
  52. excel_parser = Excel()
  53. for q,a in excel_parser(filename, binary, callback):
  54. res.append(beAdoc({}, q, a, excel_parser.is_english))
  55. return res
  56. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  57. callback(0.1, "Start to parse.")
  58. txt = ""
  59. if binary:
  60. txt = binary.decode("utf-8")
  61. else:
  62. with open(filename, "r") as f:
  63. while True:
  64. l = f.readline()
  65. if not l: break
  66. txt += l
  67. lines = txt.split("\n")
  68. eng = is_english([rmPrefix(l) for l in lines[:100]])
  69. fails = []
  70. for i, line in enumerate(lines):
  71. arr = [l for l in line.split("\t") if len(l) > 1]
  72. if len(arr) != 2:
  73. fails.append(str(i))
  74. continue
  75. res.append(beAdoc({}, arr[0], arr[1], eng))
  76. if len(res) % 999 == 0:
  77. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  78. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  79. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  80. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  81. return res
  82. raise NotImplementedError("file type not supported yet(pptx, pdf supported)")
  83. if __name__== "__main__":
  84. import sys
  85. def dummy(a, b):
  86. pass
  87. chunk(sys.argv[1], callback=dummy)