-
Notifications
You must be signed in to change notification settings - Fork 304
/
01_Ingest_Data.py
247 lines (224 loc) · 8.86 KB
/
01_Ingest_Data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import io
from os import path
from bs4 import BeautifulSoup
import streamlit as st
from typing import Optional
import mimetypes
import traceback
import chardet
from datetime import datetime, timedelta
import requests
from azure.identity import DefaultAzureCredential
from azure.storage.blob import (
BlobServiceClient,
generate_blob_sas,
ContentSettings,
UserDelegationKey,
)
import urllib.parse
import sys
import logging
from batch.utilities.helpers.ConfigHelper import ConfigHelper
from batch.utilities.helpers.EnvHelper import EnvHelper
sys.path.append(path.join(path.dirname(__file__), ".."))
env_helper: EnvHelper = EnvHelper()
logger = logging.getLogger(__name__)
st.set_page_config(
page_title="Ingest Data",
page_icon=path.join("images", "favicon.ico"),
layout="wide",
menu_items=None,
)
mod_page_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
</style>
"""
st.markdown(mod_page_style, unsafe_allow_html=True)
def request_user_delegation_key(
blob_service_client: BlobServiceClient,
) -> UserDelegationKey:
# Get a user delegation key that's valid for 1 day
delegation_key_start_time = datetime.utcnow()
delegation_key_expiry_time = delegation_key_start_time + timedelta(days=1)
user_delegation_key = blob_service_client.get_user_delegation_key(
key_start_time=delegation_key_start_time,
key_expiry_time=delegation_key_expiry_time,
)
return user_delegation_key
def remote_convert_files_and_add_embeddings():
backend_url = urllib.parse.urljoin(
env_helper.BACKEND_URL, "/api/BatchStartProcessing"
)
params = {}
if env_helper.FUNCTION_KEY is not None:
params["code"] = env_helper.FUNCTION_KEY
params["clientId"] = "clientKey"
try:
response = requests.post(backend_url, params=params)
if response.status_code == 200:
st.success(
f"{response.text}\nPlease note this is an asynchronous process and may take a few minutes to complete."
)
else:
st.error(f"Error: {response.text}")
except Exception:
st.error(traceback.format_exc())
def add_urls():
urls = st.session_state["urls"].split("\n")
if env_helper.AZURE_SEARCH_USE_INTEGRATED_VECTORIZATION:
download_url_and_upload_to_blob(urls)
else:
add_url_embeddings(urls)
def download_url_and_upload_to_blob(urls: list[str]):
for url in urls:
try:
response = requests.get(url)
parsed_data = BeautifulSoup(response.content, "html.parser")
with io.BytesIO(parsed_data.get_text().encode("utf-8")) as stream:
upload_file(stream, url)
st.success(f"Url {url} added to knowledge base")
except Exception:
logger.error(traceback.format_exc())
st.error(f"Exception occurred while adding {url} to the knowledge base.")
def add_url_embeddings(urls: list[str]):
params = {}
if env_helper.FUNCTION_KEY is not None:
params["code"] = env_helper.FUNCTION_KEY
params["clientId"] = "clientKey"
for url in urls:
body = {"url": url}
backend_url = urllib.parse.urljoin(
env_helper.BACKEND_URL, "/api/AddURLEmbeddings"
)
r = requests.post(url=backend_url, params=params, json=body)
if not r.ok:
raise ValueError(f"Error {r.status_code}: {r.text}")
else:
st.success(f"Embeddings added successfully for {url}")
def upload_file(bytes_data: bytes, file_name: str, content_type: Optional[str] = None):
# Upload a new file
st.session_state["filename"] = file_name
if content_type is None:
content_type = mimetypes.MimeTypes().guess_type(file_name)[0]
charset = (
f"; charset={chardet.detect(bytes_data)['encoding']}"
if content_type == "text/plain"
else ""
)
content_type = content_type if content_type is not None else "text/plain"
account_name = env_helper.AZURE_BLOB_ACCOUNT_NAME
if env_helper.AZURE_AUTH_TYPE == "rbac":
credential = DefaultAzureCredential()
account_url = f"https://{account_name}.blob.core.windows.net/"
blob_service_client = BlobServiceClient(
account_url=account_url, credential=credential
)
user_delegation_key = request_user_delegation_key(
blob_service_client=blob_service_client
)
container_name = env_helper.AZURE_BLOB_CONTAINER_NAME
blob_client = blob_service_client.get_blob_client(
container=container_name, blob=file_name
)
blob_client.upload_blob(
bytes_data,
overwrite=True,
content_settings=ContentSettings(content_type=content_type + charset),
metadata={"title": file_name},
)
st.session_state["file_url"] = (
blob_client.url
+ "?"
+ generate_blob_sas(
account_name,
container_name,
file_name,
user_delegation_key=user_delegation_key,
permission="r",
expiry=datetime.utcnow() + timedelta(hours=3),
)
)
else:
account_key = env_helper.AZURE_BLOB_ACCOUNT_KEY
container_name = env_helper.AZURE_BLOB_CONTAINER_NAME
if account_name is None or account_key is None or container_name is None:
raise ValueError(
"Please provide values for AZURE_BLOB_ACCOUNT_NAME, AZURE_BLOB_ACCOUNT_KEY and AZURE_BLOB_CONTAINER_NAME"
)
connect_str = f"DefaultEndpointsProtocol=https;AccountName={account_name};AccountKey={account_key};EndpointSuffix=core.windows.net"
blob_service_client: BlobServiceClient = (
BlobServiceClient.from_connection_string(connect_str)
)
# Create a blob client using the local file name as the name for the blob
blob_client = blob_service_client.get_blob_client(
container=container_name, blob=file_name
)
# Upload the created file
blob_client.upload_blob(
bytes_data,
overwrite=True,
content_settings=ContentSettings(content_type=content_type + charset),
metadata={"title": file_name},
)
# Generate a SAS URL to the blob and return it
st.session_state["file_url"] = (
blob_client.url
+ "?"
+ generate_blob_sas(
account_name,
container_name,
file_name,
account_key=account_key,
permission="r",
expiry=datetime.utcnow() + timedelta(hours=3),
)
)
try:
with st.expander("Add documents in Batch", expanded=True):
config = ConfigHelper.get_active_config_or_default()
file_type = [
processor.document_type for processor in config.document_processors
]
uploaded_files = st.file_uploader(
"Upload a document to add it to the Azure Storage Account, compute embeddings and add them to the Azure AI Search index. Check your configuration for available document processors.",
type=file_type,
accept_multiple_files=True,
)
if uploaded_files is not None:
for up in uploaded_files:
# To read file as bytes:
bytes_data = up.getvalue()
if st.session_state.get("filename", "") != up.name:
# Upload a new file
upload_file(bytes_data, up.name)
if len(uploaded_files) > 0:
st.success(
f"{len(uploaded_files)} documents uploaded. Embeddings computation in progress. \nPlease note this is an asynchronous process and may take a few minutes to complete.\nYou can check for further details in the Azure Function logs."
)
col1, col2, col3 = st.columns([2, 1, 2])
with col3:
st.button(
"Reprocess all documents in the Azure Storage account",
on_click=remote_convert_files_and_add_embeddings,
)
with st.expander("Add URLs to the knowledge base", expanded=True):
col1, col2 = st.columns([3, 1])
with col1:
st.text_area(
"Add a URLs and than click on 'Compute Embeddings'",
placeholder="PLACE YOUR URLS HERE SEPARATED BY A NEW LINE",
height=100,
key="urls",
)
with col2:
st.selectbox(
"Embeddings models",
[env_helper.AZURE_OPENAI_EMBEDDING_MODEL],
disabled=True,
)
st.button("Process and ingest web pages", on_click=add_urls, key="add_url")
except Exception:
st.error(traceback.format_exc())