anything-llm/collector/scripts/link_utils.py

45 lines
1.8 KiB
Python
Raw Normal View History

import json, pyppeteer
2023-06-04 04:28:07 +02:00
from datetime import datetime
from .watch.utils import guid
2023-06-04 04:28:07 +02:00
from dotenv import load_dotenv
2023-11-15 01:41:39 +01:00
from .watch.utils import guid
from .utils import tokenize
from requests_html import AsyncHTMLSession
2023-06-04 04:28:07 +02:00
load_dotenv()
def normalize_url(url):
if(url.endswith('.web')):
return url
return f"{url}.web"
2023-06-04 04:28:07 +02:00
def append_meta(request, text, metadata_only = False):
meta = {
2023-11-15 01:41:39 +01:00
'id': guid(),
'url': normalize_url(request.url),
2023-06-04 04:28:07 +02:00
'title': request.html.find('title', first=True).text if len(request.html.find('title')) != 0 else '',
2023-11-15 01:41:39 +01:00
'docAuthor': 'N/A',
2023-06-04 04:28:07 +02:00
'description': request.html.find('meta[name="description"]', first=True).attrs.get('content') if request.html.find('meta[name="description"]', first=True) != None else '',
'docSource': 'web page',
'chunkSource': request.url,
2023-06-04 04:28:07 +02:00
'published':request.html.find('meta[property="article:published_time"]', first=True).attrs.get('content') if request.html.find('meta[property="article:published_time"]', first=True) != None else datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
'wordCount': len(text.split(' ')),
2023-11-15 01:41:39 +01:00
'pageContent': text,
'token_count_estimate':len(tokenize(text)),
2023-06-04 04:28:07 +02:00
}
return "Article JSON Metadata:\n"+json.dumps(meta)+"\n\n\nText Content:\n" + text if metadata_only == False else meta
class AsyncHTMLSessionFixed(AsyncHTMLSession):
"""
pip3 install websockets==6.0 --force-reinstall
"""
def __init__(self, **kwargs):
super(AsyncHTMLSessionFixed, self).__init__(**kwargs)
self.__browser_args = kwargs.get("browser_args", ["--no-sandbox"])
@property
async def browser(self):
if not hasattr(self, "_browser"):
self._browser = await pyppeteer.launch(ignoreHTTPSErrors=not(self.verify), headless=True, handleSIGINT=False, handleSIGTERM=False, handleSIGHUP=False, args=self.__browser_args)
return self._browser