Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import PyPDF2 | |
| import os | |
| import keyfile | |
| from openai import OpenAI | |
| # here we are calling our API for openAI | |
| os.environ["OPENAI_API_KEY"] = keyfile.OPENAI_API_KEY | |
| # Built a client for OpenAI | |
| client = OpenAI() | |
| # 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} | |
| ], | |
| response_format={"type": "text"}, | |
| ) | |
| # answer = resp.choices[0].message["content"].strip() | |
| return resp | |
| 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() |