chatbotmeraj / app.py
meraj12's picture
Update app.py
3e74cee verified
Raw
History Blame Contribute Delete
2.33 kB
# Import Libraries
import streamlit as st
from PyPDF2 import PdfReader
import groq
# Set Up Groq API
def setup_groq_client(api_key):
return groq.Client(api_key=api_key)
# Extract Text from PDF
def extract_text_from_pdf(pdf_file):
reader = PdfReader(pdf_file)
text = ""
for page in reader.pages:
text += page.extract_text()
return text
# Streamlit App
def main():
st.title("PDF Chatbot with Groq API")
st.write("Upload a PDF file and ask questions about its content.")
# Upload PDF File
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
if uploaded_file is not None:
# Extract Text from PDF
pdf_text = extract_text_from_pdf(uploaded_file)
st.write("### Extracted Text from PDF")
st.write(pdf_text[:1000] + "...") # Display first 1000 characters for preview
# Enter Groq API Key
groq_api_key = st.text_input("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:", type="password")
if groq_api_key:
# Initialize Groq Client
client = setup_groq_client(groq_api_key)
# Ask Questions
question = st.text_input("Ask a question about the PDF content:")
if question:
# Send Question and PDF Text to Groq API
try:
response = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are a helpful assistant. Answer questions based on the provided PDF text."
},
{
"role": "user",
"content": f"PDF Text: {pdf_text}\n\nQuestion: {question}"
}
],
model="mixtral-8x7b-32768", # Use Groq's Mixtral model
max_tokens=512
)
answer = response.choices[0].message.content
st.write("### Answer:")
st.write(answer)
except Exception as e:
st.error(f"An error occurred: {e}")
# Run the Streamlit App
if __name__ == "__main__":
main()