Spaces:
Sleeping
Sleeping
Create app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Bring in dependenciesimport osimport streamlit as stfrom langchain.llms import LlamaCppfrom langchain.embeddings import LlamaCppEmbeddingsfrom langchain.prompts import PromptTemplatefrom langchain.chains import LLMChainfrom langchain.document_loaders import TextLoaderfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Chromaimport PyPDF2
# Model Download SectionMODEL_DIR = "./models"MODEL_FILE = "llama-2-7b.ggmlv3.q4_0.bin"MODEL_PATH = os.path.join(MODEL_DIR, MODEL_FILE)
# Create model directory and download model if not existsif not os.path.exists(MODEL_PATH): os.makedirs(MODEL_DIR, exist_ok=True) os.system(f"wget -O {MODEL_PATH} https://huggingface.co/TheBloke/Llama-2-7B-GGML/resolve/main/{MODEL_FILE}")
# Streamlit page settingsst.set_page_config(page_title="DOCAI", page_icon="🤖", layout="wide")st.title("📄 Document Chat with LLaMA 🤖")
# Function to extract text from PDFdef extract_text_from_pdf(file): reader = PyPDF2.PdfReader(file) text = "" for page in reader.pages: text += page.extract_text() return text
# Function to write text into a temp filedef write_text_file(content, file_path): try: with open(file_path, 'w', encoding='utf-8') as f: f.write(content) return True except Exception as e: print(f"Error writing file: {e}") return False
# Prompt Templateprompt_template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say you don't know. Don't make up stuff.
{context}
Question: {question}Answer:"""prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
# Initialize the LLM and Embeddingsllm = LlamaCpp(model_path=MODEL_PATH)embeddings = LlamaCppEmbeddings(model_path=MODEL_PATH)llm_chain = LLMChain(llm=llm, prompt=prompt)
# Upload the PDFuploaded_file = st.file_uploader("Upload a PDF document", type="pdf")
if uploaded_file is not None: # Extract and save text text_content = extract_text_from_pdf(uploaded_file) file_path = "./temp_file.txt" write_text_file(text_content, file_path)
# Load and split text loader = TextLoader(file_path) docs = loader.load() text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0) texts = text_splitter.split_documents(docs)
# Create vector database db = Chroma.from_documents(texts, embeddings)
st.success("✅ PDF Loaded and Processed Successfully!")
# Ask questions question = st.text_input("Ask your question from the PDF:") if question: similar_doc = db.similarity_search(question, k=1) context = similar_doc[0].page_content response = llm_chain.run({"context": context, "question": question}) st.write(response)app.pyAdded+86