forked from microsoft/UFO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml_loader.py
118 lines (88 loc) · 3.16 KB
/
xml_loader.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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from . import basic
import os
from langchain_community.document_loaders import UnstructuredXMLLoader
from langchain.docstore.document import Document
import xml.etree.ElementTree as ET
class XMLLoader(basic.BasicDocumentLoader):
"""
Class to load XML documents.
"""
def __init__(self, directory: str = None):
"""
Create a new XMLLoader.
"""
super().__init__()
self.extensions = ".xml"
self.directory = directory
def get_microsoft_document_metadata(self, file: str):
"""
Get the metadata for the given file.
:param file: The file to get the metadata for.
:return: The metadata for the given file.
"""
if not os.path.exists(file):
return {'title': os.path.basename(file), 'summary': os.path.basename(file)}
tree = ET.parse(file)
root = tree.getroot()
# Extracting title
if root.find('title') is not None:
title = root.find('title').text
else:
title = None
# Extracting content summary
if root.find('Content-Summary') is not None:
summary = root.find('Content-Summary').attrib['value']
else:
summary = None
return {'title': title, 'summary': summary}
def get_microsoft_document_text(self, file: str):
"""
Get the text for the given file.
:param file: The file to get the text for.
:return: The text for the given file.
"""
try:
doc_text = UnstructuredXMLLoader(file).load()[0].page_content
except:
doc_text = None
return doc_text
def construct_document_list(self):
"""
Construct a list of documents.
:return: The list of documents.
"""
documents = []
for file in self.load_file_name():
text = self.get_microsoft_document_text(file)
metadata = self.get_microsoft_document_metadata(file + ".meta")
title = metadata["title"]
summary = metadata["summary"]
document = {
'title': title,
'summary': summary,
'text':text
}
documents.append(document)
return documents
def construct_document(self):
"""
Construct a langchain document list.
:return: The langchain document list.
"""
documents = []
for file in self.load_file_name():
text = self.get_microsoft_document_text(file)
metadata = self.get_microsoft_document_metadata(file + ".meta")
title = metadata["title"]
summary = metadata["summary"]
page_content = """{title} - {summary}""".format(title=title, summary=summary)
metadata = {
'title': title,
'summary': summary,
'text':text
}
document = Document(page_content=page_content, metadata=metadata)
documents.append(document)
return documents