rbbist commited on
Commit
0dfdf39
·
verified ·
1 Parent(s): abe2d80

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +90 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,92 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from PyPDF2 import PdfReader
3
+ from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
5
+ from langchain.vectorstores import FAISS
6
+ from langchain.memory import ConversationBufferMemory
7
+ from langchain.chains import ConversationalRetrievalChain
8
+ from langchain.llms import HuggingFaceHub
9
+ from htmlTemplates import css, bot_template, user_template
10
+ import os
11
 
12
+ def get_pdf_text(pdf_docs):
13
+ text = ""
14
+ for pdf in pdf_docs:
15
+ pdf_reader = PdfReader(pdf)
16
+ for page in pdf_reader.pages:
17
+ page_text = page.extract_text()
18
+ if page_text:
19
+ text += page_text
20
+ return text
21
+
22
+
23
+ def get_text_chunks(text):
24
+ text_splitter = CharacterTextSplitter(
25
+ separator="\n",
26
+ chunk_size=1000,
27
+ chunk_overlap=200,
28
+ length_function=len
29
+ )
30
+ return text_splitter.split_text(text)
31
+
32
+
33
+ def get_vectorstore(text_chunks):
34
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
35
+ return FAISS.from_texts(texts=text_chunks, embedding=embeddings)
36
+
37
+
38
+ def get_conversation_chain(vectorstore):
39
+ llm = HuggingFaceHub(
40
+ repo_id="google/flan-t5-xxl",
41
+ model_kwargs={"temperature": 0.5, "max_length": 512}
42
+ )
43
+
44
+ memory = ConversationBufferMemory(
45
+ memory_key='chat_history', return_messages=True
46
+ )
47
+
48
+ return ConversationalRetrievalChain.from_llm(
49
+ llm=llm,
50
+ retriever=vectorstore.as_retriever(),
51
+ memory=memory
52
+ )
53
+
54
+
55
+ def handle_userinput(user_question):
56
+ response = st.session_state.conversation({'question': user_question})
57
+ st.session_state.chat_history = response['chat_history']
58
+
59
+ for i, message in enumerate(st.session_state.chat_history):
60
+ if i % 2 == 0:
61
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
62
+ else:
63
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
64
+
65
+
66
+ def main():
67
+ st.set_page_config(page_title="Chat with your PDFs", page_icon="📚")
68
+ st.write(css, unsafe_allow_html=True)
69
+
70
+ if "conversation" not in st.session_state:
71
+ st.session_state.conversation = None
72
+ if "chat_history" not in st.session_state:
73
+ st.session_state.chat_history = None
74
+
75
+ st.header("Chat with your PDFs 📚")
76
+ user_question = st.text_input("Ask something about your PDFs:")
77
+ if user_question:
78
+ handle_userinput(user_question)
79
+
80
+ with st.sidebar:
81
+ st.subheader("Your documents")
82
+ pdf_docs = st.file_uploader("Upload PDFs", accept_multiple_files=True)
83
+ if st.button("Process"):
84
+ with st.spinner("Processing..."):
85
+ raw_text = get_pdf_text(pdf_docs)
86
+ text_chunks = get_text_chunks(raw_text)
87
+ vectorstore = get_vectorstore(text_chunks)
88
+ st.session_state.conversation = get_conversation_chain(vectorstore)
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()