KevinHuSh commited on
Commit
004756c
·
1 Parent(s): 967c830

refine manual parser (#140)

Browse files
api/apps/conversation_app.py CHANGED
@@ -118,14 +118,13 @@ def message_fit_in(msg, max_length=4000):
118
 
119
  c = count()
120
  if c < max_length: return c, msg
121
- msg = [m for m in msg if m.role in ["system", "user"]]
122
- c = count()
123
- if c < max_length: return c, msg
124
  msg_ = [m for m in msg[:-1] if m.role == "system"]
125
  msg_.append(msg[-1])
126
  msg = msg_
127
  c = count()
128
  if c < max_length: return c, msg
 
129
  ll = num_tokens_from_string(msg_[0].content)
130
  l = num_tokens_from_string(msg_[-1].content)
131
  if ll / (ll + l) > 0.8:
 
118
 
119
  c = count()
120
  if c < max_length: return c, msg
121
+
 
 
122
  msg_ = [m for m in msg[:-1] if m.role == "system"]
123
  msg_.append(msg[-1])
124
  msg = msg_
125
  c = count()
126
  if c < max_length: return c, msg
127
+
128
  ll = num_tokens_from_string(msg_[0].content)
129
  l = num_tokens_from_string(msg_[-1].content)
130
  if ll / (ll + l) > 0.8:
api/apps/document_app.py CHANGED
@@ -218,7 +218,7 @@ def rm():
218
  ELASTICSEARCH.deleteByQuery(Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
219
 
220
  DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1, 0)
221
- if not DocumentService.delete_by_id(req["doc_id"]):
222
  return get_data_error_result(
223
  retmsg="Database error (Document removal)!")
224
 
 
218
  ELASTICSEARCH.deleteByQuery(Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
219
 
220
  DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1, 0)
221
+ if not DocumentService.delete(doc):
222
  return get_data_error_result(
223
  retmsg="Database error (Document removal)!")
224
 
api/db/db_models.py CHANGED
@@ -353,7 +353,7 @@ class User(DataBaseModel, UserMixin):
353
  email = CharField(max_length=255, null=False, help_text="email", index=True)
354
  avatar = TextField(null=True, help_text="avatar base64 string")
355
  language = CharField(max_length=32, null=True, help_text="English|Chinese", default="Chinese")
356
- color_schema = CharField(max_length=32, null=True, help_text="Bright|Dark", default="Dark")
357
  timezone = CharField(max_length=64, null=True, help_text="Timezone", default="UTC+8\tAsia/Shanghai")
358
  last_login_time = DateTimeField(null=True)
359
  is_authenticated = CharField(max_length=1, null=False, default="1")
 
353
  email = CharField(max_length=255, null=False, help_text="email", index=True)
354
  avatar = TextField(null=True, help_text="avatar base64 string")
355
  language = CharField(max_length=32, null=True, help_text="English|Chinese", default="Chinese")
356
+ color_schema = CharField(max_length=32, null=True, help_text="Bright|Dark", default="Bright")
357
  timezone = CharField(max_length=64, null=True, help_text="Timezone", default="UTC+8\tAsia/Shanghai")
358
  last_login_time = DateTimeField(null=True)
359
  is_authenticated = CharField(max_length=1, null=False, default="1")
api/db/init_data.py CHANGED
@@ -223,7 +223,7 @@ def init_llm_factory():
223
  "fid": factory_infos[3]["name"],
224
  "llm_name": "qwen-14B-chat",
225
  "tags": "LLM,CHAT,",
226
- "max_tokens": 8191,
227
  "model_type": LLMType.CHAT.value
228
  }, {
229
  "fid": factory_infos[3]["name"],
@@ -271,11 +271,15 @@ def init_llm_factory():
271
  pass
272
 
273
  """
 
274
  drop table llm;
275
- drop table factories;
276
  update tenant_llm set llm_factory='Tongyi-Qianwen' where llm_factory='通义千问';
277
  update tenant_llm set llm_factory='ZHIPU-AI' where llm_factory='智谱AI';
278
  update tenant set parser_ids='naive:General,one:One,qa:Q&A,resume:Resume,table:Table,laws:Laws,manual:Manual,book:Book,paper:Paper,presentation:Presentation,picture:Picture';
 
 
 
279
  """
280
 
281
 
 
223
  "fid": factory_infos[3]["name"],
224
  "llm_name": "qwen-14B-chat",
225
  "tags": "LLM,CHAT,",
226
+ "max_tokens": 4096,
227
  "model_type": LLMType.CHAT.value
228
  }, {
229
  "fid": factory_infos[3]["name"],
 
271
  pass
272
 
273
  """
274
+ modify service_config
275
  drop table llm;
276
+ drop table llm_factories;
277
  update tenant_llm set llm_factory='Tongyi-Qianwen' where llm_factory='通义千问';
278
  update tenant_llm set llm_factory='ZHIPU-AI' where llm_factory='智谱AI';
279
  update tenant set parser_ids='naive:General,one:One,qa:Q&A,resume:Resume,table:Table,laws:Laws,manual:Manual,book:Book,paper:Paper,presentation:Presentation,picture:Picture';
280
+ alter table knowledgebase modify avatar longtext;
281
+ alter table user modify avatar longtext;
282
+ alter table dialog modify icon longtext;
283
  """
284
 
285
 
api/db/services/document_service.py CHANGED
@@ -60,6 +60,15 @@ class DocumentService(CommonService):
60
  raise RuntimeError("Database error (Knowledgebase)!")
61
  return doc
62
 
 
 
 
 
 
 
 
 
 
63
  @classmethod
64
  @DB.connection_context()
65
  def get_newly_uploaded(cls, tm, mod=0, comm=1, items_per_page=64):
 
60
  raise RuntimeError("Database error (Knowledgebase)!")
61
  return doc
62
 
63
+ @classmethod
64
+ @DB.connection_context()
65
+ def delete(cls, doc):
66
+ e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
67
+ if not KnowledgebaseService.update_by_id(
68
+ kb.id, {"doc_num": kb.doc_num - 1}):
69
+ raise RuntimeError("Database error (Knowledgebase)!")
70
+ return cls.delete_by_id(doc.id)
71
+
72
  @classmethod
73
  @DB.connection_context()
74
  def get_newly_uploaded(cls, tm, mod=0, comm=1, items_per_page=64):
deepdoc/parser/pdf_parser.py CHANGED
@@ -11,7 +11,7 @@ import logging
11
  from PIL import Image, ImageDraw
12
  import numpy as np
13
 
14
- from api.db import ParserType
15
  from deepdoc.vision import OCR, Recognizer, LayoutRecognizer, TableStructureRecognizer
16
  from rag.nlp import huqie
17
  from copy import deepcopy
@@ -288,9 +288,9 @@ class HuParser:
288
  for b in bxs])
