anything-llm/collector/scripts/watch/convert/as_text.py

32 lines
1.1 KiB
Python
Raw Normal View History

2023-06-04 04:28:07 +02:00
import os
from slugify import slugify
from ..utils import guid, file_creation_time, write_to_server_documents, move_source
from ...utils import tokenize
# Process all text-related documents.
def as_text(**kwargs):
parent_dir = kwargs.get('directory', 'hotdir')
filename = kwargs.get('filename')
ext = kwargs.get('ext', '.txt')
remove = kwargs.get('remove_on_complete', False)
2023-06-04 04:28:07 +02:00
fullpath = f"{parent_dir}/{filename}{ext}"
content = open(fullpath).read()
print(f"-- Working {fullpath} --")
data = {
'id': guid(),
2023-06-04 04:28:07 +02:00
'url': "file://"+os.path.abspath(f"{parent_dir}/processed/{filename}{ext}"),
'title': f"{filename}{ext}",
'docAuthor': 'Unknown', # TODO: Find a better author
'description': 'Unknown', # TODO: Find a better description
'chunkSource': f"{filename}{ext}",
2023-06-04 04:28:07 +02:00
'published': file_creation_time(fullpath),
'wordCount': len(content),
'pageContent': content,
'token_count_estimate': len(tokenize(content))
}
2023-06-04 04:28:07 +02:00
write_to_server_documents(data, f"{slugify(filename)}-{data.get('id')}")
move_source(parent_dir, f"{filename}{ext}", remove=remove)
print(f"[SUCCESS]: {filename}{ext} converted & ready for embedding.\n")