Spaces:
Build error
Build error
Download app.py from galaxyweblinks/llmaidemo: direct link, hf CLI and curl.
- Browser
- Download file 7.27 kB
-
https://huggingface.co/spaces/galaxyweblinks/llmaidemo/resolve/main/app.py
- Command line
-
hf download hf://spaces/galaxyweblinks/llmaidemo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/galaxyweblinks/llmaidemo/resolve/main/app.py
7.27 kB
| import streamlit as st | |
| from PyPDF2 import PdfReader | |
| from langchain.text_splitter import CharacterTextSplitter | |
| from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings | |
| from langchain_community.vectorstores import FAISS | |
| from langchain.memory import ConversationBufferMemory | |
| from langchain.chains import ConversationalRetrievalChain | |
| #from langchain.chat_models import ChatOpenAI | |
| from langchain_openai import ChatOpenAI | |
| from htmlTemplates import bot_template, user_template, css, img_template | |
| from transformers import pipeline | |
| import os, re, glob | |
| import fitz | |
| def get_pdf_text(pdf_files): | |
| text = "" | |
| for pdf_file in pdf_files: | |
| file = pdf_file.name.replace(".pdf", "").replace(" ","") | |
| reader = PdfReader(pdf_file) | |
| i=0 | |
| for page in reader.pages: | |
| i += 1 | |
| text += f"""##{file}_page{i}## {page.extract_text()}@@""" | |
| return text | |
| def extract_images_from_pdf(pdf_path, image_folder): | |
| # Open the PDF file | |
| file = os.path.basename(pdf_path).replace(".pdf", "").replace(" ","") | |
| pdf_document = fitz.open(pdf_path) | |
| # Iterate through pages | |
| for page_number in range(pdf_document.page_count): | |
| page = pdf_document[page_number] | |
| # Get the images on the page | |
| images = page.get_images(full=True) | |
| for img_index, img_info in enumerate(images): | |
| try: | |
| image_index = img_info[0] | |
| # Get the image information | |
| base_image = pdf_document.extract_image(image_index) | |
| # Get the image bytes | |
| image_bytes = base_image["image"] | |
| # Save the image | |
| image_filename = f"{image_folder}/{file}_page{page_number + 1}_img{img_index + 1}.png" | |
| with open(image_filename, "wb") as image_file: | |
| image_file.write(image_bytes) | |
| except Exception: | |
| continue | |
| # Close the PDF file | |
| pdf_document.close() | |
| def get_chunk_text(text): | |
| text_splitter = CharacterTextSplitter( | |
| separator = "\n", | |
| chunk_size = 2000, | |
| chunk_overlap = 200, | |
| length_function = len | |
| ) | |
| chunks = text_splitter.split_text(text) | |
| return chunks | |
| def get_vector_store(text_chunks): | |
| # For OpenAI Embeddings | |
| embeddings = OpenAIEmbeddings() | |
| # For Huggingface Embeddings | |
| # embeddings = HuggingFaceInstructEmbeddings(model_name = "hkunlp/instructor-xl") | |
| vectorstore = FAISS.from_texts(texts = text_chunks, embedding = embeddings) | |
| return vectorstore | |
| def get_conversation_chain(vector_store): | |
| # OpenAI Model | |
| llm = ChatOpenAI() | |
| #model_name='gpt-4-32k', #gpt-3.5-turbo-16k temperature=0, | |
| # HuggingFace Model | |
| # llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512}) | |
| memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True) | |
| conversation_chain = ConversationalRetrievalChain.from_llm( | |
| llm = llm, | |
| retriever = vector_store.as_retriever(), | |
| memory = memory | |
| ) | |
| return conversation_chain | |
| def handle_user_input(question): | |
| response = st.session_state.conversation({"question":question}) | |
| search = st.session_state.vectorDB.similarity_search(question, k=1) | |
| images = [] | |
| if search: | |
| result = re.search('##(.*)##', search[0].page_content) | |
| images = glob.glob(f'images/{result.group(1)}_*') | |
| st.session_state.chat_history.append({"question":question, "answer": response['answer'], "images": images}) | |
| #print(response) | |
| for i, message in enumerate(st.session_state.chat_history): | |
| st.write(user_template.replace("{{MSG}}", message["question"]), unsafe_allow_html=True) | |
| st.write(bot_template.replace("{{MSG}}", message["answer"]), unsafe_allow_html=True) | |
| #image | |
| # if message["images"]: | |
| # groups = [] | |
| # n = 3 | |
| # for i in range(0, len(message["images"]), n): | |
| # groups.append(message["images"][i:i+n]) | |
| # for group in groups: | |
| # cols = st.columns(n) | |
| # for i, img in enumerate(group): | |
| # cols[i].image(img) | |
| #print(st.session_state) | |
| def save_uploaded_files(uploaded_files): | |
| for uploaded_file in uploaded_files: | |
| with open(os.path.join("uploads", uploaded_file.name), "wb") as f: | |
| f.write(uploaded_file.read()) | |
| def main(): | |
| #load_dotenv() | |
| st.set_page_config(page_title='LLM POC') | |
| st.write(css, unsafe_allow_html=True) | |
| if "conversation" not in st.session_state: | |
| st.session_state.conversation = [] | |
| if "chat_history" not in st.session_state: | |
| st.session_state.chat_history = [] | |
| images = glob.glob('images/*') | |
| for im in images: | |
| os.remove(im) | |
| if "vectorDB" not in st.session_state: | |
| st.session_state.vectorDB = None | |
| if not os.path.exists("images"): | |
| os.makedirs("images") | |
| if not os.path.exists("uploads"): | |
| os.makedirs("uploads") | |
| files = glob.glob('uploads/*') | |
| for f in files: | |
| os.remove(f) | |
| st.header('LLM - POC') | |
| # question = st.text_input("Ask anything to your Documents: ") | |
| # if question: | |
| # handle_user_input(question) | |
| # React to user input | |
| if prompt := st.chat_input("Ask anything to your Documents"): | |
| handle_user_input(prompt) | |
| with st.sidebar: | |
| st.subheader("Upload your Documents Here: ") | |
| os.environ["OPENAI_API_KEY"] = st.text_input("OpenAI API Key", placeholder="sk-") | |
| pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True) | |
| save_uploaded_files(pdf_files) | |
| if st.button("OK"): | |
| with st.spinner("Processing your PDFs..."): | |
| # Get PDF Text | |
| pdfs = glob.glob("uploads/*") | |
| text_PdfReader = get_pdf_text(pdf_files) | |
| for pdf in pdfs: | |
| extract_images_from_pdf(pdf, 'images') | |
| # Get Text Chunks | |
| text_chunks = text_PdfReader[:-2].split('@@') #per page | |
| # Create Vector Store | |
| vector_store = get_vector_store(text_chunks) | |
| model = ChatOpenAI(temperature=0, | |
| model="gpt-4-vision-preview", | |
| max_tokens=1024) | |
| memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True) | |
| chain = ConversationalRetrievalChain.from_llm( | |
| llm = model, | |
| retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k":10}), | |
| memory = memory, | |
| verbose=True, | |
| condense_question_llm=model, | |
| chain_type="stuff", | |
| ) | |
| st.write("DONE") | |
| # Create conversation chain | |
| st.session_state.conversation = chain #get_conversation_chain(vector_store) | |
| st.session_state.vectorDB = vector_store | |
| if __name__ == '__main__': | |
| main() | |