289
  self.boxes.append(bxs)
290
 
291
- def _layouts_rec(self, ZM):
292
  assert len(self.page_images) == len(self.boxes)
293
- self.boxes, self.page_layout = self.layouter(self.page_images, self.boxes, ZM)
294
  # cumlative Y
295
  for i in range(len(self.boxes)):
296
  self.boxes[i]["top"] += \
@@ -908,6 +908,23 @@ class HuParser:
908
  self.page_images.append(img)
909
  self.page_chars.append([])
910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911
  logging.info("Images converted.")
912
  self.is_english = [re.search(r"[a-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join(
913
  random.choices([c["text"] for c in self.page_chars[i]], k=min(100, len(self.page_chars[i]))))) for i in
 
11
  from PIL import Image, ImageDraw
12
  import numpy as np
13
 
14
+ from PyPDF2 import PdfReader as pdf2_read
15
  from deepdoc.vision import OCR, Recognizer, LayoutRecognizer, TableStructureRecognizer
16
  from rag.nlp import huqie
17
  from copy import deepcopy
 
288
  for b in bxs])
289
  self.boxes.append(bxs)
290
 
291
+ def _layouts_rec(self, ZM, drop=True):
292
  assert len(self.page_images) == len(self.boxes)
293
+ self.boxes, self.page_layout = self.layouter(self.page_images, self.boxes, ZM, drop=drop)
294
  # cumlative Y
