Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from groq import Groq
|
3 |
+
import pdfplumber
|
4 |
+
import os
|
5 |
+
import gc
|
6 |
+
|
7 |
+
# Set your Groq API key (make sure to set this in your environment variables)
|
8 |
+
os.environ["GROQ_API_KEY"] = "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" # Set your API key here
|
9 |
+
|
10 |
+
# Initialize the Groq client
|
11 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
12 |
+
|
13 |
+
def generate_response_groq(context, query):
|
14 |
+
"""Generate response using Groq API."""
|
15 |
+
prompt = f"Context: {context}\nQuestion: {query}\nAnswer:"
|
16 |
+
chat_completion = client.chat.completions.create(
|
17 |
+
messages=[
|
18 |
+
{
|
19 |
+
"role": "user",
|
20 |
+
"content": prompt,
|
21 |
+
}
|
22 |
+
],
|
23 |
+
model="llama3-8b-8192",
|
24 |
+
)
|
25 |
+
response = chat_completion.choices[0].message.content
|
26 |
+
return response
|
27 |
+
|
28 |
+
def extract_text_from_pdf(pdf_file):
|
29 |
+
"""Extract text from PDF file using pdfplumber."""
|
30 |
+
text = ""
|
31 |
+
with pdfplumber.open(pdf_file) as pdf:
|
32 |
+
for page in pdf.pages:
|
33 |
+
text += page.extract_text() or ""
|
34 |
+
return text
|
35 |
+
|
36 |
+
# Streamlit UI
|
37 |
+
st.title("PDF Query Application")
|
38 |
+
|
39 |
+
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
|
40 |
+
|
41 |
+
if uploaded_file:
|
42 |
+
st.write("PDF uploaded successfully!")
|
43 |
+
document_text = extract_text_from_pdf(uploaded_file)
|
44 |
+
st.text_area("Extracted Text", document_text, height=300)
|
45 |
+
|
46 |
+
query = st.text_input("Enter your query")
|
47 |
+
|
48 |
+
if st.button("Get Answer"):
|
49 |
+
if query:
|
50 |
+
with st.spinner("Generating response..."):
|
51 |
+
response = generate_response_groq(document_text, query)
|
52 |
+
st.write("Response:")
|
53 |
+
st.write(response)
|
54 |
+
|
55 |
+
# Clear memory after generating response
|
56 |
+
gc.collect()
|
57 |
+
|
58 |
+
else:
|
59 |
+
st.error("Please enter a query.")
|