taupirho commited on
Commit
bf82520
·
1 Parent(s): cc15362

Update space

Browse files
Files changed (2) hide show
  1. app.py +93 -56
  2. requirements.txt +8 -1
app.py CHANGED
@@ -1,63 +1,100 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  if __name__ == "__main__":
 
63
  demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import os
4
+ import groq
5
+ import warnings
6
+ import asyncio
7
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
8
+ from llama_index.llms.groq import Groq
9
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
10
 
11
+ # A warning may appear which doesn't
12
+ # affect the operation of the code
13
+ # Suppress it with this code
14
+ warnings.filterwarnings("ignore", message=".*clean_up_tokenization_spaces.*")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # Global variables
17
+ index = None
18
+ query_engine = None
19
 
20
+ # Initialize Groq LLM and ensure it is used
21
+ llm = Groq(model="mixtral-8x7b-32768")
22
+ Settings.llm = llm # Ensure Groq is the LLM being used
23
+
24
+ # Initialize our chosen embedding model
25
+ embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
26
+
27
+ # These are our RAG fucntions, called in response to user
28
+ # initiated events e.g clicking the Load Documents button
29
+ # on the GUI
30
+ #
31
+ def load_documents(file_objs):
32
+ global index, query_engine
33
+ try:
34
+ if not file_objs:
35
+ return "Error: No files selected."
36
+
37
+ documents = []
38
+ document_names = []
39
+ for file_obj in file_objs:
40
+ document_names.append(file_obj.name)
41
+ loaded_docs = SimpleDirectoryReader(input_files=[file_obj.name]).load_data()
42
+ documents.extend(loaded_docs)
43
+
44
+ if not documents:
45
+ return "No documents found in the selected files."
46
+
47
+ # Create index from documents using Groq LLM and HuggingFace Embeddings
48
+ index = VectorStoreIndex.from_documents(
49
+ documents,
50
+ llm=llm, # Ensure Groq is used here
51
+ embed_model=embed_model
52
+ )
53
+
54
+ # Create query engine
55
+ query_engine = index.as_query_engine()
56
+
57
+ return f"Successfully loaded {len(documents)} documents from the files: {', '.join(document_names)}"
58
+ except Exception as e:
59
+ return f"Error loading documents: {str(e)}"
60
+
61
+ async def perform_rag(query, history):
62
+ global query_engine
63
+ if query_engine is None:
64
+ return history + [("Please load documents first.", None)]
65
+ try:
66
+ response = await asyncio.to_thread(query_engine.query, query)
67
+ return history + [(query, str(response))]
68
+ except Exception as e:
69
+ return history + [(query, f"Error processing query: {str(e)}")]
70
+
71
+ def clear_all():
72
+ global index, query_engine
73
+ index = None
74
+ query_engine = None
75
+ return None, "", [], "" # Reset file input, load output, chatbot, and message input to default states
76
+
77
+
78
+ # Create the Gradio interface
79
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
80
+ gr.Markdown("# RAG Multi-file Chat Application")
81
+
82
+ with gr.Row():
83
+ file_input = gr.File(label="Select PDF files to load", file_count="multiple")
84
+ load_btn = gr.Button("Load Documents")
85
+
86
+ load_output = gr.Textbox(label="Load Status")
87
+
88
+ msg = gr.Textbox(label="Enter your question")
89
+ chatbot = gr.Chatbot()
90
+ clear = gr.Button("Clear")
91
+
92
+ # Set up event handlers
93
+ load_btn.click(load_documents, inputs=[file_input], outputs=[load_output])
94
+ msg.submit(perform_rag, inputs=[msg, chatbot], outputs=[chatbot])
95
+ clear.click(clear_all, outputs=[file_input, load_output, chatbot, msg], queue=False)
96
+
97
+ # Run the app
98
  if __name__ == "__main__":
99
+ demo.queue()
100
  demo.launch()
requirements.txt CHANGED
@@ -1 +1,8 @@
1
- huggingface_hub==0.22.2
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.22.2
2
+ gradio
3
+ groq
4
+ llama-index-llms-groq
5
+ llama_index
6
+ openpyxl
7
+ llama-index-embeddings-huggingface
8
+ doc2txt