295
  for i in range(len(self.boxes)):
296
  self.boxes[i]["top"] += \
 
908
  self.page_images.append(img)
909
  self.page_chars.append([])
910
 
911
+ self.outlines = []
912
+ try:
913
+ self.pdf = pdf2_read(fnm if isinstance(fnm, str) else BytesIO(fnm))
914
+ outlines = self.pdf.outline
915
+
916
+ def dfs(arr, depth):
917
+ for a in arr:
918
+ if isinstance(a, dict):
919
+ self.outlines.append((a["/Title"], depth))
920
+ continue
921
+ dfs(a, depth+1)
922
+ dfs(outlines, 0)
923
+ except Exception as e:
924
+ logging.warning(f"Outlines exception: {e}")
925
+ if not self.outlines:
926
+ logging.warning(f"Miss outlines")
927
+
928
  logging.info("Images converted.")
929
  self.is_english = [re.search(r"[a-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join(
930
  random.choices([c["text"] for c in self.page_chars[i]], k=min(100, len(self.page_chars[i]))))) for i in
deepdoc/vision/layout_recognizer.py CHANGED
@@ -39,7 +39,7 @@ class LayoutRecognizer(Recognizer):
39
  super().__init__(self.labels, domain, os.path.join(get_project_base_directory(), "rag/res/deepdoc/"))
40
  self.garbage_layouts = ["footer", "header", "reference"]
41
 
42
- def __call__(self, image_list, ocr_res, scale_factor=3, thr=0.2, batch_size=16):
43
  def __is_garbage(b):
44
  patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
45
  r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
@@ -88,7 +88,11 @@ class LayoutRecognizer(Recognizer):
88
  i += 1
89
  continue
90
  lts_[ii]["visited"] = True
91
- if lts_[ii]["type"] in self.garbage_layouts:
 
 
 
 
92
  if lts_[ii]["type"] not in garbages:
93
  garbages[lts_[ii]["type"]] = []
94
  garbages[lts_[ii]["type"]].append(bxs[i]["text"])
 
39
  super().__init__(self.labels, domain, os.path.join(get_project_base_directory(), "rag/res/deepdoc/"))
40
  self.garbage_layouts = ["footer", "header", "reference"]
41
 
42
+ def __call__(self, image_list, ocr_res, scale_factor=3, thr=0.2, batch_size=16, drop=True):
43
  def __is_garbage(b):
44
  patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
45
  r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
 
88
  i += 1
89
  continue
90
  lts_[ii]["visited"] = True
91
+ keep_feats = [
92
+ lts_[ii]["type"] == "footer" and bxs[i]["bottom"] < image_list[pn].size[1]*0.9/scale_factor,
93
+ lts_[ii]["type"] == "header" and bxs[i]["top"] > image_list[pn].size[1]*0.1/scale_factor,
94
+ ]
95
+ if drop and lts_[ii]["type"] in self.garbage_layouts and not any(keep_feats):
96
  if lts_[ii]["type"] not in garbages:
97
  garbages[lts_[ii]["type"]] = []
98
  garbages[lts_[ii]["type"]].append(bxs[i]["text"])
rag/app/manual.py CHANGED
@@ -51,15 +51,30 @@ class Pdf(PdfParser):
51
 
52
  # set pivot using the most frequent type of title,
53
  # then merge between 2 pivot
54
- bull = bullets_category([b["text"] for b in self.boxes])
55
- most_level, levels = title_frequency(bull, [(b["text"], b.get("layout_no","")) for b in self.boxes])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  assert len(self.boxes) == len(levels)
57
  sec_ids = []
58
  sid = 0
59
  for i, lvl in enumerate(levels):
60
  if lvl <= most_level and i > 0 and lvl != levels[i-1]: sid += 1
61
  sec_ids.append(sid)
62
- #print(lvl, self.boxes[i]["text"], most_level)
63
 
64
  sections = [(b["text"], sec_ids[i], self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)]
65
  for (img, rows), poss in tbls:
@@ -67,13 +82,16 @@ class Pdf(PdfParser):
67
 
68
  chunks = []
69
  last_sid = -2
 
