Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import streamlit as stfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain_core.messages import HumanMessage, AIMessageChunk, AIMessagefrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_core.vectorstores import InMemoryVectorStoreimport osfrom langchain_core.chat_history import InMemoryChatMessageHistory, BaseChatMessageHistoryimport timefrom graph import get_graphif 'read_file' not in st.session_state:st.session_state.read_file = Falsest.session_state.retriever = Noneif 'chat_history' not in st.session_state:st.session_state.chat_history = {}st.session_state.first_msg = Truedef get_session_by_id(session_id: str) -> BaseChatMessageHistory:if session_id not in st.session_state.chat_history:st.session_state.chat_history[session_id] = InMemoryChatMessageHistory()return st.session_state.chat_history[session_id]return st.session_state.chat_history[session_id]if not st.session_state.read_file:st.title('π€ Upload your PDF to talk with it', anchor=False)file = st.file_uploader('Upload a PDF file', type='pdf')if file:with st.status('π€ Booting up the things!', expanded=True):with st.spinner('π Uploading the PDF...', show_time=True):with open('file.pdf', 'wb') as f:f.write(file.read())loader = PyPDFLoader('file.pdf')documents = loader.load_and_split(RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200))st.success('π File uploaded successfully!!!')with st.spinner('π§ Reading the file...', show_time=True):vstore = InMemoryVectorStore.from_documents(documents, HuggingFaceEmbeddings(model_name='all-MiniLM-L6-v2'))st.session_state.retriever = vstore.as_retriever()st.success('π§ File read successfully!!!')os.remove('file.pdf')with st.spinner('π΄ Waking up the LLM...', show_time=True):st.session_state.graph = get_graph(st.session_state.retriever)st.success('π LLM awakened!!!')st.balloons()placeholder = st.empty()for _ in range(5, -1, -1):placeholder.write(f'β³ Chat starting in 0{_} sec.')time.sleep(1)st.session_state.read_file = Truest.rerun()if st.session_state.read_file:st.title('π€ DocAI', anchor=False)st.subheader('Chat with your document!', anchor=False)if st.session_state.first_msg:st.session_state.first_msg = Falseget_session_by_id('chat42').add_message(AIMessage(content='Hello, how are you? How about we talk about the ''document you sent me to read?'))for msg in get_session_by_id('chat42').messages:with st.chat_message(name='user' if isinstance(msg, HumanMessage) else 'ai'):st.write(msg.content)prompt = st.chat_input('Try to ask something about your file!')if prompt:with st.chat_message(name='user'):st.write(prompt)response = st.session_state.graph.stream({'question': prompt,'scratchpad': None,'answer': None,'next_node': None,'history': get_session_by_id('chat42').messages,},stream_mode='messages')get_session_by_id('chat42').add_message(HumanMessage(content=prompt))def get_message():for chunk, _ in response:if chunk.content and isinstance(chunk, AIMessageChunk):yield chunk.contentwith st.chat_message(name='ai'):full_response = ''placeholder = st.empty()for msg in get_message():full_response += msgif '</tool>' in full_response:full_response = ''continueif '<tool>' in full_response:continueplaceholder.write(full_response)print(full_response)get_session_by_id('chat42').add_message(AIMessage(content=full_response))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import streamlit as stfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain_core.messages import HumanMessage, AIMessageChunk, AIMessagefrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_core.vectorstores import InMemoryVectorStoreimport osfrom langchain_core.chat_history import InMemoryChatMessageHistory, BaseChatMessageHistoryimport timefrom graph import get_graphif 'read_file' not in st.session_state:st.session_state.read_file = Falsest.session_state.retriever = Noneif 'chat_history' not in st.session_state:st.session_state.chat_history = {}st.session_state.first_msg = Truedef get_session_by_id(session_id: str) -> BaseChatMessageHistory:if session_id not in st.session_state.chat_history:st.session_state.chat_history[session_id] = InMemoryChatMessageHistory()return st.session_state.chat_history[session_id]return st.session_state.chat_history[session_id]if not st.session_state.read_file:st.title('π€ Upload your PDF to talk with it', anchor=False)file = st.file_uploader('Upload a PDF file', type='pdf')if file:with st.status('π€ Booting up the things!', expanded=True):with st.spinner('π Uploading the PDF...', show_time=True):with open('file.pdf', 'wb') as f:f.write(file.read())loader = PyPDFLoader('file.pdf')documents = loader.load_and_split(RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200))st.success('π File uploaded successfully!!!')with st.spinner('π§ Reading the file...', show_time=True):vstore = InMemoryVectorStore.from_documents(documents, HuggingFaceEmbeddings(model_name='all-MiniLM-L6-v2'))st.session_state.retriever = vstore.as_retriever()st.success('π§ File read successfully!!!')os.remove('file.pdf')with st.spinner('π΄ Waking up the LLM...', show_time=True):st.session_state.graph = get_graph(st.session_state.retriever)st.success('π LLM awakened!!!')st.balloons()placeholder = st.empty()for _ in range(5, -1, -1):placeholder.write(f'β³ Chat starting in 0{_} sec.')time.sleep(1)st.session_state.read_file = Truest.rerun()if st.session_state.read_file:st.title('π€ DocAI', anchor=False)st.subheader('Chat with your document!', anchor=False)if st.session_state.first_msg:st.session_state.first_msg = Falseget_session_by_id('chat42').add_message(AIMessage(content='Hello, how are you? How about we talk about the ''document you sent me to read?'))for msg in get_session_by_id('chat42').messages:with st.chat_message(name='user' if isinstance(msg, HumanMessage) else 'ai'):st.write(msg.content)prompt = st.chat_input('Try to ask something about your file!')if prompt:with st.chat_message(name='user'):st.write(prompt)response = st.session_state.graph.stream({'question': prompt,'scratchpad': None,'answer': None,'next_node': None,'history': get_session_by_id('chat42').messages,},stream_mode='messages')get_session_by_id('chat42').add_message(HumanMessage(content=prompt))def get_message():for chunk, _ in response:if chunk.content and isinstance(chunk, AIMessageChunk):yield chunk.contentwith st.chat_message(name='ai'):full_response = ''tool_placeholder = st.empty()placeholders = {}prompt_message_placeholder = st.empty()for msg in get_message():full_response += msgif '<tool>' in full_response:with tool_placeholder.status('Reading document...', expanded=True):if 'tool_message_placeholder' not in placeholders:placeholders['tool_message_placeholder'] = st.empty()placeholders['tool_message_placeholder'].write(full_response.replace('<tool>', '').replace('</tool>', '').replace('retriever', 'Retrieving document'))prompt_message_placeholder.empty()if '</tool>' in full_response:full_response = ''continueelse:prompt_message_placeholder.write(full_response)get_session_by_id('chat42').add_message(AIMessage(content=full_response))
app.py+111-102