Spaces:
Sleeping
Sleeping
File size: 2,135 Bytes
77be39a a817aa4 ced2a64 77be39a a817aa4 77be39a ced2a64 77be39a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
import streamlit as st
import PyPDF2
import os
import keyfile
from openai import OpenAI
# Built a client for OpenAI
client = OpenAI()
# here we are calling our API for openAI
os.environ["OPENAI_API_KEY"] = keyfile.OPENAI_API_KEY
# We need to upload the file
def extract_text(pdfPath):
reader = PyPDF2.PdfReader(pdfPath)
text = ""
for x in range(len(reader.pages)):
page = reader.pages[x]
text += page.extract_text() + "\n"
return text
# Ask GPT about the query
def gptAnswer(prompt):
# I will try a request to GPT for answer the question
try:
resp = client.chat.completions.create(
model = "gpt-4o-mini",
messages = [
{"role" : "system", "content" : "You are helpful assistant."},
{"role": "user", "content" : prompt}
],
max_tokens = 1024
)
answer = resp.choices[0].message["content"].strip()
return answer
except Exception as e:
return f"An error occured: {e}"
def main():
st.title("PDF Q&A with GPT-4o-MINI")
st.write("""
Upload a PDF Document, and ask the question based on the content
""")
uploaded_file = st.file_uploader("Choose a PDF File", type = ["pdf"])
if uploaded_file is not None:
with st.spinner("Extracting the text from the PDF...."):
text = extract_text(uploaded_file)
st.success("Text Extraction is Completed!!")
if not text:
st.warning("No text found in the uploaded file!!")
return
question = st.text_input("Ask your questions related to PDF:")
if st.button("Get Answer"):
if question:
with st.spinner("GPT-4o-mini is generating answer.."):
prompt = f"Here is the content of a PDF document: \n\n{text}\n\nBased on the text, answer the above question:\n\n{question}"
answer = gptAnswer(prompt)
st.write("***Answer***")
st.write(answer)
else:
st.warning("Please enter a question!")
if __name__ == "__main__":
main() |