Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
import configparser
|
4 |
+
import streamlit as st
|
5 |
+
import streamlit
|
6 |
+
import chromadb
|
7 |
+
import langchain
|
8 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
9 |
+
from langchain.vectorstores import Chroma
|
10 |
+
from langchain.chains import ConversationalRetrievalChain
|
11 |
+
from langchain.chat_models import ChatOpenAI
|
12 |
+
from langchain.document_loaders import PyPDFLoader
|
13 |
+
import tempfile
|
14 |
+
import shutil
|
15 |
+
import os
|
16 |
+
import openai
|
17 |
+
|
18 |
+
# You need your own API key
|
19 |
+
api_key = st.secrets["OPENAI_API_KEY"] # Get API key from Streamlit secrets
|
20 |
+
|
21 |
+
if not api_key:
|
22 |
+
st.error("I can not find API key")
|
23 |
+
else:
|
24 |
+
openai.api_key = api_key
|
25 |
+
|
26 |
+
st.title('PDF Documents Q&A App')
|
27 |
+
|
28 |
+
uploaded_file = st.file_uploader("Please upload your PDF file", type=["pdf"])
|
29 |
+
if uploaded_file is not None:
|
30 |
+
# Save as tempfile
|
31 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmpfile:
|
32 |
+
shutil.copyfileobj(uploaded_file, tmpfile)
|
33 |
+
file_path = tmpfile.name
|
34 |
+
|
35 |
+
# PyPDFLoader
|
36 |
+
loader = PyPDFLoader(file_path)
|
37 |
+
pages = loader.load_and_split()
|
38 |
+
|
39 |
+
# Model and vectorstore
|
40 |
+
embeddings = OpenAIEmbeddings()
|
41 |
+
vectorstore = Chroma.from_documents(pages, embedding=embeddings, persist_directory=".")
|
42 |
+
vectorstore.persist()
|
43 |
+
llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")
|
44 |
+
|
45 |
+
# Q&A chain
|
46 |
+
pdf_qa = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)
|
47 |
+
|
48 |
+
# Get question from user
|
49 |
+
question = st.text_input("Please input your question:")
|
50 |
+
if st.button('Get Answer'):
|
51 |
+
result = pdf_qa({"question": question, "chat_history": []})
|
52 |
+
answer = result["answer"]
|
53 |
+
st.write("Answer:", answer)
|
54 |
+
|
55 |
+
# Delete tempfile
|
56 |
+
os.remove(file_path) # Clean up the temporary file
|