pratham0011 commited on
Commit
c854dfe
1 Parent(s): bb97e48

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import docx2txt
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ icons = {"assistant": "robot.png", "user": "man-kddi.png"}
15
+
16
+ # Configure the Llama index settings
17
+ Settings.llm = HuggingFaceInferenceAPI(
18
+ model_name="meta-llama/Meta-Llama-3-8B-Instruct",
19
+ tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
20
+ context_window=3900,
21
+ token=os.getenv("HF_TOKEN"),
22
+ max_new_tokens=1000,
23
+ generate_kwargs={"temperature": 0.5},
24
+ )
25
+ Settings.embed_model = HuggingFaceEmbedding(
26
+ model_name="BAAI/bge-small-en-v1.5"
27
+ )
28
+
29
+ # Define the directory for persistent storage and data
30
+ PERSIST_DIR = "./db"
31
+ DATA_DIR = "data"
32
+
33
+ # Ensure data directory exists
34
+ os.makedirs(DATA_DIR, exist_ok=True)
35
+ os.makedirs(PERSIST_DIR, exist_ok=True)
36
+
37
+ def displayPDF(file):
38
+ with open(file, "rb") as f:
39
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
40
+ pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
41
+ st.markdown(pdf_display, unsafe_allow_html=True)
42
+
43
+ def displayDOCX(file):
44
+ text = docx2txt.process(file)
45
+ st.text_area("Document Content", text, height=400)
46
+
47
+ def displayTXT(file):
48
+ with open(file, "r") as f:
49
+ text = f.read()
50
+ st.text_area("Document Content", text, height=400)
51
+
52
+ def data_ingestion():
53
+ documents = SimpleDirectoryReader(DATA_DIR).load_data()
54
+ storage_context = StorageContext.from_defaults()
55
+ index = VectorStoreIndex.from_documents(documents)
56
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
57
+
58
+ def handle_query(query):
59
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
60
+ index = load_index_from_storage(storage_context)
61
+ chat_text_qa_msgs = [
62
+ (
63
+ "user",
64
+ """You are Q&A assistant named CHAT-DOC. 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.
65
+ Context:
66
+ {context_str}
67
+ Question:
68
+ {query_str}
69
+ """
70
+ )
71
+ ]
72
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
73
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template)
74
+ answer = query_engine.query(query)
75
+
76
+ if hasattr(answer, 'response'):
77
+ return answer.response
78
+ elif isinstance(answer, dict) and 'response' in answer:
79
+ return answer['response']
80
+ else:
81
+ return "Sorry, I couldn't find an answer."
82
+
83
+ # Streamlit app initialization
84
+ st.title("Chat with your Document 📄")
85
+ st.markdown("Chat here👇")
86
+
87
+ if 'messages' not in st.session_state:
88
+ st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF, DOCX, or TXT file and ask me anything about its content.'}]
89
+
90
+ for message in st.session_state.messages:
91
+ with st.chat_message(message['role'], avatar=icons[message['role']]):
92
+ st.write(message['content'])
93
+
94
+ with st.sidebar:
95
+ st.title("Menu:")
96
+ uploaded_file = st.file_uploader("Upload your document (PDF, DOCX, TXT)", type=["pdf", "docx", "txt"])
97
+ if st.button("Submit & Process") and uploaded_file:
98
+ with st.spinner("Processing..."):
99
+ file_extension = os.path.splitext(uploaded_file.name)[1].lower()
100
+ filepath = os.path.join(DATA_DIR, "uploaded_file" + file_extension)
101
+ with open(filepath, "wb") as f:
102
+ f.write(uploaded_file.getbuffer())
103
+
104
+ if file_extension == ".pdf":
105
+ displayPDF(filepath)
106
+ elif file_extension == ".docx":
107
+ displayDOCX(filepath)
108
+ elif file_extension == ".txt":
109
+ displayTXT(filepath)
110
+
111
+ data_ingestion() # Process file every time a new file is uploaded
112
+ st.success("Done")
113
+
114
+ user_prompt = st.chat_input("Ask me anything about the content of the document:")
115
+
116
+ if user_prompt and uploaded_file:
117
+ st.session_state.messages.append({'role': 'user', "content": user_prompt})
118
+ with st.chat_message("user", avatar=icons["user"]):
119
+ st.write(user_prompt)
120
+
121
+ # Trigger assistant's response retrieval and update UI
122
+ with st.spinner("Thinking..."):
123
+ response = handle_query(user_prompt)
124
+ with st.chat_message("assistant", avatar=icons["assistant"]):
125
+ st.write(response)
126
+ st.session_state.messages.append({'role': 'assistant', "content": response})