Baweja commited on
Commit
6ad6aab
·
verified ·
1 Parent(s): 0623e09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -17
app.py CHANGED
@@ -1,20 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
@@ -25,19 +146,11 @@ def respond(
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
@@ -60,4 +173,4 @@ demo = gr.ChatInterface(
60
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
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()
64
+
65
+
66
+
67
  import gradio as gr
68
  from huggingface_hub import InferenceClient
69
+ import torch
70
+ from transformers import RagRetriever, RagSequenceForGeneration, AutoTokenizer
71
 
72
  """
73
  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
74
  """
75
+
76
+ def strip_title(title):
77
+ if title.startswith('"'):
78
+ title = title[1:]
79
+ if title.endswith('"'):
80
+ title = title[:-1]
81
+ return title
82
+
83
+ def retrieved_info(rag_model, query):
84
+ # Tokenize query
85
+ retriever_input_ids = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
86
+ [query],
87
+ return_tensors="pt",
88
+ padding=True,
89
+ truncation=True,
90
+ )["input_ids"].to(device)
91
+
92
+ # Retrieve documents
93
+ question_enc_outputs = rag_model.rag.question_encoder(retriever_input_ids)
94
+ question_enc_pool_output = question_enc_outputs[0]
95
+
96
+ result = rag_model.retriever(
97
+ retriever_input_ids,
98
+ question_enc_pool_output.cpu().detach().to(torch.float32).numpy(),
99
+ prefix=rag_model.rag.generator.config.prefix,
100
+ n_docs=rag_model.config.n_docs,
101
+ return_tensors="pt",
102
+ )
103
+
104
+ # Display retrieved documents including URLs
105
+ all_docs = rag_model.retriever.index.get_doc_dicts(result.doc_ids)
106
+ retrieved_context = []
107
+ for docs in all_docs:
108
+ titles = [strip_title(title) for title in docs["title"]]
109
+ texts = docs["text"]
110
+ for title, text in zip(titles, texts):
111
+ #print(f"Title: {title}")
112
+ #print(f"Context: {text}")
113
+ retrieved_context.append(f"{title}: {text}")
114
+
115
+ answer = retrieved_context
116
+
117
+
118
 
119
 
120
  def respond(
121
  message,
122
  history: list[tuple[str, str]],
123
  system_message,
 
 
 
124
  ):
125
+ # Load model
126
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
127
+
128
+ dataset_path = "/IndexedDataFiles/my_knowledge_dataset"
129
+ index_path = "/IndexedDataFiles/my_knowledge_dataset_hnsw_index.faiss"
130
+
131
+ tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
132
+ retriever = RagRetriever.from_pretrained("facebook/rag-sequence-nq", index_name="custom",
133
+ passages_path = dataset_path,
134
+ index_path = index_path,
135
+ n_docs = 1)
136
+ rag_model = RagSequenceForGeneration.from_pretrained('facebook/rag-sequence-nq', retriever=retriever)
137
+ rag_model.retriever.init_retrieval()
138
+ rag_model.to(device)
139
  messages = [{"role": "system", "content": system_message}]
140
 
141
  for val in history:
 
146
 
147
  messages.append({"role": "user", "content": message})
148
 
149
+ #response = ""
150
+
151
+ response = retrieved_info(rag_model, message)
 
 
 
 
 
 
 
152
 
153
+ yield response
 
154
 
155
  """
156
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
 
173
 
174
 
175
  if __name__ == "__main__":
176
+ demo.launch()