Browse Source

adjust hierarchical_merge strategy (#100)

tags/v0.1.0
KevinHuSh 1 year ago
parent
commit
d7c362f237
No account linked to committer's email address
3 changed files with 77 additions and 45 deletions
  1. 0
    1
      rag/app/laws.py
  2. 75
    42
      rag/nlp/__init__.py
  3. 2
    2
      rag/nlp/search.py

+ 0
- 1
rag/app/laws.py View File

if not l:break if not l:break
txt += l txt += l
sections = txt.split("\n") sections = txt.split("\n")
sections = txt.split("\n")
sections = [l for l in sections if l] sections = [l for l in sections if l]
callback(0.8, "Finish parsing.") callback(0.8, "Finish parsing.")
else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)") else: raise NotImplementedError("file type not supported yet(docx, pdf, txt supported)")

+ 75
- 42
rag/nlp/__init__.py View File

import random
from rag.utils import num_tokens_from_string
from . import huqie
from nltk import word_tokenize
import re
import copy import copy
from nltk.stem import PorterStemmer from nltk.stem import PorterStemmer
stemmer = PorterStemmer() stemmer = PorterStemmer()
import re
from nltk import word_tokenize
from . import huqie
from rag.utils import num_tokens_from_string
import random
BULLET_PATTERN = [[ BULLET_PATTERN = [[
r"第[零一二三四五六七八九十百0-9]+(分?编|部分)", r"第[零一二三四五六七八九十百0-9]+(分?编|部分)",
maxium = 0 maxium = 0
res = -1 res = -1
for i, h in enumerate(hits): for i, h in enumerate(hits):
if h <= maxium: continue
if h <= maxium:
continue
res = i res = i
maxium = h maxium = h
return res return res
d["content_with_weight"] = t d["content_with_weight"] = t
if eng: if eng:
t = re.sub(r"([a-z])-([a-z])", r"\1\2", t) t = re.sub(r"([a-z])-([a-z])", r"\1\2", t)
d["content_ltks"] = " ".join([stemmer.stem(w) for w in word_tokenize(t)])
d["content_ltks"] = " ".join([stemmer.stem(w)
for w in word_tokenize(t)])
else: else:
d["content_ltks"] = huqie.qie(t) d["content_ltks"] = huqie.qie(t)
d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"]) d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
res = [] res = []
# add tables # add tables
for (img, rows), poss in tbls: for (img, rows), poss in tbls:
if not rows:continue
if not rows:
continue
if isinstance(rows, str): if isinstance(rows, str):
d = copy.deepcopy(doc) d = copy.deepcopy(doc)
r = re.sub(r"<[^<>]{,12}>", "", rows) r = re.sub(r"<[^<>]{,12}>", "", rows)
def add_positions(d, poss): def add_positions(d, poss):
if not poss:return
if not poss:
return
d["page_num_int"] = [] d["page_num_int"] = []
d["position_int"] = [] d["position_int"] = []
d["top_int"] = [] d["top_int"] = []
for pn, left, right, top, bottom in poss: for pn, left, right, top, bottom in poss:
d["page_num_int"].append(pn+1)
d["page_num_int"].append(pn + 1)
d["top_int"].append(top) d["top_int"].append(top)
d["position_int"].append((pn+1, left, right, top, bottom))
d["position_int"].append((pn + 1, left, right, top, bottom))
d["top_int"] = d["top_int"][:1] d["top_int"] = d["top_int"][:1]
while i < len(sections): while i < len(sections):
def get(i): def get(i):
nonlocal sections nonlocal sections
return (sections[i] if type(sections[i]) == type("") else sections[i][0]).strip()
return (sections[i] if isinstance(sections[i],
type("")) else sections[i][0]).strip()
if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$", if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$",
re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)): re.sub(r"( | |\u3000)+", "", get(i).split("@@")[0], re.IGNORECASE)):
i += 1 i += 1
continue continue
sections.pop(i) sections.pop(i)
if i >= len(sections): break
if i >= len(sections):
break
prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2]) prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
while not prefix: while not prefix:
sections.pop(i) sections.pop(i)
if i >= len(sections): break
if i >= len(sections):
break
prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2]) prefix = get(i)[:3] if not eng else " ".join(get(i).split(" ")[:2])
sections.pop(i) sections.pop(i)
if i >= len(sections) or not prefix: break
if i >= len(sections) or not prefix:
break
for j in range(i, min(i + 128, len(sections))): for j in range(i, min(i + 128, len(sections))):
if not re.match(prefix, get(j)): if not re.match(prefix, get(j)):
continue continue
for _ in range(i, j): sections.pop(i)
for _ in range(i, j):
sections.pop(i)
break break
def make_colon_as_title(sections): def make_colon_as_title(sections):
if not sections: return []
if type(sections[0]) == type(""): return sections
if not sections:
return []
if isinstance(sections[0], type("")):
return sections
i = 0 i = 0
while i < len(sections): while i < len(sections):
txt, layout = sections[i] txt, layout = sections[i]
def hierarchical_merge(bull, sections, depth): def hierarchical_merge(bull, sections, depth):
if not sections or bull < 0: return []
if type(sections[0]) == type(""): sections = [(s, "") for s in sections]
sections = [(t,o) for t, o in sections if t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
if not sections or bull < 0:
return []
if isinstance(sections[0], type("")):
sections = [(s, "") for s in sections]
sections = [(t, o) for t, o in sections if
t and len(t.split("@")[0].strip()) > 1 and not re.match(r"[0-9]+$", t.split("@")[0].strip())]
bullets_size = len(BULLET_PATTERN[bull]) bullets_size = len(BULLET_PATTERN[bull])
levels = [[] for _ in range(bullets_size + 2)] levels = [[] for _ in range(bullets_size + 2)]
def not_title(txt): def not_title(txt):
if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt): return False
if len(txt.split(" "))>12 or (txt.find(" ")<0 and len(txt)) >= 32: return True
if re.match(r"第[零一二三四五六七八九十百0-9]+条", txt):
return False
if len(txt.split(" ")) > 12 or (txt.find(" ") < 0 and len(txt) >= 32):
return True
return re.search(r"[,;,。;!!]", txt) return re.search(r"[,;,。;!!]", txt)
for i, (txt, layout) in enumerate(sections): for i, (txt, layout) in enumerate(sections):
for j, p in enumerate(BULLET_PATTERN[bull]): for j, p in enumerate(BULLET_PATTERN[bull]):
if re.match(p, txt.strip()) and not not_title(txt):
if re.match(p, txt.strip()):
levels[j].append(i) levels[j].append(i)
break break
else: else:
else: else:
levels[bullets_size + 1].append(i) levels[bullets_size + 1].append(i)
sections = [t for t, _ in sections] sections = [t for t, _ in sections]
#for s in sections: print("--", s)
# for s in sections: print("--", s)
def binary_search(arr, target): def binary_search(arr, target):
if not arr: return -1
if target > arr[-1]: return len(arr) - 1
if target < arr[0]: return -1
if not arr:
return -1
if target > arr[-1]:
return len(arr) - 1
if target < arr[0]:
return -1
s, e = 0, len(arr) s, e = 0, len(arr)
while e - s > 1: while e - s > 1:
i = (e + s) // 2 i = (e + s) // 2
levels = levels[::-1] levels = levels[::-1]
for i, arr in enumerate(levels[:depth]): for i, arr in enumerate(levels[:depth]):
for j in arr: for j in arr:
if readed[j]: continue
if readed[j]:
continue
readed[j] = True readed[j] = True
cks.append([j]) cks.append([j])
if i + 1 == len(levels) - 1: continue
if i + 1 == len(levels) - 1:
continue
for ii in range(i + 1, len(levels)): for ii in range(i + 1, len(levels)):
jj = binary_search(levels[ii], j) jj = binary_search(levels[ii], j)
if jj < 0: continue
if jj > cks[-1][-1]: cks[-1].pop(-1)
if jj < 0:
continue
if jj > cks[-1][-1]:
cks[-1].pop(-1)
cks[-1].append(levels[ii][jj]) cks[-1].append(levels[ii][jj])
for ii in cks[-1]: readed[ii] = True
for ii in cks[-1]:
readed[ii] = True
if not cks:return cks
if not cks:
return cks
for i in range(len(cks)): for i in range(len(cks)):
cks[i] = [sections[j] for j in cks[i][::-1]] cks[i] = [sections[j] for j in cks[i][::-1]]
def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"): def naive_merge(sections, chunk_token_num=128, delimiter="\n。;!?"):
if not sections: return []
if type(sections[0]) == type(""): sections = [(s, "") for s in sections]
if not sections:
return []
if isinstance(sections[0], type("")):
sections = [(s, "") for s in sections]
cks = [""] cks = [""]
tk_nums = [0] tk_nums = [0]
def add_chunk(t, pos): def add_chunk(t, pos):
nonlocal cks, tk_nums, delimiter nonlocal cks, tk_nums, delimiter
tnum = num_tokens_from_string(t) tnum = num_tokens_from_string(t)
if tnum < 8: pos = ""
if tnum < 8:
pos = ""
if tk_nums[-1] > chunk_token_num: if tk_nums[-1] > chunk_token_num:
if t.find(pos) < 0: t += pos
if t.find(pos) < 0:
t += pos
cks.append(t) cks.append(t)
tk_nums.append(tnum) tk_nums.append(tnum)
else: else:
if cks[-1].find(pos) < 0: t += pos
if cks[-1].find(pos) < 0:
t += pos
cks[-1] += t cks[-1] += t
tk_nums[-1] += tnum tk_nums[-1] += tnum
s, e = 0, 1 s, e = 0, 1
while e < len(sec): while e < len(sec):
if sec[e] in delimiter: if sec[e] in delimiter:
add_chunk(sec[s: e+1], pos)
add_chunk(sec[s: e + 1], pos)
s = e + 1 s = e + 1
e = s + 1 e = s + 1
else: else:
e += 1 e += 1
if s < e: add_chunk(sec[s: e], pos)
if s < e:
add_chunk(sec[s: e], pos)
return cks return cks

+ 2
- 2
rag/nlp/search.py View File

) )
else: else:
s = s.sort( s = s.sort(
{"page_num_int": {"order": "asc", "unmapped_type": "float"}},
{"top_int": {"order": "asc", "unmapped_type": "float", "mode" : "avg"}},
{"page_num_int": {"order": "asc", "unmapped_type": "float", "mode" : "avg"}},
{"top_int": {"order": "asc", "unmapped_type": "float", "mode": "avg"}},
{"create_time": {"order": "desc", "unmapped_type": "date"}}, {"create_time": {"order": "desc", "unmapped_type": "date"}},
{"create_timestamp_flt": {"order": "desc", "unmapped_type": "float"}} {"create_timestamp_flt": {"order": "desc", "unmapped_type": "float"}}
) )

Loading…
Cancel
Save