pratham0011
commited on
Commit
•
e615de1
1
Parent(s):
64d3bf0
Upload 4 files
Browse files- app_.py +111 -0
- man-kddi.png +0 -0
- requirements.txt +5 -0
- robot.png +0 -0
app_.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
3 |
+
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
6 |
+
from llama_index.core import Settings
|
7 |
+
import os
|
8 |
+
import base64
|
9 |
+
|
10 |
+
# Load environment variables
|
11 |
+
load_dotenv()
|
12 |
+
|
13 |
+
icons = {"assistant": "robot.png", "user": "man-kddi.png"}
|
14 |
+
|
15 |
+
# Configure the Llama index settings
|
16 |
+
Settings.llm = HuggingFaceInferenceAPI(
|
17 |
+
model_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
18 |
+
tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
19 |
+
context_window=3900,
|
20 |
+
# token=os.getenv("HF_TOKEN"),
|
21 |
+
max_new_tokens=1000,
|
22 |
+
generate_kwargs={"temperature": 0.1},
|
23 |
+
)
|
24 |
+
Settings.embed_model = HuggingFaceEmbedding(
|
25 |
+
model_name="BAAI/bge-small-en-v1.5"
|
26 |
+
)
|
27 |
+
|
28 |
+
# Define the directory for persistent storage and data
|
29 |
+
PERSIST_DIR = "./db"
|
30 |
+
DATA_DIR = "data"
|
31 |
+
|
32 |
+
# Ensure data directory exists
|
33 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
34 |
+
os.makedirs(PERSIST_DIR, exist_ok=True)
|
35 |
+
|
36 |
+
def displayPDF(file):
|
37 |
+
with open(file, "rb") as f:
|
38 |
+
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
|
39 |
+
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
|
40 |
+
st.markdown(pdf_display, unsafe_allow_html=True)
|
41 |
+
|
42 |
+
def data_ingestion():
|
43 |
+
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
44 |
+
storage_context = StorageContext.from_defaults()
|
45 |
+
index = VectorStoreIndex.from_documents(documents)
|
46 |
+
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
47 |
+
|
48 |
+
def handle_query(query):
|
49 |
+
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
50 |
+
index = load_index_from_storage(storage_context)
|
51 |
+
chat_text_qa_msgs = [
|
52 |
+
(
|
53 |
+
"user",
|
54 |
+
"""You are Q&A assistant named CHATTO, created by Pachaiappan an AI Specialist. Your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.
|
55 |
+
Context:
|
56 |
+
{context_str}
|
57 |
+
Question:
|
58 |
+
{query_str}
|
59 |
+
"""
|
60 |
+
)
|
61 |
+
]
|
62 |
+
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
63 |
+
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
64 |
+
answer = query_engine.query(query)
|
65 |
+
|
66 |
+
|
67 |
+
if hasattr(answer, 'response'):
|
68 |
+
return answer.response
|
69 |
+
elif isinstance(answer, dict) and 'response' in answer:
|
70 |
+
return answer['response']
|
71 |
+
else:
|
72 |
+
return "Sorry, I couldn't find an answer."
|
73 |
+
|
74 |
+
|
75 |
+
# Streamlit app initialization
|
76 |
+
st.title("Chat with your PDF 📄")
|
77 |
+
st.markdown("chat here👇")
|
78 |
+
|
79 |
+
if 'messages' not in st.session_state:
|
80 |
+
st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF and ask me anything about its content.'}]
|
81 |
+
|
82 |
+
for message in st.session_state.messages:
|
83 |
+
with st.chat_message(message['role'], avatar=icons[message['role']]):
|
84 |
+
st.write(message['content'])
|
85 |
+
|
86 |
+
with st.sidebar:
|
87 |
+
st.title("Menu:")
|
88 |
+
uploaded_file = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button")
|
89 |
+
if st.button("Submit & Process"):
|
90 |
+
with st.spinner("Processing..."):
|
91 |
+
filepath = "data/saved_pdf.pdf"
|
92 |
+
with open(filepath, "wb") as f:
|
93 |
+
f.write(uploaded_file.getbuffer())
|
94 |
+
# displayPDF(filepath) # Display the uploaded PDF
|
95 |
+
data_ingestion() # Process PDF every time new file is uploaded
|
96 |
+
st.success("Done")
|
97 |
+
|
98 |
+
user_prompt = st.chat_input("Ask me anything about the content of the PDF:")
|
99 |
+
|
100 |
+
if user_prompt and uploaded_file:
|
101 |
+
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
102 |
+
with st.chat_message("user", avatar="man-kddi.png"):
|
103 |
+
st.write(user_prompt)
|
104 |
+
|
105 |
+
# Trigger assistant's response retrieval and update UI
|
106 |
+
with st.spinner("Thinking..."):
|
107 |
+
response = handle_query(user_prompt)
|
108 |
+
with st.chat_message("user", avatar="robot.png"):
|
109 |
+
st.write(response)
|
110 |
+
st.session_state.messages.append({'role': 'assistant', "content": response})
|
111 |
+
|
man-kddi.png
ADDED
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
python-dotenv
|
3 |
+
llama-index
|
4 |
+
llama-index-embeddings-huggingface
|
5 |
+
llama-index-llms-huggingface
|
robot.png
ADDED