HTML-код, который я хочу проанализировать, выглядит следующим образом:
Код: Выделить всё
...
Examples
Create camera
Create a camera. Setting invalid_entity_id as the parent entity will make the camera to be created under the Ego entity, as it must be
camera_id = workspace.create_entity( anyverse_platform.WorkspaceEntityType.Camera, "New Camera", anyverse_platform.invalid_entity_id )
...
Скрипт на основе «неструктурированного» пакета, который я использую для разделения веб-страницы на фрагменты, выглядит следующим образом:
from unstructured.partition.html import partition_html
elements = partition_html(url=web_path)
element_dict = [el.to_dict() for el in elements]
output_path = os.path.join(output_dir_documentation, 'unstructured.json')
with open(output_path, 'w', encoding='utf-8') as output_file:
output_file.write(json.dumps(element_dict, indent=2))
Результат JSON, соответствующий приведенному выше фрагменту HTML:
{
"type": "Title",
"element_id": "e68ee04dff59551b7d1ae07a2f8a00dc",
"text": "Examples",
"metadata": {
"category_depth": 1,
"page_number": 1,
"languages": [
"eng"
],
"parent_id": "2253b75dcb33b928dae76ea64543f053",
"url": "https://anyverse.gitlab.io/anyversestudio/",
"filetype": "text/html"
}
},
{
"type": "Title",
"element_id": "534a8b35bbd7e5f0b6006d63efe887a9",
"text": "Create camera",
"metadata": {
"category_depth": 2,
"page_number": 1,
"languages": [
"eng"
],
"parent_id": "e68ee04dff59551b7d1ae07a2f8a00dc",
"url": "https://anyverse.gitlab.io/anyversestudio/",
"filetype": "text/html"
}
},
{
"type": "NarrativeText",
"element_id": "ae9df01594a27733b24d33ca212f2e66",
"text": "Create a camera. Setting invalid_entity_id as the parent entity will make the camera to be created under the Ego entity, as it must be",
"metadata": {
"page_number": 1,
"languages": [
"eng"
],
"parent_id": "534a8b35bbd7e5f0b6006d63efe887a9",
"url": "https://anyverse.gitlab.io/anyversestudio/",
"filetype": "text/html"
}
},
{
"type": "Title",
"element_id": "ec7fe9ae1c7f315580886ee99e826f3c",
"text": "Add resource to workspace",
"metadata": {
"category_depth": 2,
"page_number": 2,
"languages": [
"eng"
],
"parent_id": "e68ee04dff59551b7d1ae07a2f8a00dc",
"url": "https://anyverse.gitlab.io/anyversestudio/",
"filetype": "text/html"
}
},
Как видите, текст кода Python отсутствует.
Я также попробовал для этого langchain:
from langchain_text_splitters import HTMLHeaderTextSplitter
splitter = HTMLHeaderTextSplitter(
headers_to_split_on=[
("h1","Header1"),
("h2","Header2"),
("h3","Header3"),
]
)
chunks = splitter.split_text_from_url(web_path)
for index,chunk in enumerate(chunks):
output_path = os.path.join(output_dir_documentation, f'{index}.txt')
with open(output_path,"w",encoding="utf-8") as f:
f.write(str(chunk))
Соответствующий фрагмент заголовка «Создать камеру»:
page_content='Create a camera. Setting invalid_entity_id as the parent entity will make the camera to be created under the Ego entity, as it must be' metadata={'Header1': 'Scripting', 'Header2': 'Examples', 'Header3': 'Create camera'}
Текст из HTML-тега pre/code не отображается. Конечно, я проверил все сгенерированные фрагменты веб-страницы, и в них нет текста под тегами pre/code.
Чего мне здесь не хватает? Как я могу настроить раздел part_html и/или HTMLHeaderTextSplitter, чтобы получить текст под HTML-тегами pre/code?
ПРИМЕЧАНИЕ. Я обнаружил, что с помощью BeautifulSoup я могу получить недостающий текст из тегов «pre», но это слишком усложняет разбиение на фрагменты, потому что мне просто нужен заголовок (h1, h2 и т. д.) в качестве условия разбивки. Сначала разбивать на части часть без кода, а затем извлекать часть кода, чтобы окончательно объединить обе части, каким-то образом не кажется правильным подходом. Специализированные инструменты, такие как langchain и неструктурированные, должны иметь возможность обрабатывать эти HTML-теги до и/или кода.
Код BeautifulSoup:
import requests
data = requests.get(web_path)
from bs4 import BeautifulSoup
soup = BeautifulSoup(data.text, 'html.parser')
content = soup.find_all("pre")
Подробнее здесь: https://stackoverflow.com/questions/785 ... -and-or-co
Мобильная версия