PDFとチャットAIを作ってみる

下記のPDFとチャットAIのデモアプリを作ってみて、まとめました。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/225269/9f6d57cf-df52-9c52-8bcf-2784d2ccb8be.png)

https://huggingface.co/spaces/jingwora/AI-DEMO-PDF-QA

目次：

はじめに
コード
まとめ

## はじめに
この記事では、OpenAIのチャットAIを使用して、Gradioを用いたデモアプリの作成方法を紹介します。PDFの入力方法は以下の3つです。
1. PDFファイルのアップロード
2. PDFのURLから
3. サンプルPDFファイル

## コード

ライブラリのインポート
```python
import gradio as gr
import os
import time
import requests

from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.llms import OpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain

```

データの出力の関数

```python
def loading_pdf():
    return "Loading..."

def pdf_changes(pdf_doc, open_ai_key):
    if openai_key is not None:
        os.environ['OPENAI_API_KEY'] = open_ai_key
        loader = PyPDFLoader(pdf_doc.name)
        documents = loader.load()
        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        texts = text_splitter.split_documents(documents)
        embeddings = OpenAIEmbeddings()
        db = Chroma.from_documents(texts, embeddings)
        retriever = db.as_retriever()
        global qa
        qa = ConversationalRetrievalChain.from_llm(
            llm=OpenAI(temperature=0.5),
            retriever=retriever,
            return_source_documents=False)
        return "✅ Ready: Upload PDF"
    else:
        return "Please input correct OpenAI API key"

def pdf_url(url, open_ai_key):
    destination = 'url.pdf'  # download
    response = requests.get(url)

    if response.status_code == 200:
        with open(destination, 'wb') as file:
            file.write(response.content)
        print(f"File downloaded to {destination}")
    else:
        print(f"Failed to download the file. Status code: {response.status_code}")

    if openai_key is not None:
        os.environ['OPENAI_API_KEY'] = open_ai_key
        loader = PyPDFLoader("url.pdf")
        documents = loader.load()
        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        texts = text_splitter.split_documents(documents)
        embeddings = OpenAIEmbeddings()
        db = Chroma.from_documents(texts, embeddings)
        retriever = db.as_retriever()
        global qa
        qa = ConversationalRetrievalChain.from_llm(
            llm=OpenAI(temperature=0.5),
            retriever=retriever,
            return_source_documents=False)
        return "✅ Ready: Upload from URL"
    else:
        return "Please input correct OpenAI API key"

def pdf_example(open_ai_key):
    if openai_key is not None:
        os.environ['OPENAI_API_KEY'] = open_ai_key
        loader = PyPDFLoader("sample.pdf")
        documents = loader.load()
        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        texts = text_splitter.split_documents(documents)
        embeddings = OpenAIEmbeddings()
        db = Chroma.from_documents(texts, embeddings)
        retriever = db.as_retriever()
        global qa
        qa = ConversationalRetrievalChain.from_llm(
            llm=OpenAI(temperature=0.5),
            retriever=retriever,
            return_source_documents=False)
        return "✅ Ready: Load example PDF"
    else:
        return "Please input correct OpenAI API key"
```

チャット履歴の設定

```python
def add_text(history, text):
    history = history + [(text, None)]
    return history, ""

def bot(history):
    response = infer(history[-1][0], history)
    history[-1][1] = ""

    for character in response:
        history[-1][1] += character
        time.sleep(0.05)
        yield history
```
チャットの返事

```python
def infer(question, history):

    res = []
    for human, ai in history[:-1]:
        pair = (human, ai)
        res.append(pair)

    chat_history = res
    #print(chat_history)
    query = question
    result = qa({"question": query, "chat_history": chat_history})
    #print(result)
    return result["answer"]
```
利用方法の内容を追加します。

```python
css="""
#col-container {max-width: 700px; margin-left: auto; margin-right: auto;}
"""

title = """
<div style="text-align: center;max-width: 700px;">
    <h1>language-document-extractor-QA</h1>
    <p style="text-align: left;">Instruction: <br />
    1. Input your Open API key <br />
    2. There are 3 options: <br />
    2.1 Upload PDF file and click [Upload PDF]  <br />
    2.2 Input PDF url and click [Upload from URL]  <br />
    2.3 Click [Load example PDF] to use example  <br />
    3. When status is ready, you can ask question about the pdf. <br />
    </p>
</div>
"""
version = """
<div style="text-align: center;max-width: 700px;">
    <p style="text-align: left;">
    version: 1.01
    </p>
</div>
"""
```
gardioの設定

```python
with gr.Blocks(css=css) as demo:
    with gr.Column(elem_id="col-container"):
        gr.HTML(title)

        with gr.Column():
            openai_key = gr.Textbox(label="You OpenAI API key", type="password")
            pdf_doc = gr.File(label="Load a pdf", file_types=['.pdf'], type="file")
            url = gr.Textbox(label='Enter PDF URL here', placeholder="https://huggingface.co/spaces/jingwora/language-PDF-extractor-QA/resolve/main/sample.pdf")
            with gr.Row():
                load_pdf = gr.Button("Upload PDF")
                load_url = gr.Button("Upload from URL", )
                load_example = gr.Button("Load example PDF")

        status = gr.Textbox(label="Status", placeholder="", interactive=False)
        chatbot = gr.Chatbot([], elem_id="chatbot").style(height=350)
        question = gr.Textbox(label="Question", placeholder="Type your question and hit Enter ")
        submit_btn = gr.Button("Send Message")
        gr.HTML(version)

    load_pdf.click(loading_pdf, None, status, queue=False)
    load_pdf.click(pdf_changes, inputs=[pdf_doc, openai_key], outputs=[status], queue=False)

    load_example.click(loading_pdf, None, status, queue=False)
    load_example.click(pdf_example, inputs=[openai_key], outputs=[status], queue=False)

    load_url.click(loading_pdf, None, status, queue=False)
    load_url.click(pdf_url, inputs=[url, openai_key], outputs=[status], queue=False)

    question.submit(add_text, [chatbot, question], [chatbot, question]).then(
        bot, chatbot, chatbot
    )
    submit_btn.click(add_text, [chatbot, question], [chatbot, question]).then(
        bot, chatbot, chatbot)

demo.queue(concurrency_count=5, max_size=20).launch(debug=True)
```

## まとめ

本記事では、OpenAIのチャットAIとGradioを使用して、PDFと対話型要素を組み合わせたデモアプリを作成する方法を解説しました。PDFの異なる入力方法を通じて、Gradioの機能と活用法について理解することができるでしょう。是非、この手順を参考にして自身のプロジェクトに応用してみてください。