使用chatgpt api快速分析pdf

需求背景

搞材料的兄弟经常要分析pdf,然后看到国外有产品是专门调用chatpdf来分析pdf的,所以就来问我能不能帮他也做一个出来。正好我有chatgpt的api,所以就研究了一下这玩意怎么弄。

需求分析

由于chatgpt是按字符算钱的,所以如果把整个pdf文本全部塞进去,虽然效果是好了,但是钱花的巨快。测试的时候不小心传了个86页的pdf进去,好家伙,直接余额变负值了,一下子花了6刀多。。。。所以我们只能先对pdf做预处理,主要使用了langchain包加载和生成向量库

引入依赖

python 复制代码
from langchain.document_loaders import PyPDFLoader
from langchain.indexes.vectorstore import VectorstoreIndexCreator
from langchain.vectorstores.chroma import Chroma
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.indexes.vectorstore import VectorStoreIndexWrapper

生成向量

python 复制代码
# https://chatpdf4cn.com/
def load_pdf_and_save_to_index(file_path, index_name):
    loader = PyPDFLoader(file_path)
    index = VectorstoreIndexCreator(vectorstore_kwargs={"persist_directory":get_index_path(index_name)}).from_loaders({loader})
    print('save')

    index.vectorstore.persist()

加载向量库

python 复制代码
def load_index(index_name):
    index_path=get_index_path(index_name)
    embedding = OpenAIEmbeddings()
    vectordb = Chroma(
    persist_directory=index_path,
    embedding_function=embedding
 )
    return VectorStoreIndexWrapper(vectorstore=vectordb)

最后调用chatgpt访问

python 复制代码
load_pdf_and_save_to_index(file_path, index_name)
index = load_index(index_name)

ans = index.query("文章中提到的两种磁化模式有什么区别?",chain_type_kwargs={}) #RetrievalQAWithSourcesChain

print(ans)

附上完整项目试用地址
chatpdf4cn

调用chatgpt接口还是蛮贵的,所以限制了试用次数,如果有需要的可以联系我开放限制,希望能反馈一些使用意见。

相关推荐
Mr.LJie8 小时前
记录使用iText7合并PDF文件、PDF发票、PDF火车票
java·pdf
Johnny.Cheung9 小时前
开源免费的AI浏览器ChatGPT Atlas的可选平替Toutcas-“用后即焚”
人工智能·chatgpt·ai浏览器·toutcas·ai浏览助理
wwwlyj1233219 小时前
劳特巴赫 设置pdf
pdf
kingmax5421200810 小时前
0基础快速入门AI大模型应用与实战
人工智能·chatgpt
居7然18 小时前
ChatGPT是怎么学会接龙的?
深度学习·语言模型·chatgpt·性能优化·transformer
Arenaschi1 天前
关于垃圾的CSDN
java·网络·chrome·笔记·其他·oracle·pdf
开开心心就好1 天前
内存清理工具开源免费,自动优化清理项
linux·运维·服务器·python·django·pdf·1024程序员节
开开心心_Every1 天前
图片批量压缩工具:支持有损无损两种模式
python·游戏·微信·django·pdf·excel·语音识别
感谢地心引力1 天前
【AI】2026 OpenAI 重磅:ChatGPT Go 套餐发布(8美元/月),广告测试同步启动
人工智能·ai·chatgpt·广告
jackywine61 天前
AI三国演义:ChatGPT、Claude、Gemini的发展史与较量
人工智能·chatgpt