- Java锁的逻辑(结合对象头和ObjectMonitor)
- 还在用饼状图?来瞧瞧这些炫酷的百分比可视化新图形(附代码实现)⛵
- 自动注册实体类到EntityFrameworkCore上下文,并适配ABP及ABPVNext
- 基于Sklearn机器学习代码实战
在前面的文章中,我们介绍了实现原理和基本环境安装。本文将重点介绍数据训练的流程,以及如何加载、切割、训练数据,并使用向量数据库Milvus进行数据存储.
在本文中,我们使用了Milvus作为向量数据库。读者可以参考之前的文章《基于GPT搭建私有知识库聊天机器人(二)环境安装》来准备其他基础环境.
数据训练的流程包括准备PDF文档、上传至系统文件目录、开始训练、加载文件内容、内容切割和存储至向量数据库。下面是整个流程的流程图:
@app.route('/upload', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# 获取文本内容
text = request.form.get('name')
# 获取文件内容
file = request.files.get('file')
if file:
# 保存文件到服务器
filename = file.filename
file.save(os.path.join(KNOWLEDGE_FOLDER, text, filename))
file_path = os.path.join(KNOWLEDGE_FOLDER, text, filename)
else:
file_path = None
return jsonify({'message': '上传成功', 'fileServicePath': file_path})
return render_template('index.html')
# 映射文件加载
LOADER_MAPPING = {
".csv": (CSVLoader, {}),
".docx": (Docx2txtLoader, {}),
".doc": (UnstructuredWordDocumentLoader, {}),
".docx": (UnstructuredWordDocumentLoader, {}),
".enex": (EverNoteLoader, {}),
".eml": (MyElmLoader, {}),
".epub": (UnstructuredEPubLoader, {}),
".html": (UnstructuredHTMLLoader, {}),
".md": (UnstructuredMarkdownLoader, {}),
".odt": (UnstructuredODTLoader, {}),
".pdf": (PDFMinerLoader, {}),
".ppt": (UnstructuredPowerPointLoader, {}),
".pptx": (UnstructuredPowerPointLoader, {}),
".txt": (TextLoader, {"encoding": "utf8"}),
}
def load_single_document(file_path: str) -> List[Document]:
ext = "." + file_path.rsplit(".", 1)[-1]
if ext in LOADER_MAPPING:
loader_class, loader_args = LOADER_MAPPING[ext]
loader = loader_class(file_path, **loader_args)
return loader.load()
raise ValueError(f"文件不存在 '{ext}'")
# 加载文件
def load_documents_knowledge(source_dir: str, secondary_directories: str) -> List[Document]:
"""
Loads all documents from the source documents directory, ignoring specified files
"""
all_files = []
for ext in LOADER_MAPPING:
all_files.extend(
glob.glob(os.path.join(source_dir, secondary_directories, f"**/*{ext}"), recursive=True)
)
filtered_files = [file_path for file_path in all_files if file_path]
with Pool(processes=os.cpu_count()) as pool:
results = []
with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
for i, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
results.extend(docs)
pbar.update()
return results
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
texts = text_splitter.split_documents(documents)
Milvus.from_documents(
texts,
collection_name=collection_name,
embedding=embeddings,
connection_args={"host": MILVUS_HOST, "port": MILVUS_PORT}
)
#!/usr/bin/env python3
import glob
import os
import shutil
from multiprocessing import Pool
from typing import List
from dotenv import load_dotenv
from langchain.docstore.document import Document
from langchain.document_loaders import (
CSVLoader,
EverNoteLoader,
PDFMinerLoader,
TextLoader,
UnstructuredEmailLoader,
UnstructuredEPubLoader,
UnstructuredHTMLLoader,
UnstructuredMarkdownLoader,
UnstructuredODTLoader,
UnstructuredPowerPointLoader,
UnstructuredWordDocumentLoader, )
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Milvus
from tqdm import tqdm
load_dotenv(".env")
MILVUS_HOST = os.environ.get('MILVUS_HOST')
MILVUS_PORT = os.environ.get('MILVUS_PORT')
source_directory = os.environ.get('SOURCE_DIRECTORY', 'source_documents')
KNOWLEDGE_FOLDER = os.environ.get('KNOWLEDGE_FOLDER')
KNOWLEDGE_FOLDER_BK = os.environ.get('KNOWLEDGE_FOLDER_BK')
chunk_size = 500
chunk_overlap = 50
# Custom document loaders
class MyElmLoader(UnstructuredEmailLoader):
"""在默认值不起作用时回退到文本纯"""
def load(self) -> List[Document]:
"""EMl没有 html 使用text/plain"""
try:
try:
doc = UnstructuredEmailLoader.load(self)
except ValueError as e:
if 'text/html content not found in email' in str(e):
# Try plain text
self.unstructured_kwargs["content_source"] = "text/plain"
doc = UnstructuredEmailLoader.load(self)
else:
raise
except Exception as e:
# Add file_path to exception message
raise type(e)(f"{self.file_path}: {e}") from e
return doc
# 映射文件加载
LOADER_MAPPING = {
".csv": (CSVLoader, {}),
# ".docx": (Docx2txtLoader, {}),
".doc": (UnstructuredWordDocumentLoader, {}),
".docx": (UnstructuredWordDocumentLoader, {}),
".enex": (EverNoteLoader, {}),
".eml": (MyElmLoader, {}),
".epub": (UnstructuredEPubLoader, {}),
".html": (UnstructuredHTMLLoader, {}),
".md": (UnstructuredMarkdownLoader, {}),
".odt": (UnstructuredODTLoader, {}),
".pdf": (PDFMinerLoader, {}),
".ppt": (UnstructuredPowerPointLoader, {}),
".pptx": (UnstructuredPowerPointLoader, {}),
".txt": (TextLoader, {"encoding": "utf8"}),
}
def load_single_document(file_path: str) -> List[Document]:
ext = "." + file_path.rsplit(".", 1)[-1]
if ext in LOADER_MAPPING:
loader_class, loader_args = LOADER_MAPPING[ext]
loader = loader_class(file_path, **loader_args)
return loader.load()
raise ValueError(f"文件不存在 '{ext}'")
def load_documents_knowledge(source_dir: str, secondary_directories: str) -> List[Document]:
"""
Loads all documents from the source documents directory, ignoring specified files
"""
all_files = []
for ext in LOADER_MAPPING:
all_files.extend(
glob.glob(os.path.join(source_dir, secondary_directories, f"**/*{ext}"), recursive=True)
)
filtered_files = [file_path for file_path in all_files if file_path]
with Pool(processes=os.cpu_count()) as pool:
results = []
with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
for i, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
results.extend(docs)
pbar.update()
return results
def process_documents_knowledge(secondary_directories: str) -> List[Document]:
"""
加载文档并拆分为块
"""
print(f"加载文件目录: {KNOWLEDGE_FOLDER}")
documents = load_documents_knowledge(KNOWLEDGE_FOLDER, secondary_directories)
if not documents:
print("没有文件需要加载")
exit(0)
print(f"加载 {len(documents)} 文件从 {KNOWLEDGE_FOLDER}")
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
texts = text_splitter.split_documents(documents)
print(f"切割 {len(texts)} 文本块 (最大. {chunk_size} tokens 令牌)")
return texts
def main_knowledge(collection_name: str):
# Create embeddings
embeddings = OpenAIEmbeddings()
texts = process_documents_knowledge(collection_name)
Milvus.from_documents(
texts,
collection_name=collection_name,
embedding=embeddings,
connection_args={"host": MILVUS_HOST, "port": MILVUS_PORT}
)
在本文中,我们详细介绍了基于GPT搭建私有知识库聊天机器人的数据训练过程,包括数据训练的依赖、流程和代码展示。数据训练是搭建聊天机器人的重要步骤,希望本文能对读者有所帮助。在下一篇文章中,我们将介绍如何使用训练好的模型进行聊天机器人的测试和使用.
最后此篇关于基于GPT搭建私有知识库聊天机器人(三)向量数据训练的文章就讲到这里了,如果你想了解更多关于基于GPT搭建私有知识库聊天机器人(三)向量数据训练的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
如果需要在类外访问静态(例如单例),可以选择公共(public)静态而不是私有(private)静态,而当不需要公开函数时首选私有(private)静态(否则未命名的命名空间就可以了)——在这种情况下
在互联网上进行了一些搜索,但找不到简单的答案。我的问题集是在 Android 框架中使用 Java,但我相信这也是标准的 Java 行为。我理解 final 和 private 的定义,它们都用于变量
我有这个代码: public final class Board { private final int[][] blocks; private final int N; pr
对我来说,过去作为 Objective-C 开发人员很简单。一个类需要公开的每个字段都是一个属性,每个私有(private)字段都是一个没有 getter 或 setter 的实例变量。但我经常看到人
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我有一个在 Docker 容器中运行的应用程序。它需要来自公司私有(private) NPM 注册表(Sinopia)的一些私有(private)模块,并且访问这些需要用户身份验证。 Dockerfi
我试图理解 C# 使用 getters 和 setters 自动声明变量与 java 声明之间的区别。 在java中我通常这样做: private int test; public int getTe
我在 Azure 中创建了 VNET。我放入了一个子集 Azure Private Link,它在 VNET 之外和另一台虚拟机中调用 Azure Function。 当我尝试通过专用 IP 调用专用
我在 Azure 中创建了 VNET。我放入了一个子集 Azure Private Link,它在 VNET 之外和另一台虚拟机中调用 Azure Function。 当我尝试通过专用 IP 调用专用
我目前正在使用 Objective-C(适用于 iPhone)构建游戏。 为此,出于性能/复杂性原因,我略微打破了 MVC,并为 View (渲染器)提供了对模型的直接引用。这是因为它应该以 60fp
我已经在 ubuntu 上成功配置了 2 个虚拟主机站点(基于名称的虚拟主机)。我的 apache 版本是 2.2.22。 这两个站点都在本地主机上工作。 /etc/hosts 条目 127.0.0.
考虑下面的类 public class A { private final Map cache; public HeavyObject getThing(); } 假设不能泄漏对缓存
我有一个类,它有一个方法,我希望它只能被它的子对象访问,而不能被这个包中的其他类访问。 Modifier | Class | Package | Subclass | World ———————
本文实例讲述了JavaScript中的公有、私有、特权和静态成员用法。分享给大家供大家参考。具体分析如下: 下面的内容是在《JavaScript.DOM高级程序设计》里面摘抄出来的,比较容易理解,
我有一个用例,我已将其简化为以下程序: public class A { private int x = 100; class B { private int y = ne
问题: 类声明如下: class Select { public: template static Iterator function(Iterator , Iterator , bo
我是一名初级 PHP 程序员。我还有很多东西要学。这就是我问这个问题的原因。在一个类中,您有一个公共(public)函数,您可以从该类外部调用它。有时你有一个私有(private)函数,你可以在私有(
问题是: 何时使用私有(private)函数,何时使用嵌套函数? (我在问 F# 但也许答案可能与其他功能语言相关) 一个小例子 namespace SomeName module BinaryRea
我发现工作表中仍然可以使用私有(private)函数。它们是隐藏的,但如果用户输入他们的名字,他们就会被调用。为什么?它应该以这种方式工作吗?有没有办法完全阻止用户定义的函数在 VBA 项目之外使用?
所以我最近开始尝试使用 Kotlin,我偶然发现了这个: If a top-level declaration is marked private, it is private to the pack
我是一名优秀的程序员,十分优秀!