Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,157 @@
|
|
| 1 |
-
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from ctransformers import AutoModelForCausalLM
|
| 3 |
-
from fastapi import FastAPI
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
-
import time
|
| 6 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 7 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 8 |
import numpy as np
|
| 9 |
import PyPDF2
|
| 10 |
|
| 11 |
# Load the model
|
| 12 |
-
@st.cache_resource
|
| 13 |
def load_model():
|
| 14 |
return AutoModelForCausalLM.from_pretrained(
|
| 15 |
"llama-2-7b-chat.Q5_K_M.gguf",
|
|
@@ -20,26 +162,7 @@ def load_model():
|
|
| 20 |
|
| 21 |
llm = load_model()
|
| 22 |
|
| 23 |
-
# Pydantic object
|
| 24 |
-
class Validation(BaseModel):
|
| 25 |
-
prompt: str
|
| 26 |
-
context: str
|
| 27 |
-
|
| 28 |
-
# FastAPI
|
| 29 |
-
app = FastAPI()
|
| 30 |
-
|
| 31 |
-
@app.post("/llm_on_cpu")
|
| 32 |
-
async def stream(item: Validation):
|
| 33 |
-
system_prompt = "You are an intelligent assistant. Answer the question based solely on the provided context. If the answer cannot be found in the context, say 'I don't have enough information to answer this question based on the provided context.'"
|
| 34 |
-
B_INST, E_INST = "[INST]", "[/INST]"
|
| 35 |
-
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
| 36 |
-
|
| 37 |
-
full_prompt = f"{B_INST}{B_SYS}{system_prompt}{E_SYS}Context: {item.context}\n\nQuestion: {item.prompt}\n\nAnswer:{E_INST}"
|
| 38 |
-
|
| 39 |
-
return llm(full_prompt, stream=True)
|
| 40 |
-
|
| 41 |
# Helper functions
|
| 42 |
-
@st.cache_resource
|
| 43 |
def get_vectorizer():
|
| 44 |
return TfidfVectorizer()
|
| 45 |
|
|
@@ -63,83 +186,76 @@ def generate_llama_response(prompt, context):
|
|
| 63 |
|
| 64 |
full_prompt = f"{B_INST}{B_SYS}{system_prompt}{E_SYS}Context: {context}\n\nQuestion: {prompt}\n\nAnswer:{E_INST}"
|
| 65 |
|
| 66 |
-
return llm(full_prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
-
def summarize_pdf(documents
|
| 76 |
context = " ".join(documents[:3])
|
| 77 |
prompt = "Provide a concise summary of the main points in the following text:"
|
| 78 |
-
|
| 79 |
|
| 80 |
-
def create_questions(documents
|
| 81 |
context = " ".join(documents[:3])
|
| 82 |
prompt = "Generate 5 important questions based on the following text. These questions should cover key concepts and encourage critical thinking:"
|
| 83 |
-
|
| 84 |
|
| 85 |
-
def create_notes(documents
|
| 86 |
context = " ".join(documents[:3])
|
| 87 |
prompt = "Create concise and informative notes based on the following text. Focus on key concepts, definitions, and important points:"
|
| 88 |
-
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
|
| 98 |
-
def main():
|
| 99 |
-
st.title("LLaMA-2 PDF Analysis and Chat Interface")
|
| 100 |
-
|
| 101 |
-
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 102 |
-
|
| 103 |
-
if uploaded_file is not None:
|
| 104 |
-
text = extract_text_from_pdf(uploaded_file)
|
| 105 |
-
chunk_size = 1000
|
| 106 |
-
documents = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
|
| 107 |
-
|
| 108 |
-
st.success("PDF uploaded and processed successfully!")
|
| 109 |
-
|
| 110 |
-
# Create columns for buttons
|
| 111 |
-
col1, col2, col3 = st.columns(3)
|
| 112 |
-
|
| 113 |
-
with col1:
|
| 114 |
-
if st.button("Summarize PDF"):
|
| 115 |
-
with st.spinner("Generating summary..."):
|
| 116 |
-
placeholder = st.empty()
|
| 117 |
-
summarize_pdf(documents, placeholder)
|
| 118 |
-
|
| 119 |
-
with col2:
|
| 120 |
-
if st.button("Generate Questions"):
|
| 121 |
-
with st.spinner("Generating questions..."):
|
| 122 |
-
placeholder = st.empty()
|
| 123 |
-
create_questions(documents, placeholder)
|
| 124 |
-
|
| 125 |
-
with col3:
|
| 126 |
-
if st.button("Create Notes"):
|
| 127 |
-
with st.spinner("Creating notes..."):
|
| 128 |
-
placeholder = st.empty()
|
| 129 |
-
create_notes(documents, placeholder)
|
| 130 |
-
|
| 131 |
-
# Chat interface
|
| 132 |
-
st.subheader("Chat with the PDF")
|
| 133 |
-
user_question = st.text_input("Ask a question about the PDF:")
|
| 134 |
-
if user_question:
|
| 135 |
-
relevant_docs = retrieve_documents(user_question, documents)
|
| 136 |
-
context = " ".join(relevant_docs)
|
| 137 |
-
with st.spinner("Generating answer..."):
|
| 138 |
-
placeholder = st.empty()
|
| 139 |
-
stream_response(user_question, context, placeholder)
|
| 140 |
-
|
| 141 |
-
else:
|
| 142 |
-
st.info("Please upload a PDF file to begin.")
|
| 143 |
-
|
| 144 |
-
if __name__ == "__main__":
|
| 145 |
-
main()
|
|
|
|
| 1 |
+
# import streamlit as st
|
| 2 |
+
# from ctransformers import AutoModelForCausalLM
|
| 3 |
+
# from fastapi import FastAPI
|
| 4 |
+
# from pydantic import BaseModel
|
| 5 |
+
# import time
|
| 6 |
+
# from sklearn.feature_extraction.text import TfidfVectorizer
|
| 7 |
+
# from sklearn.metrics.pairwise import cosine_similarity
|
| 8 |
+
# import numpy as np
|
| 9 |
+
# import PyPDF2
|
| 10 |
+
|
| 11 |
+
# # Load the model
|
| 12 |
+
# @st.cache_resource
|
| 13 |
+
# def load_model():
|
| 14 |
+
# return AutoModelForCausalLM.from_pretrained(
|
| 15 |
+
# "llama-2-7b-chat.Q5_K_M.gguf",
|
| 16 |
+
# model_type='llama',
|
| 17 |
+
# max_new_tokens=1096,
|
| 18 |
+
# threads=3,
|
| 19 |
+
# )
|
| 20 |
+
|
| 21 |
+
# llm = load_model()
|
| 22 |
+
|
| 23 |
+
# # Pydantic object
|
| 24 |
+
# class Validation(BaseModel):
|
| 25 |
+
# prompt: str
|
| 26 |
+
# context: str
|
| 27 |
+
|
| 28 |
+
# # FastAPI
|
| 29 |
+
# app = FastAPI()
|
| 30 |
+
|
| 31 |
+
# @app.post("/llm_on_cpu")
|
| 32 |
+
# async def stream(item: Validation):
|
| 33 |
+
# system_prompt = "You are an intelligent assistant. Answer the question based solely on the provided context. If the answer cannot be found in the context, say 'I don't have enough information to answer this question based on the provided context.'"
|
| 34 |
+
# B_INST, E_INST = "[INST]", "[/INST]"
|
| 35 |
+
# B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
| 36 |
+
|
| 37 |
+
# full_prompt = f"{B_INST}{B_SYS}{system_prompt}{E_SYS}Context: {item.context}\n\nQuestion: {item.prompt}\n\nAnswer:{E_INST}"
|
| 38 |
+
|
| 39 |
+
# return llm(full_prompt, stream=True)
|
| 40 |
+
|
| 41 |
+
# # Helper functions
|
| 42 |
+
# @st.cache_resource
|
| 43 |
+
# def get_vectorizer():
|
| 44 |
+
# return TfidfVectorizer()
|
| 45 |
+
|
| 46 |
+
# def encode_texts(texts, vectorizer):
|
| 47 |
+
# return vectorizer.fit_transform(texts)
|
| 48 |
+
|
| 49 |
+
# def retrieve_documents(query, documents, top_k=3):
|
| 50 |
+
# vectorizer = get_vectorizer()
|
| 51 |
+
# all_texts = documents + [query]
|
| 52 |
+
# embeddings = encode_texts(all_texts, vectorizer)
|
| 53 |
+
# doc_embeddings = embeddings[:-1]
|
| 54 |
+
# query_embedding = embeddings[-1]
|
| 55 |
+
# similarities = cosine_similarity(query_embedding, doc_embeddings).flatten()
|
| 56 |
+
# top_indices = np.argsort(similarities)[-top_k:][::-1]
|
| 57 |
+
# return [documents[i] for i in top_indices]
|
| 58 |
+
|
| 59 |
+
# def generate_llama_response(prompt, context):
|
| 60 |
+
# system_prompt = "You are an intelligent assistant. Answer the question based solely on the provided context. If the answer cannot be found in the context, say 'I don't have enough information to answer this question based on the provided context.'"
|
| 61 |
+
# B_INST, E_INST = "[INST]", "[/INST]"
|
| 62 |
+
# B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
| 63 |
+
|
| 64 |
+
# full_prompt = f"{B_INST}{B_SYS}{system_prompt}{E_SYS}Context: {context}\n\nQuestion: {prompt}\n\nAnswer:{E_INST}"
|
| 65 |
+
|
| 66 |
+
# return llm(full_prompt, stream=True)
|
| 67 |
+
|
| 68 |
+
# def stream_response(prompt, context, placeholder):
|
| 69 |
+
# response = ""
|
| 70 |
+
# for token in generate_llama_response(prompt, context):
|
| 71 |
+
# response += token
|
| 72 |
+
# placeholder.markdown(response + "▌")
|
| 73 |
+
# placeholder.markdown(response)
|
| 74 |
+
|
| 75 |
+
# def summarize_pdf(documents, placeholder):
|
| 76 |
+
# context = " ".join(documents[:3])
|
| 77 |
+
# prompt = "Provide a concise summary of the main points in the following text:"
|
| 78 |
+
# stream_response(prompt, context, placeholder)
|
| 79 |
+
|
| 80 |
+
# def create_questions(documents, placeholder):
|
| 81 |
+
# context = " ".join(documents[:3])
|
| 82 |
+
# prompt = "Generate 5 important questions based on the following text. These questions should cover key concepts and encourage critical thinking:"
|
| 83 |
+
# stream_response(prompt, context, placeholder)
|
| 84 |
+
|
| 85 |
+
# def create_notes(documents, placeholder):
|
| 86 |
+
# context = " ".join(documents[:3])
|
| 87 |
+
# prompt = "Create concise and informative notes based on the following text. Focus on key concepts, definitions, and important points:"
|
| 88 |
+
# stream_response(prompt, context, placeholder)
|
| 89 |
+
|
| 90 |
+
# def extract_text_from_pdf(file):
|
| 91 |
+
# pdf_reader = PyPDF2.PdfReader(file)
|
| 92 |
+
# text = ""
|
| 93 |
+
# for page in pdf_reader.pages:
|
| 94 |
+
# text += page.extract_text()
|
| 95 |
+
# return text
|
| 96 |
+
|
| 97 |
+
# # Streamlit UI
|
| 98 |
+
# def main():
|
| 99 |
+
# st.title("LLaMA-2 PDF Analysis and Chat Interface")
|
| 100 |
+
|
| 101 |
+
# uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 102 |
+
|
| 103 |
+
# if uploaded_file is not None:
|
| 104 |
+
# text = extract_text_from_pdf(uploaded_file)
|
| 105 |
+
# chunk_size = 1000
|
| 106 |
+
# documents = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
|
| 107 |
+
|
| 108 |
+
# st.success("PDF uploaded and processed successfully!")
|
| 109 |
+
|
| 110 |
+
# # Create columns for buttons
|
| 111 |
+
# col1, col2, col3 = st.columns(3)
|
| 112 |
+
|
| 113 |
+
# with col1:
|
| 114 |
+
# if st.button("Summarize PDF"):
|
| 115 |
+
# with st.spinner("Generating summary..."):
|
| 116 |
+
# placeholder = st.empty()
|
| 117 |
+
# summarize_pdf(documents, placeholder)
|
| 118 |
+
|
| 119 |
+
# with col2:
|
| 120 |
+
# if st.button("Generate Questions"):
|
| 121 |
+
# with st.spinner("Generating questions..."):
|
| 122 |
+
# placeholder = st.empty()
|
| 123 |
+
# create_questions(documents, placeholder)
|
| 124 |
+
|
| 125 |
+
# with col3:
|
| 126 |
+
# if st.button("Create Notes"):
|
| 127 |
+
# with st.spinner("Creating notes..."):
|
| 128 |
+
# placeholder = st.empty()
|
| 129 |
+
# create_notes(documents, placeholder)
|
| 130 |
+
|
| 131 |
+
# # Chat interface
|
| 132 |
+
# st.subheader("Chat with the PDF")
|
| 133 |
+
# user_question = st.text_input("Ask a question about the PDF:")
|
| 134 |
+
# if user_question:
|
| 135 |
+
# relevant_docs = retrieve_documents(user_question, documents)
|
| 136 |
+
# context = " ".join(relevant_docs)
|
| 137 |
+
# with st.spinner("Generating answer..."):
|
| 138 |
+
# placeholder = st.empty()
|
| 139 |
+
# stream_response(user_question, context, placeholder)
|
| 140 |
+
|
| 141 |
+
# else:
|
| 142 |
+
# st.info("Please upload a PDF file to begin.")
|
| 143 |
+
|
| 144 |
+
# if __name__ == "__main__":
|
| 145 |
+
# main()
|
| 146 |
+
|
| 147 |
+
import gradio as gr
|
| 148 |
from ctransformers import AutoModelForCausalLM
|
|
|
|
|
|
|
|
|
|
| 149 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 150 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 151 |
import numpy as np
|
| 152 |
import PyPDF2
|
| 153 |
|
| 154 |
# Load the model
|
|
|
|
| 155 |
def load_model():
|
| 156 |
return AutoModelForCausalLM.from_pretrained(
|
| 157 |
"llama-2-7b-chat.Q5_K_M.gguf",
|
|
|
|
| 162 |
|
| 163 |
llm = load_model()
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
# Helper functions
|
|
|
|
| 166 |
def get_vectorizer():
|
| 167 |
return TfidfVectorizer()
|
| 168 |
|
|
|
|
| 186 |
|
| 187 |
full_prompt = f"{B_INST}{B_SYS}{system_prompt}{E_SYS}Context: {context}\n\nQuestion: {prompt}\n\nAnswer:{E_INST}"
|
| 188 |
|
| 189 |
+
return llm(full_prompt)
|
| 190 |
+
|
| 191 |
+
def extract_text_from_pdf(file):
|
| 192 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
| 193 |
+
text = ""
|
| 194 |
+
for page in pdf_reader.pages:
|
| 195 |
+
text += page.extract_text()
|
| 196 |
+
return text
|
| 197 |
|
| 198 |
+
# Gradio functions
|
| 199 |
+
def process_pdf(file):
|
| 200 |
+
text = extract_text_from_pdf(file)
|
| 201 |
+
chunk_size = 1000
|
| 202 |
+
documents = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
|
| 203 |
+
return documents
|
| 204 |
|
| 205 |
+
def summarize_pdf(documents):
|
| 206 |
context = " ".join(documents[:3])
|
| 207 |
prompt = "Provide a concise summary of the main points in the following text:"
|
| 208 |
+
return generate_llama_response(prompt, context)
|
| 209 |
|
| 210 |
+
def create_questions(documents):
|
| 211 |
context = " ".join(documents[:3])
|
| 212 |
prompt = "Generate 5 important questions based on the following text. These questions should cover key concepts and encourage critical thinking:"
|
| 213 |
+
return generate_llama_response(prompt, context)
|
| 214 |
|
| 215 |
+
def create_notes(documents):
|
| 216 |
context = " ".join(documents[:3])
|
| 217 |
prompt = "Create concise and informative notes based on the following text. Focus on key concepts, definitions, and important points:"
|
| 218 |
+
return generate_llama_response(prompt, context)
|
| 219 |
|
| 220 |
+
def chat_with_pdf(documents, user_question):
|
| 221 |
+
relevant_docs = retrieve_documents(user_question, documents)
|
| 222 |
+
context = " ".join(relevant_docs)
|
| 223 |
+
return generate_llama_response(user_question, context)
|
| 224 |
+
|
| 225 |
+
# Gradio interface
|
| 226 |
+
def gradio_interface(pdf_file):
|
| 227 |
+
documents = process_pdf(pdf_file)
|
| 228 |
+
|
| 229 |
+
summary = summarize_pdf(documents)
|
| 230 |
+
questions = create_questions(documents)
|
| 231 |
+
notes = create_notes(documents)
|
| 232 |
+
|
| 233 |
+
def chat(user_question):
|
| 234 |
+
return chat_with_pdf(documents, user_question)
|
| 235 |
+
|
| 236 |
+
return (
|
| 237 |
+
gr.Textbox(value=summary, label="PDF Summary"),
|
| 238 |
+
gr.Textbox(value=questions, label="Generated Questions"),
|
| 239 |
+
gr.Textbox(value=notes, label="Created Notes"),
|
| 240 |
+
gr.Textbox(placeholder="Ask a question about the PDF", label="Chat with PDF"),
|
| 241 |
+
gr.Textbox(label="Answer"),
|
| 242 |
+
gr.Button("Ask"),
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
iface = gr.Interface(
|
| 246 |
+
fn=gradio_interface,
|
| 247 |
+
inputs=gr.File(label="Upload PDF"),
|
| 248 |
+
outputs=[
|
| 249 |
+
gr.Textbox(label="PDF Summary"),
|
| 250 |
+
gr.Textbox(label="Generated Questions"),
|
| 251 |
+
gr.Textbox(label="Created Notes"),
|
| 252 |
+
gr.Textbox(label="Chat with PDF"),
|
| 253 |
+
gr.Textbox(label="Answer"),
|
| 254 |
+
gr.Button("Ask"),
|
| 255 |
+
],
|
| 256 |
+
title="LLaMA-2 PDF Analysis and Chat Interface",
|
| 257 |
+
description="Upload a PDF file to analyze and chat with its content using LLaMA-2.",
|
| 258 |
+
allow_flagging="never",
|
| 259 |
+
)
|
| 260 |
|
| 261 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|