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