Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
working test rag
Perinim15b468473b75
diff --git a/examples/custom_graph_example.py b/examples/custom_graph_example.pyindex e65e3eeb..1c12c124 100644--- a/examples/custom_graph_example.py+++ b/examples/custom_graph_example.py@@ -6,7 +6,7 @@ import osfrom dotenv import load_dotenvfrom scrapegraphai.models import OpenAIfrom scrapegraphai.graphs import BaseGraph-from scrapegraphai.nodes import FetchHTMLNode, ParseHTMLNode, GenerateAnswerNode+from scrapegraphai.nodes import FetchHTMLNode, ParseHTMLNode, GenerateAnswerNode, TestRagNodeload_dotenv()@@ -22,7 +22,7 @@ model = OpenAI(llm_config)# define the nodes for the graphfetch_html_node = FetchHTMLNode("fetch_html")-parse_document_node = ParseHTMLNode("parse_document")+parse_document_node = TestRagNode(model, "parse_document")generate_answer_node = GenerateAnswerNode(model, "generate_answer")# create the graph@@ -40,7 +40,7 @@ graph = BaseGraph()# execute the graph-inputs = {"user_input": "What is the title of the page?", "url": "https://example.com"}+inputs = {"user_input": "Dammi i cinema presenti a Roma", "url": "https://www.mymovies.it/cinema/roma/"}result = graph.execute(inputs)# get the answer from the resultdiff --git a/examples/example_multichunks.py b/examples/example_multichunks.pyindex 3790aa96..443201f9 100644--- a/examples/example_multichunks.py+++ b/examples/example_multichunks.py@@ -3,27 +3,81 @@ from langchain_community.document_loaders import AsyncHtmlLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import Chroma+from langchain.docstore.document import Document+from langchain_openai import OpenAIEmbeddings+import os+from dotenv import load_dotenv+from langchain.retrievers import ContextualCompressionRetriever+from langchain.retrievers.document_compressors import LLMChainExtractor+from langchain.retrievers.document_compressors import EmbeddingsFilter+from langchain.retrievers.document_compressors import DocumentCompressorPipeline+from langchain_community.document_transformers import EmbeddingsRedundantFilter+from langchain_openai import OpenAI+from langchain_community.vectorstores import FAISS-chroma = Chroma('test',HuggingFaceEmbeddings())+load_dotenv()++# Helper function for printing docs++def pretty_print_docs(docs):+ print(+ f"\n{'-' * 100}\n".join(+ [f"Document {i+1}:\n\n" + d.page_content for i, d in enumerate(docs)]+ )+ )++# Define the configuration for the language model+openai_key = os.getenv("OPENAI_APIKEY")++# chroma = Chroma('test', OpenAIEmbeddings(api_key=openai_key))# html2text 2020.1.16-urls = ["https://www.mymovies.it/cinema/roma",'https://lurenss.github.io']+urls = ["https://www.mymovies.it/cinema/roma"]loader = AsyncHtmlLoader(urls)docs = loader.load()-text_splitter = RecursiveCharacterTextSplitter(+text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=4000,- chunk_overlap=100,- length_function=len,- is_separator_regex=False,+ chunk_overlap=200,)docs_transformed = Html2TextTransformer().transform_documents(docs)-list_texts = [] # is a list of lists, [i][j] where i is the website and j is the chunk-for doc in docs_transformed:- doc.page_content = doc.page_content.replace('\n','')- chroma.add_documents(text_splitter.create_documents([doc.page_content]))- #list_texts.append(text_splitter.create_documents([doc.page_content]))+doc = docs[0]++chunks = text_splitter.split_text(doc.page_content)++chunked_docs = []++for i, chunk in enumerate(chunks):+ doc = Document(+ page_content=chunk,+ metadata={+ "chunk": i + 1,+ },+ )+ chunked_docs.append(doc)++retriever = FAISS.from_documents(chunked_docs, OpenAIEmbeddings(api_key=openai_key)).as_retriever()++embeddings = OpenAIEmbeddings(api_key=openai_key) # could be any embedding of your choice+embeddings_filter = EmbeddingsFilter(embeddings=embeddings)+redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings)+relevant_filter = EmbeddingsFilter(embeddings=embeddings) # similarity_threshold could be set, now k=20+pipeline_compressor = DocumentCompressorPipeline(+ transformers=[redundant_filter, relevant_filter]+)++compression_retriever = ContextualCompressionRetriever(+ base_compressor=pipeline_compressor, base_retriever=retriever+)++compressed_docs = compression_retriever.get_relevant_documents(+ "Dammi i nomi dei cinema in provincia di Roma"+)++pretty_print_docs(compressed_docs)++# db = Chroma.from_documents(chunked_docs, OpenAIEmbeddings(api_key=openai_key))+# chroma.similarity_search_with_relevance_scores('Find the cinema name', 10)-chroma.similarity_search_with_relevance_scores('Find the cinema name', 10)diff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.pyindex a1adb974..2898fa16 100644--- a/scrapegraphai/nodes/__init__.py+++ b/scrapegraphai/nodes/__init__.py@@ -6,5 +6,6 @@ from .conditional_node import ConditionalNodefrom .get_probable_tags_node import GetProbableTagsNodefrom .generate_answer_node import GenerateAnswerNodefrom .parse_html_node import ParseHTMLNode+from .test_rag_node import TestRagNodefrom .text_to_speech_node import TextToSpeechNodefrom .image_to_text_node import ImageToTextNodediff --git a/scrapegraphai/nodes/generate_answer_node.py b/scrapegraphai/nodes/generate_answer_node.pyindex 5c83f54c..62af266f 100644--- a/scrapegraphai/nodes/generate_answer_node.py+++ b/scrapegraphai/nodes/generate_answer_node.py@@ -69,7 +69,7 @@ class GenerateAnswerNode(BaseNode):relevant_chunks = state.get("relevant_chunks", None)if relevant_chunks:- context = relevant_chunks+ context = relevant_chunks[0].page_contentelif parsed_document:context = parsed_documentelse:diff --git a/scrapegraphai/nodes/test_rag_node.py b/scrapegraphai/nodes/test_rag_node.pynew file mode 100644index 00000000..6ad86b1c--- /dev/null+++ b/scrapegraphai/nodes/test_rag_node.py@@ -0,0 +1,110 @@+"""+Module for parsing the HTML node+"""+# from langchain_community.document_transformers import BeautifulSoupTransformer+from langchain.text_splitter import RecursiveCharacterTextSplitter+from langchain_community.document_transformers import Html2TextTransformer+from langchain.docstore.document import Document+from langchain_community.vectorstores import FAISS+from langchain_openai import OpenAIEmbeddings+from langchain.retrievers import ContextualCompressionRetriever+from langchain.retrievers.document_compressors import EmbeddingsFilter+from langchain.retrievers.document_compressors import DocumentCompressorPipeline+from langchain_community.document_transformers import EmbeddingsRedundantFilter++from .base_node import BaseNode+++class TestRagNode(BaseNode):+ """+ A node responsible for parsing HTML content from a document using specified tags.+ It uses BeautifulSoupTransformer for parsing, providing flexibility in extracting+ specific parts of an HTML document based on the tags provided in the state.++ This node enhances the scraping workflow by allowing for targeted extraction of+ content, thereby optimizing the processing of large HTML documents.++ Attributes:+ node_name (str): The unique identifier name for the node, defaulting to "ParseHTMLNode".+ node_type (str): The type of the node, set to "node" indicating a standard operational node.++ Args:+ node_name (str, optional): The unique identifier name for the node.+ Defaults to "ParseHTMLNode".++ Methods:+ execute(state): Parses the HTML document contained within the state using+ the specified tags, if provided, and updates the state with the parsed content.+ """++ def __init__(self, llm, node_name="TestRagNode"):+ """+ Initializes the ParseHTMLNode with a node name.+ """+ super().__init__(node_name, "node")+ self.llm = llm++ def execute(self, state):+ """+ Executes the node's logic to parse the HTML document based on specified tags.+ If tags are provided in the state, the document is parsed accordingly; otherwise,+ the document remains unchanged. The method updates the state with either the original+ or parsed document under the 'parsed_document' key.++ Args:+ state (dict): The current state of the graph, expected to contain+ 'document' within 'keys', and optionally 'tags' for targeted parsing.++ Returns:+ dict: The updated state with the 'parsed_document' key containing the parsed content,+ if tags were provided, or the original document otherwise.++ Raises:+ KeyError: If 'document' is not found in the state, indicating that the necessary+ information for parsing is missing.+ """++ print("---PARSE HTML DOCUMENT---")+ try:+ user_input = state["user_input"]+ document = state["document"]+ except KeyError as e:+ print(f"Error: {e} not found in state.")+ raise++ text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(+ chunk_size=4000,+ chunk_overlap=200,+ )++ docs_transformed = Html2TextTransformer().transform_documents(document)[0]++ chunks = text_splitter.split_text(docs_transformed.page_content)+ chunked_docs = []++ for i, chunk in enumerate(chunks):+ doc = Document(+ page_content=chunk,+ metadata={+ "chunk": i + 1,+ },+ )+ chunked_docs.append(doc)++ openai_key = self.llm.openai_api_key+ retriever = FAISS.from_documents(chunked_docs, OpenAIEmbeddings(api_key=openai_key)).as_retriever()+ embeddings = OpenAIEmbeddings(api_key=openai_key) # could be any embedding of your choice+ redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings)+ relevant_filter = EmbeddingsFilter(embeddings=embeddings) # similarity_threshold could be set, now k=20+ pipeline_compressor = DocumentCompressorPipeline(+ transformers=[redundant_filter, relevant_filter]+ )++ compression_retriever = ContextualCompressionRetriever(+ base_compressor=pipeline_compressor, base_retriever=retriever+ )++ compressed_docs = compression_retriever.get_relevant_documents(user_input)+ print("Documents compressed and stored in a vector database.")+ state.update({"relevant_chunks": compressed_docs})+ return state