MEOW commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,34 @@
|
|
| 1 |
-
# Import necessary libraries
|
| 2 |
-
import warnings
|
| 3 |
-
from langchain_core._api.deprecation import LangChainDeprecationWarning
|
| 4 |
-
|
| 5 |
-
warnings.filterwarnings("ignore", category=LangChainDeprecationWarning, module="llama_index")
|
| 6 |
-
|
| 7 |
-
import getpass
|
| 8 |
-
import os
|
| 9 |
import gradio as gr
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from llama_index.llms.nvidia import NVIDIA
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
from llama_index.readers
|
|
|
|
|
|
|
|
|
|
| 19 |
DocxReader,
|
| 20 |
PDFReader,
|
| 21 |
-
|
| 22 |
ImageReader,
|
| 23 |
-
PptxReader,
|
| 24 |
CSVReader,
|
| 25 |
)
|
| 26 |
|
| 27 |
-
|
|
|
|
| 28 |
Settings.embed_model = NVIDIAEmbedding(model="NV-Embed-QA", truncate="END")
|
| 29 |
-
|
| 30 |
-
from llama_index.vector_stores.milvus import MilvusVectorStore
|
| 31 |
-
|
| 32 |
-
from llama_index.core.node_parser import SentenceSplitter
|
| 33 |
Settings.text_splitter = SentenceSplitter(chunk_size=400)
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# Import Nemo modules
|
| 36 |
|
|
@@ -40,6 +38,7 @@ from nemoguardrails import LLMRails, RailsConfig
|
|
| 40 |
config = RailsConfig.from_path("./Config")
|
| 41 |
rails = LLMRails(config)
|
| 42 |
|
|
|
|
| 43 |
# Initialize global variables for the index and query engine
|
| 44 |
index = None
|
| 45 |
query_engine = None
|
|
@@ -51,120 +50,115 @@ def get_files_from_input(file_objs):
|
|
| 51 |
return [file_obj.name for file_obj in file_objs]
|
| 52 |
|
| 53 |
# Function to load documents and create the index
|
| 54 |
-
def load_documents(file_objs):
|
| 55 |
global index, query_engine
|
| 56 |
try:
|
| 57 |
if not file_objs:
|
| 58 |
return "Error: No files selected."
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
".png": ImageReader(),
|
| 69 |
}
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
#
|
| 95 |
-
# collection_name="your_collection_name",
|
| 96 |
-
# gpu_id=0, # Specify the GPU ID to use
|
| 97 |
-
# output_fields=["field1","field2"]
|
| 98 |
-
#)
|
| 99 |
-
|
| 100 |
-
vector_store = MilvusVectorStore(uri="./milvus_demo.db", dim=1024, overwrite=True,output_fields=[])
|
| 101 |
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
|
|
|
| 102 |
|
| 103 |
-
# Create
|
| 104 |
-
index = VectorStoreIndex.from_documents(
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
query_engine = index.as_query_engine()
|
| 108 |
-
return
|
| 109 |
-
except Exception as e:
|
| 110 |
-
return f"Error loading documents: {str(e)}"
|
| 111 |
|
| 112 |
-
|
| 113 |
# Function to handle chat interactions
|
| 114 |
-
def
|
| 115 |
-
global query_engine
|
| 116 |
if query_engine is None:
|
| 117 |
-
return history + [("Please upload a file first.",None)]
|
| 118 |
try:
|
| 119 |
-
#
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
except Exception as e:
|
| 124 |
-
|
| 125 |
|
| 126 |
# Function to stream responses
|
| 127 |
-
def stream_response(message,history):
|
| 128 |
global query_engine
|
| 129 |
if query_engine is None:
|
| 130 |
-
yield history + [("Please upload a file first.",None)]
|
| 131 |
return
|
| 132 |
|
| 133 |
try:
|
|
|
|
| 134 |
response = query_engine.query(message)
|
|
|
|
|
|
|
| 135 |
partial_response = ""
|
| 136 |
-
for text in
|
| 137 |
partial_response += text
|
| 138 |
-
yield history + [(message,partial_response)]
|
| 139 |
except Exception as e:
|
| 140 |
yield history + [(message, f"Error processing query: {str(e)}")]
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
| 168 |
|
| 169 |
# Launch the Gradio interface
|
| 170 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from llama_index import (
|
| 3 |
+
Settings,
|
| 4 |
+
SimpleDirectoryReader,
|
| 5 |
+
VectorStoreIndex,
|
| 6 |
+
ServiceContext,
|
| 7 |
+
LLMPredictor,
|
| 8 |
+
)
|
| 9 |
+
from llama_index.storage.storage_context import StorageContext
|
| 10 |
+
from llama_index.vector_stores.milvus import MilvusVectorStore
|
| 11 |
from llama_index.llms.nvidia import NVIDIA
|
| 12 |
+
from llama_index.embeddings.nvidia import NVIDIAEmbedding
|
| 13 |
+
from llama_index.postprocessor import NvidiaNeMoRerank
|
| 14 |
+
from llama_index.readers import (
|
| 15 |
+
Reader,
|
| 16 |
+
# SimpleWebPageReader,
|
| 17 |
+
HTMLTagReader,
|
| 18 |
DocxReader,
|
| 19 |
PDFReader,
|
| 20 |
+
PresentationReader,
|
| 21 |
ImageReader,
|
|
|
|
| 22 |
CSVReader,
|
| 23 |
)
|
| 24 |
|
| 25 |
+
# Initialize LLM, embedding model, and text splitter
|
| 26 |
+
Settings.llm = NVIDIA(model="meta/llama-3.1-8b-instruct")
|
| 27 |
Settings.embed_model = NVIDIAEmbedding(model="NV-Embed-QA", truncate="END")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
Settings.text_splitter = SentenceSplitter(chunk_size=400)
|
| 29 |
+
Settings.service_context = ServiceContext.from_defaults(
|
| 30 |
+
llm=Settings.llm, embed_model=Settings.embed_model, text_splitter=Settings.text_splitter
|
| 31 |
+
)
|
| 32 |
|
| 33 |
# Import Nemo modules
|
| 34 |
|
|
|
|
| 38 |
config = RailsConfig.from_path("./Config")
|
| 39 |
rails = LLMRails(config)
|
| 40 |
|
| 41 |
+
|
| 42 |
# Initialize global variables for the index and query engine
|
| 43 |
index = None
|
| 44 |
query_engine = None
|
|
|
|
| 50 |
return [file_obj.name for file_obj in file_objs]
|
| 51 |
|
| 52 |
# Function to load documents and create the index
|
| 53 |
+
def load_documents(file_objs, url=None):
|
| 54 |
global index, query_engine
|
| 55 |
try:
|
| 56 |
if not file_objs:
|
| 57 |
return "Error: No files selected."
|
| 58 |
+
|
| 59 |
+
# Create reader classes for different file types
|
| 60 |
+
reader_classes = {
|
| 61 |
+
".pdf": PDFReader,
|
| 62 |
+
".docx": DocxReader,
|
| 63 |
+
".pptx": PresentationReader,
|
| 64 |
+
".csv": CSVReader,
|
| 65 |
+
".jpg": ImageReader,
|
| 66 |
+
".jpeg": ImageReader,
|
|
|
|
| 67 |
}
|
| 68 |
|
| 69 |
+
documents = []
|
| 70 |
+
for file in file_objs:
|
| 71 |
+
reader_class = reader_classes.get(file.name.lower()[-5:], Reader)
|
| 72 |
+
reader = reader_class()
|
| 73 |
+
documents.extend(reader.load_data(file))
|
| 74 |
+
|
| 75 |
+
if url:
|
| 76 |
+
reader = HTMLTagReader()
|
| 77 |
+
documents.extend(reader.load_data(urls=[url]))
|
| 78 |
+
|
| 79 |
+
if not documents:
|
| 80 |
+
return f"No documents found in the selected files."
|
| 81 |
+
|
| 82 |
+
# Create index from documents
|
| 83 |
+
def create_index(documents):
|
| 84 |
+
vector_store = MilvusVectorStore(
|
| 85 |
+
host="127.0.0.1",
|
| 86 |
+
port=19530,
|
| 87 |
+
dim=1024,
|
| 88 |
+
collection_name="vectorstore",
|
| 89 |
+
gpu_id=0, # Specify the GPU ID to use
|
| 90 |
+
output_fields=["field1","field2"]
|
| 91 |
+
)
|
| 92 |
+
# vector_store = MilvusVectorStore(uri="./milvus_demo.db", dim=1024, overwrite=True) #For CPU only vector store
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
| 94 |
+
return VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
| 95 |
|
| 96 |
+
# Create index and query engine
|
| 97 |
+
index = VectorStoreIndex.from_documents(
|
| 98 |
+
documents, service_context=service_context
|
| 99 |
+
)
|
| 100 |
+
query_engine = index.as_query_engine(similarity_top_k=20, streaming=True)
|
| 101 |
+
return "Documents loaded successfully!"
|
|
|
|
|
|
|
| 102 |
|
|
|
|
| 103 |
# Function to handle chat interactions
|
| 104 |
+
def moderated_chat(message, history):
|
| 105 |
+
global query_engine, rails
|
| 106 |
if query_engine is None:
|
| 107 |
+
return history + [("Please upload a file first.", None)]
|
| 108 |
try:
|
| 109 |
+
# Get response from query engine
|
| 110 |
+
response = query_engine.query(message)
|
| 111 |
+
# Provide relevant context to guardrails
|
| 112 |
+
validated_response = rails.generate(context={"history": history, "response": response.response, "message": message}, prompt=message)
|
| 113 |
+
history.append((message, validated_response.generated_text))
|
| 114 |
+
yield history
|
| 115 |
except Exception as e:
|
| 116 |
+
yield history + [(message, f"An error occurred: {str(e)}")]
|
| 117 |
|
| 118 |
# Function to stream responses
|
| 119 |
+
def stream_response(message, history):
|
| 120 |
global query_engine
|
| 121 |
if query_engine is None:
|
| 122 |
+
yield history + [("Please upload a file first.", None)]
|
| 123 |
return
|
| 124 |
|
| 125 |
try:
|
| 126 |
+
# Get response from query engine
|
| 127 |
response = query_engine.query(message)
|
| 128 |
+
# Provide relevant context to guardrails
|
| 129 |
+
validated_response = rails.generate(context={"history": history, "response": response.response, "message": message}, prompt=message)
|
| 130 |
partial_response = ""
|
| 131 |
+
for text in validated_response.response_gen:
|
| 132 |
partial_response += text
|
| 133 |
+
yield history + [(message, partial_response)]
|
| 134 |
except Exception as e:
|
| 135 |
yield history + [(message, f"Error processing query: {str(e)}")]
|
| 136 |
|
| 137 |
+
with gr.Blocks() as iface:
|
| 138 |
+
gr.Markdown("# Multi-document RAG Chatbot 🦀 ") # Title using Markdown
|
| 139 |
+
gr.Markdown("Upload various documents or HTML URL for Q&A")
|
| 140 |
+
with gr.Row():
|
| 141 |
+
with gr.Column():
|
| 142 |
+
file_input = gr.File(
|
| 143 |
+
file_count="multiple", label="Upload documents")
|
| 144 |
+
with gr.Column():
|
| 145 |
+
url_input = gr.Textbox(label="Enter URL")
|
| 146 |
+
with gr.Row():
|
| 147 |
+
load_button = gr.Button("Load Documents & URL")
|
| 148 |
+
status_output = gr.Textbox(label="Status")
|
| 149 |
+
|
| 150 |
+
load_button.click(
|
| 151 |
+
fn=load_documents,
|
| 152 |
+
inputs=[file_input, url_input],
|
| 153 |
+
outputs=status_output,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
with gr.Row():
|
| 157 |
+
chatbot = gr.Chatbot()
|
| 158 |
+
msg = gr.Textbox(label="Enter your question")
|
| 159 |
+
msg.submit(stream_response, inputs=[msg, chatbot], outputs=[chatbot])
|
| 160 |
+
clear_button = gr.Button("Clear")
|
| 161 |
+
clear_button.click(lambda: None, None, chatbot, queue=False)
|
|
|
|
| 162 |
|
| 163 |
# Launch the Gradio interface
|
| 164 |
if __name__ == "__main__":
|