Pinata, OpenAI 및 Streamlit을 사용하여 PDF와 채팅
이 튜토리얼에서는 사용자가 PDF를 업로드하고, OpenAI API를 사용하여 해당 콘텐츠를 검색하고, 를 사용하여 채팅과 유사한 인터페이스에 응답을 표시할 수 있는 간단한 채팅 인터페이스를 구축합니다. 간소화. 또한 @pinata를 활용하여 PDF 파일을 업로드하고 저장할 것입니다.
진행하기 전에 우리가 무엇을 구축하고 있는지 잠시 살펴보겠습니다.
전제조건 :
- 파이썬에 대한 기본지식
- Pinata API 키(PDF 업로드용)
- OpenAI API 키(응답 생성용)
- Streamlit 설치(UI 구축용)
1단계: 프로젝트 설정
새 Python 프로젝트 디렉토리를 생성하여 시작하세요.
mkdir chat-with-pdf cd chat-with-pdf python3 -m venv venv source venv/bin/activate pip install streamlit openai requests PyPDF2
이제 프로젝트 루트에 .env 파일을 생성하고 다음 환경 변수를 추가하세요.
PINATA_API_KEY=<Your Pinata API Key> PINATA_SECRET_API_KEY=<Your Pinata Secret Key> OPENAI_API_KEY=<Your OpenAI API Key>
OPENAI_API_KEY는 유료이므로 직접 관리해야 하지만, 피니타에서 API 키를 생성하는 과정을 살펴보겠습니다.
계속 진행하기 전에 우리가 Pinata를 사용하는 이유가 무엇인지 알려주세요.
피나타는 분산, 분산 파일 저장 시스템인 IPFS(InterPlanetary File System)에 파일을 저장하고 관리할 수 있는 플랫폼을 제공하는 서비스입니다.
- 분산형 저장소: Pinata는 분산형 네트워크인 IPFS에 파일을 저장할 수 있도록 도와줍니다.
- 사용하기 쉬움: 파일 관리를 위한 사용자 친화적인 도구와 API를 제공합니다.
- 파일 가용성: Pinata는 IPFS에 파일을 "고정"하여 파일에 대한 액세스를 유지합니다.
- NFT 지원: NFT 및 Web3 앱용 메타데이터를 저장하는 데 적합합니다.
- 비용 효율성: Pinata는 기존 클라우드 스토리지보다 저렴한 대안이 될 수 있습니다.
로그인하여 필수 토큰을 생성해 보겠습니다.
다음 단계는 등록된 이메일을 확인하는 것입니다.
API 키 생성을 위해 로그인 인증 후 :
그런 다음 API 키 섹션으로 이동하여 새 API 키를 생성하세요.
마지막으로 키가 성공적으로 생성되었습니다. 해당 키를 복사하여 코드 편집기에 저장하세요.
OPENAI_API_KEY=<Your OpenAI API Key> PINATA_API_KEY=dfc05775d0c8a1743247 PINATA_SECRET_API_KEY=a54a70cd227a85e68615a5682500d73e9a12cd211dfbf5e25179830dc8278efc
2단계: Pinata를 사용하여 PDF 업로드
Pinata의 API를 사용하여 PDF를 업로드하고 각 파일에 대한 해시(CID)를 가져옵니다. PDF 업로드를 처리하려면 pinata_helper.py라는 파일을 생성하세요.
import os # Import the os module to interact with the operating system import requests # Import the requests library to make HTTP requests from dotenv import load_dotenv # Import load_dotenv to load environment variables from a .env file # Load environment variables from the .env file load_dotenv() # Define the Pinata API URL for pinning files to IPFS PINATA_API_URL = "https://api.pinata.cloud/pinning/pinFileToIPFS" # Retrieve Pinata API keys from environment variables PINATA_API_KEY = os.getenv("PINATA_API_KEY") PINATA_SECRET_API_KEY = os.getenv("PINATA_SECRET_API_KEY") def upload_pdf_to_pinata(file_path): """ Uploads a PDF file to Pinata's IPFS service. Args: file_path (str): The path to the PDF file to be uploaded. Returns: str: The IPFS hash of the uploaded file if successful, None otherwise. """ # Prepare headers for the API request with the Pinata API keys headers = { "pinata_api_key": PINATA_API_KEY, "pinata_secret_api_key": PINATA_SECRET_API_KEY } # Open the file in binary read mode with open(file_path, 'rb') as file: # Send a POST request to Pinata API to upload the file response = requests.post(PINATA_API_URL, files={'file': file}, headers=headers) # Check if the request was successful (status code 200) if response.status_code == 200: print("File uploaded successfully") # Print success message # Return the IPFS hash from the response JSON return response.json()['IpfsHash'] else: # Print an error message if the upload failed print(f"Error: {response.text}") return None # Return None to indicate failure
3단계: OpenAI 설정
다음으로 OpenAI API를 사용하여 PDF에서 추출된 텍스트와 상호 작용하는 함수를 만듭니다. 채팅 응답을 위해 OpenAI의 gpt-4o 또는 gpt-4o-mini 모델을 활용하겠습니다.
새 파일 openai_helper.py 만들기:
import os from openai import OpenAI from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Initialize OpenAI client with the API key OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") client = OpenAI(api_key=OPENAI_API_KEY) def get_openai_response(text, pdf_text): try: # Create the chat completion request print("User Input:", text) print("PDF Content:", pdf_text) # Optional: for debugging # Combine the user's input and PDF content for context messages = [ {"role": "system", "content": "You are a helpful assistant for answering questions about the PDF."}, {"role": "user", "content": pdf_text}, # Providing the PDF content {"role": "user", "content": text} # Providing the user question or request ] response = client.chat.completions.create( model="gpt-4", # Use "gpt-4" or "gpt-4o mini" based on your access messages=messages, max_tokens=100, # Adjust as necessary temperature=0.7 # Adjust to control response creativity ) # Extract the content of the response return response.choices[0].message.content # Corrected access method except Exception as e: return f"Error: {str(e)}"
4단계: 간소화된 인터페이스 구축
이제 도우미 기능이 준비되었으므로 PDF를 업로드하고 OpenAI에서 응답을 가져오고 채팅을 표시하는 Streamlit 앱을 구축할 차례입니다.
app.py라는 파일을 만듭니다.
import streamlit as st import os import time from pinata_helper import upload_pdf_to_pinata from openai_helper import get_openai_response from PyPDF2 import PdfReader from dotenv import load_dotenv # Load environment variables load_dotenv() st.set_page_config(page_title="Chat with PDFs", layout="centered") st.title("Chat with PDFs using OpenAI and Pinata") uploaded_file = st.file_uploader("Upload your PDF", type="pdf") # Initialize session state for chat history and loading state if "chat_history" not in st.session_state: st.session_state.chat_history = [] if "loading" not in st.session_state: st.session_state.loading = False if uploaded_file is not None: # Save the uploaded file temporarily file_path = os.path.join("temp", uploaded_file.name) with open(file_path, "wb") as f: f.write(uploaded_file.getbuffer()) # Upload PDF to Pinata st.write("Uploading PDF to Pinata...") pdf_cid = upload_pdf_to_pinata(file_path) if pdf_cid: st.write(f"File uploaded to IPFS with CID: {pdf_cid}") # Extract PDF content reader = PdfReader(file_path) pdf_text = "" for page in reader.pages: pdf_text += page.extract_text() if pdf_text: st.text_area("PDF Content", pdf_text, height=200) # Allow user to ask questions about the PDF user_input = st.text_input("Ask something about the PDF:", disabled=st.session_state.loading) if st.button("Send", disabled=st.session_state.loading): if user_input: # Set loading state to True st.session_state.loading = True # Display loading indicator with st.spinner("AI is thinking..."): # Simulate loading with sleep (remove in production) time.sleep(1) # Simulate network delay # Get AI response response = get_openai_response(user_input, pdf_text) # Update chat history st.session_state.chat_history.append({"user": user_input, "ai": response}) # Clear the input box after sending st.session_state.input_text = "" # Reset loading state st.session_state.loading = False # Display chat history if st.session_state.chat_history: for chat in st.session_state.chat_history: st.write(f"**You:** {chat['user']}") st.write(f"**AI:** {chat['ai']}") # Auto-scroll to the bottom of the chat st.write("<style>div.stChat {overflow-y: auto;}</style>", unsafe_allow_html=True) # Add three dots as a loading indicator if still waiting for response if st.session_state.loading: st.write("**AI is typing** ...") else: st.error("Could not extract text from the PDF.") else: st.error("Failed to upload PDF to Pinata.")
5단계: 앱 실행
앱을 로컬에서 실행하려면 다음 명령을 사용하세요.
streamlit run app.py
우리 파일이 Pinata 플랫폼에 성공적으로 업로드되었습니다:
6단계: 코드 설명
피냐타 업로드
- 사용자가 PDF 파일을 업로드합니다. PDF 파일은 upload_pdf_to_pinata 함수를 사용하여 로컬에 임시 저장되었다가 Pinata에 업로드됩니다. Pinata는 IPFS에 저장된 파일을 나타내는 해시(CID)를 반환합니다.
PDF 추출
- ファイルがアップロードされると、PyPDF2 を使用して PDF のコンテンツが抽出されます。このテキストはテキスト領域に表示されます。
OpenAI インタラクション
- ユーザーはテキスト入力を使用して PDF コンテンツについて質問できます。 get_openai_response 関数は、ユーザーのクエリを PDF コンテンツとともに OpenAI に送信し、OpenAI は関連する応答を返します。
最終コードはこの github リポジトリで入手できます:
https://github.com/Jagroop2001/chat-with-pdf
このブログは以上です。さらなるアップデートに注目して、素晴らしいアプリを構築し続けてください! ?✨
コーディングを楽しんでください! ?
위 내용은 Pinata, OpenAI 및 Streamlit을 사용하여 PDF와 채팅의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

Linux 터미널에서 Python 사용 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.
