This repository was archived by the owner on May 27, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 421
Expand file tree
/
Copy pathdata.py
More file actions
233 lines (212 loc) · 7.97 KB
/
data.py
File metadata and controls
233 lines (212 loc) · 7.97 KB
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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import asyncio
import hashlib
import os
import re
import traceback
from math import ceil
from typing import List
from azure.storage.blob.aio import ContainerClient
from fastapi import (
APIRouter,
Depends,
HTTPException,
UploadFile,
status,
)
from markitdown import MarkItDown, StreamInfo
from graphrag_app.logger.load_logger import load_pipeline_logger
from graphrag_app.typing.models import (
BaseResponse,
StorageNameList,
)
from graphrag_app.utils.common import (
check_cache,
create_cache,
delete_cosmos_container_item_if_exist,
delete_storage_container_if_exist,
get_blob_container_client,
get_cosmos_container_store_client,
sanitize_name,
subscription_key_check,
update_cache,
)
data_route = APIRouter(
prefix="/data",
tags=["Data Management"],
)
if os.getenv("KUBERNETES_SERVICE_HOST"):
data_route.dependencies.append(Depends(subscription_key_check))
@data_route.get(
"",
summary="Get list of data containers.",
response_model=StorageNameList,
responses={status.HTTP_200_OK: {"model": StorageNameList}},
)
async def get_all_data_containers(
container_store_client=Depends(get_cosmos_container_store_client),
):
"""
Retrieve a list of all data containers.
"""
items = []
try:
# container_store_client = get_cosmos_container_store_client()
for item in container_store_client.read_all_items():
if item["type"] == "data":
items.append(item["human_readable_name"])
except Exception as e:
reporter = load_pipeline_logger()
reporter.error(
message="Error getting list of blob containers.",
cause=e,
stack=traceback.format_exc(),
)
raise HTTPException(
status_code=500, detail="Error getting list of blob containers."
)
return StorageNameList(storage_name=items)
async def upload_file(
upload_file: UploadFile, container_client: ContainerClient, overwrite: bool = True
):
"""
Convert and upload a file to a specified blob container.
Returns a list of objects where each object will have one of the following types:
* Tuple[str, str] - a tuple of (filename, file_hash) for successful uploads
* Tuple[str, None] - a tuple of (filename, None) for failed uploads or
* None for skipped files
"""
filename = upload_file.filename
extension = os.path.splitext(filename)[1]
converted_filename = filename + ".txt"
converted_blob_client = container_client.get_blob_client(converted_filename)
with upload_file.file as file_stream:
try:
file_hash = hashlib.sha256(file_stream.read()).hexdigest()
if not await check_cache(file_hash, container_client):
# extract text from file using MarkItDown
md = MarkItDown()
stream_info = StreamInfo(
extension=extension,
)
file_stream._file.seek(0)
file_stream = file_stream._file
result = md.convert_stream(
stream=file_stream,
stream_info=stream_info,
)
# remove illegal unicode characters and upload to blob storage
cleaned_result = _clean_output(result.text_content)
await converted_blob_client.upload_blob(
cleaned_result, overwrite=overwrite
)
# return tuple of (filename, file_hash) to indicate success
return (filename, file_hash)
except Exception:
# if any exception occurs, return a tuple of (filename, None) to indicate conversion/upload failure
return (upload_file.filename, None)
def _clean_output(val: str, replacement: str = ""):
"""Removes unicode characters that are invalid XML characters (not valid for graphml files at least)."""
# fmt: off
_illegal_xml_chars_RE = re.compile(
"[\x00-\x08\x0b\x0c\x0e-\x1F\uD800-\uDFFF\uFFFE\uFFFF]"
)
# fmt: on
return _illegal_xml_chars_RE.sub(replacement, val)
@data_route.post(
"",
summary="Upload data to a data storage container",
response_model=BaseResponse,
responses={status.HTTP_201_CREATED: {"model": BaseResponse}},
)
async def upload_files(
files: List[UploadFile],
container_name: str,
sanitized_container_name: str = Depends(sanitize_name),
overwrite: bool = True,
):
"""
Create a Azure Storage container (if needed) and upload files. Multiple file types are supported, including pdf, powerpoint, word, excel, html, csv, json, xml, etc.
The complete set of supported file types can be found in the MarkItDown (https://github.com/microsoft/markitdown) library.
"""
try:
# create the initial cache if it doesn't exist
blob_container_client = await get_blob_container_client(
sanitized_container_name
)
await create_cache(blob_container_client)
# process file uploads in batches to avoid exceeding Azure Storage API limits
processing_errors = []
batch_size = 100
num_batches = ceil(len(files) / batch_size)
for i in range(num_batches):
batch_files = files[i * batch_size : (i + 1) * batch_size]
tasks = [
upload_file(file, blob_container_client, overwrite)
for file in batch_files
]
upload_results = await asyncio.gather(*tasks)
successful_uploads = [r for r in upload_results if r and r[1] is not None]
# update the file cache with successful uploads
await update_cache(successful_uploads, blob_container_client)
# collect failed uploads
failed_uploads = [r[0] for r in upload_results if r and r[1] is None]
processing_errors.extend(failed_uploads)
# update container-store entry in cosmosDB once upload process is successful
cosmos_container_store_client = get_cosmos_container_store_client()
cosmos_container_store_client.upsert_item({
"id": sanitized_container_name,
"human_readable_name": container_name,
"type": "data",
})
if len(processing_errors) > 0:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Error uploading files: {processing_errors}.",
)
return BaseResponse(status="Success.")
except Exception as e:
# import traceback
# traceback.print_exc()
logger = load_pipeline_logger()
logger.error(
message="Error uploading files.",
cause=e,
stack=traceback.format_exc(),
details={"files": processing_errors},
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error uploading files to container '{container_name}'.",
)
@data_route.delete(
"/{container_name}",
summary="Delete a data storage container",
response_model=BaseResponse,
responses={status.HTTP_200_OK: {"model": BaseResponse}},
)
async def delete_files(
container_name: str, sanitized_container_name: str = Depends(sanitize_name)
):
"""
Delete a specified data storage container.
"""
try:
delete_storage_container_if_exist(sanitized_container_name)
delete_cosmos_container_item_if_exist(
"container-store", sanitized_container_name
)
except Exception as e:
logger = load_pipeline_logger()
logger.error(
message=f"Error deleting container {container_name}.",
cause=e,
stack=traceback.format_exc(),
details={"Container": container_name},
)
raise HTTPException(
status_code=500,
detail=f"Error deleting container '{container_name}'.",
)
return BaseResponse(status="Success")