MEOW commited on
Commit
85479a5
·
unverified ·
1 Parent(s): eb0a5a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -111
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 openai import OpenAI
11
-
12
- # Set the environment
13
-
14
- from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex, StorageContext
 
 
 
 
15
  from llama_index.llms.nvidia import NVIDIA
16
- Settings.llm = NVIDIA(model="meta/llama-3.1-8b-instruct")
17
-
18
- from llama_index.readers.file import (
 
 
 
19
  DocxReader,
20
  PDFReader,
21
- HTMLTagReader,
22
  ImageReader,
23
- PptxReader,
24
  CSVReader,
25
  )
26
 
27
- from llama_index.embeddings.nvidia import NVIDIAEmbedding
 
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
- all_texts = [] # Accumulate text from all files
61
- file_extractor = {
62
- ".pdf": PDFReader(),
63
- ".csv": CSVReader(),
64
- ".html": HTMLTagReader(),
65
- ".pptx": PptxReader(),
66
- ".docx": DocxReader(),
67
- ".jpg": ImageReader(),
68
- ".png": ImageReader(),
69
  }
70
 
71
- for file_obj in file_objs: # Iterate through file objects # to process correct file type
72
- file_extension = os.path.splitext(file_obj.name)[1].lower()
73
- if file_extension in file_extractor:
74
- extractor = file_extractor[file_extension]
75
- extracted_text = extractor.extract(file_obj)
76
- all_texts.extend(extracted_text) # Add extracted text to the list
77
- else:
78
- print(f"Warning: Unsupported file type: {file_extension}")
79
-
80
- # file_paths = get_files_from_input(file_objs)
81
- #documents = []
82
- #for file_path in file_paths:
83
- # directory = os.path.dirname(file_path)
84
- # documents.extend(SimpleDirectoryReader(input_files=[file_path]).load_data())
85
-
86
- #if not documents:
87
- # return f"No documents found in the selected files."
88
-
89
-
90
- # Create a Milvus vector store and storage context
91
- # vector_store = MilvusVectorStore(
92
- # host="127.0.0.1",
93
- # port=19530,
94
- # dim=1024,
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 the index from the documents
104
- index = VectorStoreIndex.from_documents(all_texts, embedding=embeddings) # Create index inside the function after documents are loaded
105
-
106
- # Create the query engine after the index is created
107
- query_engine = index.as_query_engine()
108
- return f"Successfully loaded {len(documents)} documents from {len(file_paths)} files."
109
- except Exception as e:
110
- return f"Error loading documents: {str(e)}"
111
 
112
-
113
  # Function to handle chat interactions
114
- def chat(message,history):
115
- global query_engine
116
  if query_engine is None:
117
- return history + [("Please upload a file first.",None)]
118
  try:
119
- #modification for nemo guardrails ( next three rows)
120
- user_message = {"role":"user","content":message}
121
- response = rails.generate(messages=[user_message])
122
- return history + [(message,response['content'])]
 
 
123
  except Exception as e:
124
- return history + [(message,f"Error processing query: {str(e)}")]
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 response.response_gen:
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
- # Create the Gradio interface
143
- def process_multimodal_uploads(image, text, file):
144
- # This function would process the inputs as needed. Here's just a placeholder
145
- # response reflecting what's been uploaded.
146
- return f"Processed: Image: {'Yes' if image else 'No'}, Text: {text}, File: {file.name if file else 'No file'}"
147
-
148
- with gr.Blocks() as demo:
149
- gr.Markdown("# Multimodal RAG Chatbot 🦀 ")
150
- gr.Markdown("Upload **at least** one document, optional to input HTML URL before Q&A")
151
-
152
- with gr.Row():
153
- with gr.Column(): # Group file_uploader and url_input on the left
154
- file_uploader = gr.File(label="Select files to upload", file_count="multiple")
155
- url_input = gr.Textbox(label="🔗 Paste a URL (optional)", placeholder="Enter a HTML URL here")
156
- load_btn = gr.Button("Upload input (PDF,CSV,Docx,Pptx,JPG,PNG,website)") # Place load_btn on the right
157
-
158
- load_output = gr.Textbox(label="Load Status")
159
-
160
- chatbot = gr.Chatbot()
161
- msg = gr.Textbox(label="Enter your question",interactive=True)
162
- clear = gr.Button("Clear")
163
-
164
- # Set up event handler (Event handlers should be defined within the 'with gr.Blocks() as demo:' block)
165
- load_btn.click(process_multimodal_uploads,inputs=[file_uploader, url_input], outputs=[load_output])
166
- msg.submit(stream_response, inputs=[msg, chatbot], outputs=[chatbot]) # Use submit button instead of msg
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__":