是的-代码中的空行也计算在内。本文结尾给出了一个小的工作演示。
我们需要由Tesseract 5下载的python3和Sentence-Transformers软件包中基于distiluse-base-multilingual-cased的模型。那些已经知道接下来会发生什么的人将不会变得有趣。 同时,我们需要的一切如下所示:
前18行
import numpy as np
import os, sys, glob
os.environ['PATH'] += os.pathsep + os.path.join(os.getcwd(), 'Tesseract-OCR')
extensions = [
'.xlsx', '.docx', '.pptx',
'.pdf', '.txt', '.md', '.htm', 'html',
'.jpg', '.jpeg', '.png', '.gif'
]
import warnings; warnings.filterwarnings('ignore')
import torch, textract, pdfplumber
from cleantext import clean
from razdel import sentenize
from sklearn.neighbors import NearestNeighbors
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer('./distillUSE')
正如您所看到的那样,它将是很有必要的,并且一切似乎都已准备就绪,但是如果没有文件就无法做。特别是textract(不是来自Amazon,需要付费),在某种程度上不能与俄语pdf一起使用,因为您可以使用pdfplumber。此外,将文本分成句子是一项艰巨的任务,在这种情况下,razdel在俄语方面做得很好。
那些没有听说过scikit-learn的人-简而言之,
最主要的是实际上将(任何)文件的文本转换为矢量,这是它们的作用:
接下来的36行代码
def processor(path, embedder):
try:
if path.lower().endswith('.pdf'):
with pdfplumber.open(path) as pdf:
if len(pdf.pages):
text = ' '.join([
page.extract_text() or '' for page in pdf.pages if page
])
elif path.lower().endswith('.md') or path.lower().endswith('.txt'):
with open(path, 'r', encoding='UTF-8') as fd:
text = fd.read()
else:
text = textract.process(path, language='rus+eng').decode('UTF-8')
if path.lower()[-4:] in ['.jpg', 'jpeg', '.gif', '.png']:
text = clean(
text,
fix_unicode=False, lang='ru', to_ascii=False, lower=False,
no_line_breaks=True
)
else:
text = clean(
text,
lang='ru', to_ascii=False, lower=False, no_line_breaks=True
)
sentences = list(map(lambda substring: substring.text, sentenize(text)))
except Exception as exception:
return None
if not len(sentences):
return None
return {
'filepath': [path] * len(sentences),
'sentences': sentences,
'vectors': [vector.astype(float).tolist() for vector in embedder.encode(
sentences
)]
}
好吧,这仍然是技术问题-遍历所有文件,提取向量,然后按余弦距离找到最接近查询的内容。
剩余代码
def indexer(files, embedder):
for file in files:
processed = processor(file, embedder)
if processed is not None:
yield processed
def counter(path):
if not os.path.exists(path):
return None
for file in glob.iglob(path + '/**', recursive=True):
extension = os.path.splitext(file)[1].lower()
if extension in extensions:
yield file
def search(engine, text, sentences, files):
indices = engine.kneighbors(
embedder.encode([text])[0].astype(float).reshape(1, -1),
return_distance=True
)
distance = indices[0][0][0]
position = indices[1][0][0]
print(
' "%.3f' % (1 - distance / 2),
': "%s", "%s"' % (sentences[position], files[position])
)
print(' "%s"' % sys.argv[1])
paths = list(counter(sys.argv[1]))
print(' "%s"' % sys.argv[1])
db = list(indexer(paths, embedder))
sentences, files, vectors = [], [], []
for item in db:
sentences += item['sentences']
files += item['filepath']
vectors += item['vectors']
engine = NearestNeighbors(n_neighbors=1, metric='cosine').fit(
np.array(vectors).reshape(len(vectors), -1)
)
query = input(' : ')
while query:
search(engine, query, sentences, files)
query = input(' : ')
您可以像这样运行所有代码:
python3 app.py /path/to/your/files/
代码就是这样。
这是承诺的演示。
我从“ Lenta.ru”中获得了两个消息,一个通过臭名昭著的颜料放入了gif文件,另一个则放入了文本文件。
First.gif文件
第二个.txt文件
, . .
, - . , , , . . , .
, , , . . .
, - - .
, №71 , , , . 10 , . — .
, - . , , , . . , .
, , , . . .
, - - .
, №71 , , , . 10 , . — .
这是其工作方式的gif动画。当然,有了GPU,一切都会变得更加愉快。
谢谢阅读!我仍然希望这种方法对某人有用。