Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pdfplumber
|
3 |
+
import streamlit as st
|
4 |
+
from groq import Groq
|
5 |
+
|
6 |
+
# Set the Groq API key (you need to set this beforehand)
|
7 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
8 |
+
|
9 |
+
# Function to extract text from the PDF
|
10 |
+
def extract_text_from_pdf(pdf_path):
|
11 |
+
with pdfplumber.open(pdf_path) as pdf:
|
12 |
+
full_text = ""
|
13 |
+
for page in pdf.pages:
|
14 |
+
full_text += page.extract_text()
|
15 |
+
return full_text
|
16 |
+
|
17 |
+
# Function to search for relevant information based on the query
|
18 |
+
def search_relevant_info(query, text):
|
19 |
+
lower_text = text.lower()
|
20 |
+
lower_query = query.lower()
|
21 |
+
|
22 |
+
if lower_query in lower_text:
|
23 |
+
start = lower_text.find(lower_query)
|
24 |
+
end = start + 1000 # Extracting a portion of the text (adjustable)
|
25 |
+
return text[start:end]
|
26 |
+
else:
|
27 |
+
return "Sorry, I couldn't find any relevant information."
|
28 |
+
|
29 |
+
# Function to generate response from Groq API
|
30 |
+
def generate_response_with_retrieved_info(query, retrieved_text):
|
31 |
+
chat_completion = client.chat.completions.create(
|
32 |
+
messages=[
|
33 |
+
{
|
34 |
+
"role": "user",
|
35 |
+
"content": f"Query: {query}\nContext: {retrieved_text}",
|
36 |
+
}
|
37 |
+
],
|
38 |
+
model="llama3-8b-8192",
|
39 |
+
)
|
40 |
+
|
41 |
+
return chat_completion.choices[0].message.content
|
42 |
+
|
43 |
+
# Main chatbot function
|
44 |
+
def chatbot(query, pdf_path):
|
45 |
+
# Step 1: Extract text from the PDF
|
46 |
+
extracted_text = extract_text_from_pdf(pdf_path)
|
47 |
+
|
48 |
+
# Step 2: Search for relevant information based on the query
|
49 |
+
retrieved_text = search_relevant_info(query, extracted_text)
|
50 |
+
|
51 |
+
# Step 3: Generate a response using the Groq API
|
52 |
+
response = generate_response_with_retrieved_info(query, retrieved_text)
|
53 |
+
|
54 |
+
return response
|
55 |
+
|
56 |
+
# Streamlit UI
|
57 |
+
def main():
|
58 |
+
st.title("University Information Chatbot")
|
59 |
+
|
60 |
+
# Upload PDF
|
61 |
+
pdf_file = st.file_uploader("Upload the University Information PDF", type=["pdf"])
|
62 |
+
|
63 |
+
if pdf_file:
|
64 |
+
# Text input for user query
|
65 |
+
query = st.text_input("Ask a question about the university:")
|
66 |
+
|
67 |
+
if query:
|
68 |
+
# Process the query
|
69 |
+
with st.spinner("Searching for relevant information..."):
|
70 |
+
response = chatbot(query, pdf_file)
|
71 |
+
st.write("Response:", response)
|
72 |
+
|
73 |
+
if __name__ == "__main__":
|
74 |
+
main()
|