70
  for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
71
  poss = "\t".join([tag(*pos) for pos in poss])
72
- if sec_id == last_sid or sec_id == -1:
73
  if chunks:
74
  chunks[-1] += "\n" + txt + poss
 
75
  continue
76
  chunks.append(txt + poss)
 
77
  if sec_id >-1: last_sid = sec_id
78
  return chunks, tbls
79
 
@@ -97,37 +115,17 @@ def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", ca
97
  # is it English
98
  eng = lang.lower() == "english"#pdf_parser.is_english
99
 
100
- i = 0
101
- chunk = []
102
- tk_cnt = 0
103
  res = tokenize_table(tbls, doc, eng)
104
- def add_chunk():
105
- nonlocal chunk, res, doc, pdf_parser, tk_cnt
106
  d = copy.deepcopy(doc)
107
- ck = "\n".join(chunk)
108
- tokenize(d, pdf_parser.remove_tag(ck), eng)
109
  d["image"], poss = pdf_parser.crop(ck, need_position=True)
110
  add_positions(d, poss)
 
111
  res.append(d)
112
- chunk = []
113
- tk_cnt = 0
114
-
115
- while i < len(cks):
116
- if tk_cnt > 256: add_chunk()
117
- txt = cks[i]
118
- txt_ = pdf_parser.remove_tag(txt)
119
- i += 1
120
- cnt = num_tokens_from_string(txt_)
121
- chunk.append(txt)
122
- tk_cnt += cnt
123
- if chunk: add_chunk()
124
-
125
- for i, d in enumerate(res):
126
- print(d)
127
- # d["image"].save(f"./logs/{i}.jpg")
128
  return res
129
 
130
 
 
131
  if __name__ == "__main__":
132
  import sys
133
  def dummy(prog=None, msg=""):
 
51
 
52
  # set pivot using the most frequent type of title,
53
  # then merge between 2 pivot
54
+ if len(self.boxes)>0 and len(self.outlines)/len(self.boxes) > 0.1:
55
+ max_lvl = max([lvl for _, lvl in self.outlines])
56
+ most_level = max(0, max_lvl-1)
57
+ levels = []
58
+ for b in self.boxes:
59
+ for t,lvl in self.outlines:
60
+ tks = set([t[i]+t[i+1] for i in range(len(t)-1)])
61
+ tks_ = set([b["text"][i]+b["text"][i+1] for i in range(min(len(t), len(b["text"])-1))])
62
+ if len(set(tks & tks_))/max([len(tks), len(tks_), 1]) > 0.8:
63
+ levels.append(lvl)
64
+ break
65
+ else:
66
+ levels.append(max_lvl + 1)
67
+ else:
68
+ bull = bullets_category([b["text"] for b in self.boxes])
69
+ most_level, levels = title_frequency(bull, [(b["text"], b.get("layout_no","")) for b in self.boxes])
70
+
71
  assert len(self.boxes) == len(levels)
72
  sec_ids = []
73
  sid = 0
74
  for i, lvl in enumerate(levels):
75
  if lvl <= most_level and i > 0 and lvl != levels[i-1]: sid += 1
76
  sec_ids.append(sid)
77
+ #print(lvl, self.boxes[i]["text"], most_level, sid)
78
 
79
  sections = [(b["text"], sec_ids[i], self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)]
80
  for (img, rows), poss in tbls:
 
82
 
83
  chunks = []
84
  last_sid = -2
85
+ tk_cnt = 0
86
  for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
87
  poss = "\t".join([tag(*pos) for pos in poss])
88
+ if tk_cnt < 2048 and (sec_id == last_sid or sec_id == -1):
89
  if chunks:
90
  chunks[-1] += "\n" + txt + poss
91
+ tk_cnt += num_tokens_from_string(txt)
92
  continue
93
  chunks.append(txt + poss)
94
+ tk_cnt = num_tokens_from_string(txt)
95
  if sec_id >-1: last_sid = sec_id
96
  return chunks, tbls
97
 
 
115
  # is it English
116
  eng = lang.lower() == "english"#pdf_parser.is_english
117
 
 
 
 
118
  res = tokenize_table(tbls, doc, eng)
