>  기사  >  백엔드 개발  >  Pinata, OpenAI 및 Streamlit을 사용하여 PDF와 채팅

Pinata, OpenAI 및 Streamlit을 사용하여 PDF와 채팅

DDD
DDD원래의
2024-10-11 10:36:02872검색

이 튜토리얼에서는 사용자가 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를 사용하는 이유가 무엇인지 알려주세요.

Chat with your PDF using Pinata,OpenAI and Streamlit

피나타는 분산, 분산 파일 저장 시스템인 IPFS(InterPlanetary File System)에 파일을 저장하고 관리할 수 있는 플랫폼을 제공하는 서비스입니다.

  • 분산형 저장소: Pinata는 분산형 네트워크인 IPFS에 파일을 저장할 수 있도록 도와줍니다.
  • 사용하기 쉬움: 파일 관리를 위한 사용자 친화적인 도구와 API를 제공합니다.
  • 파일 가용성: Pinata는 IPFS에 파일을 "고정"하여 파일에 대한 액세스를 유지합니다.
  • NFT 지원: NFT 및 Web3 앱용 메타데이터를 저장하는 데 적합합니다.
  • 비용 효율성: Pinata는 기존 클라우드 스토리지보다 저렴한 대안이 될 수 있습니다.

로그인하여 필수 토큰을 생성해 보겠습니다.

Chat with your PDF using Pinata,OpenAI and Streamlit

다음 단계는 등록된 이메일을 확인하는 것입니다.

Chat with your PDF using Pinata,OpenAI and Streamlit

API 키 생성을 위해 로그인 인증 후 :

Chat with your PDF using Pinata,OpenAI and Streamlit

그런 다음 API 키 섹션으로 이동하여 새 API 키를 생성하세요.

Chat with your PDF using Pinata,OpenAI and Streamlit

마지막으로 키가 성공적으로 생성되었습니다. 해당 키를 복사하여 코드 편집기에 저장하세요.

Chat with your PDF using Pinata,OpenAI and Streamlit

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 플랫폼에 성공적으로 업로드되었습니다:
Chat with your PDF using Pinata,OpenAI and Streamlit

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.