119
+ for ck in cks:
 
120
  d = copy.deepcopy(doc)
 
 
121
  d["image"], poss = pdf_parser.crop(ck, need_position=True)
122
  add_positions(d, poss)
123
+ tokenize(d, pdf_parser.remove_tag(ck), eng)
124
  res.append(d)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  return res
126
 
127
 
128
+
129
  if __name__ == "__main__":
130
  import sys
131
  def dummy(prog=None, msg=""):
rag/app/one.py CHANGED
@@ -10,12 +10,10 @@
10
  # See the License for the specific language governing permissions and
11
  # limitations under the License.
12
  #
13
- import copy
14
  import re
15
  from rag.app import laws
16
- from rag.nlp import huqie, is_english, tokenize, naive_merge, tokenize_table, add_positions
17
  from deepdoc.parser import PdfParser, ExcelParser
18
- from rag.settings import cron_logger
19
 
20
 
21
  class Pdf(PdfParser):
@@ -33,7 +31,7 @@ class Pdf(PdfParser):
33
 
34
  from timeit import default_timer as timer
35
  start = timer()
36
- self._layouts_rec(zoomin)
37
  callback(0.63, "Layout analysis finished.")
38
  print("paddle layouts:", timer() - start)
39
  self._table_transformer_job(zoomin)
 
10
  # See the License for the specific language governing permissions and
11
  # limitations under the License.
12
  #
 
13
  import re
14
  from rag.app import laws
15
+ from rag.nlp import huqie, tokenize
16
  from deepdoc.parser import PdfParser, ExcelParser
 
17
 
18
 
19
  class Pdf(PdfParser):
 
31
 
32
  from timeit import default_timer as timer
33
  start = timer()
34
+ self._layouts_rec(zoomin, drop=False)
35
  callback(0.63, "Layout analysis finished.")
36
  print("paddle layouts:", timer() - start)
37
  self._table_transformer_job(zoomin)
rag/nlp/search.py CHANGED
@@ -215,7 +215,7 @@ class Dealer:
215
  else:
216
  pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
217
  for i in range(1, len(pieces)):
218
- if re.match(r"[a-z][.?;!][ \n]", pieces[i]):
219
  pieces[i - 1] += pieces[i][0]
220
  pieces[i] = pieces[i][1:]
221
  idx = []
@@ -243,7 +243,8 @@ class Dealer:
243
  chunks_tks,
244
  tkweight, vtweight)
245
  mx = np.max(sim) * 0.99
246
- if mx < 0.65:
 
247
  continue
248
  cites[idx[i]] = list(
249
  set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
 
215
  else:
216
  pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
217
  for i in range(1, len(pieces)):
218
+ if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
219
  pieces[i - 1] += pieces[i][0]
220
  pieces[i] = pieces[i][1:]
221
  idx = []
 
243
  chunks_tks,
244
  tkweight, vtweight)
245
  mx = np.max(sim) * 0.99
246
+ es_logger.info("{} SIM: {}".format(pieces_[i], mx))
247
+ if mx < 0.63:
248
  continue
249
  cites[idx[i]] = list(
250
  set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
rag/svr/task_broker.py CHANGED
@@ -82,8 +82,8 @@ def dispatch():
82
  tsks = []
83
  if r["type"] == FileType.PDF.value:
84
  pages = PdfParser.total_page_number(r["name"], MINIO.get(r["kb_id"], r["location"]))
85
- page_size = 5
86
- if r["parser_id"] == "paper": page_size = 12
87
  if r["parser_id"] == "one": page_size = 1000000000
88
  for s,e in r["parser_config"].get("pages", [(0,100000)]):
89
  e = min(e, pages)
 
82
  tsks = []
83
  if r["type"] == FileType.PDF.value:
84
  pages = PdfParser.total_page_number(r["name"], MINIO.get(r["kb_id"], r["location"]))
85
+ page_size = 12
86
+ if r["parser_id"] == "paper": page_size = 22
87
  if r["parser_id"] == "one": page_size = 1000000000
88
  for s,e in r["parser_config"].get("pages", [(0,100000)]):
89
  e = min(e, pages)