Skip to content

Python scraper based on AI

refactoring of the code, add tests and examples

VinciGit0071bd53d254d5
diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml
index 154a8cb8..1cdd24f3 100644
--- a/.github/workflows/pylint.yml
+++ b/.github/workflows/pylint.yml
@@ -20,4 +20,4 @@ jobs:
pip install pylint
pip install -r requirements.txt
- name: Analysing the code with pylint
- run: pylint --disable=C0114,C0115,C0116 --exit-zero scrapegraphai/**/*.py scrapegraphai/*.py examples/*.py tests/*.py
\ No newline at end of file
+ run:pylint scrapegraphai/**/*.py scrapegraphai/*.py examples/*.py tests/**/*.py
\ No newline at end of file
diff --git a/README.md b/README.md
index 610cc875..6f232a91 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ Try out ScrapeGraphAI in your browser:
## 📖 Documentation
The documentation for ScrapeGraphAI can be found [here](https://scrapegraph-ai.readthedocs.io/en/latest/).
-Behind this there is also the docusaurus documentation [here]([https://scrapegraph-ai.readthedocs.io/en/latest/](https://scrapegraph-doc.onrender.com/)).
+Behind this there is also the docusaurus documentation [here](https://scrapegraph-doc.onrender.com/)).
## Setup the api keys
diff --git a/commit_and_push.sh b/commit_and_push.sh
index 3dc39810..ead77617 100755
--- a/commit_and_push.sh
+++ b/commit_and_push.sh
@@ -20,8 +20,7 @@ fi
commit_message="$1"
# Run Pylint on the specified Python files
-pylint scrapegraphai/**/*.py scrapegraphai/*.py examples/*.py tests/*.py
-
+pylint scrapegraphai/**/*.py scrapegraphai/*.py examples/*.py tests/**/*.py
#Maket the pull
git pull
diff --git a/examples/utils/convert_to_csv.example.py b/examples/utils/convert_to_csv.example.py
new file mode 100644
index 00000000..73f1efa9
--- /dev/null
+++ b/examples/utils/convert_to_csv.example.py
@@ -0,0 +1,39 @@
+"""
+Teest for convert_to_csv
+"""
+import os
+from scrapegraphai.utils.convert_to_csv import convert_to_csv
+
+
+def main():
+ """
+ Example usage of the convert_to_csv function.
+ """
+ # Example data
+ data = {
+ 'Name': ['John', 'Alice', 'Bob'],
+ 'Age': [30, 25, 35],
+ 'City': ['New York', 'San Francisco', 'Seattle']
+ }
+
+ # Example filename and position
+ filename = "example_data"
+ position = "./output"
+
+ try:
+ # Convert data to CSV and save
+ convert_to_csv(data, filename, position)
+ print(
+ f"Data saved successfully to {os.path.join(position, filename)}.csv")
+ except ValueError as ve:
+ print(f"ValueError: {ve}")
+ except FileNotFoundError as fnfe:
+ print(f"FileNotFoundError: {fnfe}")
+ except PermissionError as pe:
+ print(f"PermissionError: {pe}")
+ except Exception as e:
+ print(f"An unexpected error occurred: {e}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/utils/convert_to_json_example.py b/examples/utils/convert_to_json_example.py
new file mode 100644
index 00000000..3859107c
--- /dev/null
+++ b/examples/utils/convert_to_json_example.py
@@ -0,0 +1,28 @@
+"""
+Example of using convert_to_json function to save data in JSON format.
+"""
+import os
+from scrapegraphai.utils.convert_to_json import convert_to_json
+
+# Data to save in JSON format
+data_to_save = {
+ "name": "John Doe",
+ "age": 30,
+ "city": "New York"
+}
+
+FILENAME = "example_data"
+DIRECTORY = "data_output"
+
+try:
+ convert_to_json(data_to_save, FILENAME, DIRECTORY)
+ print(
+ f"Data has been successfully saved to {os.path.join(DIRECTORY, FILENAME)}.json")
+except ValueError as value_error:
+ print(value_error)
+except FileNotFoundError as file_not_found_error:
+ print(file_not_found_error)
+except PermissionError as permission_error:
+ print(permission_error)
+except Exception as exception:
+ print(f"An error occurred: {exception}")
diff --git a/examples/utils/remover_example.py b/examples/utils/remover_example.py
new file mode 100644
index 00000000..dbdca118
--- /dev/null
+++ b/examples/utils/remover_example.py
@@ -0,0 +1,21 @@
+"""
+Example of the remover method
+"""
+from scrapegraphai.utils.remover import remover
+
+HTML_CONTENT = """
+<html>
+<head>
+ <title>Test Page</title>
+</head>
+<body>
+ <h1>This is a Test</h1>
+ <p>Hello, World!</p>
+ <script>alert("This is a script");</script>
+</body>
+</html>
+"""
+
+parsed_content = remover(HTML_CONTENT)
+
+print(parsed_content)
diff --git a/examples/utils/save_audio_from_bytes_example.py b/examples/utils/save_audio_from_bytes_example.py
new file mode 100644
index 00000000..c915aad6
--- /dev/null
+++ b/examples/utils/save_audio_from_bytes_example.py
@@ -0,0 +1,10 @@
+"""
+Example for th e file save_audio_from_bytes
+"""
+from scrapegraphai.utils.save_audio_from_bytes import save_audio_from_bytes
+
+BYTE_RESPONSE = b'\x12\x34\x56\x78\x90'
+
+OUTPUT_PATH = "generated_speech.wav"
+
+save_audio_from_bytes(BYTE_RESPONSE, OUTPUT_PATH)
diff --git a/examples/utils/token_calculator_example.py b/examples/utils/token_calculator_example.py
new file mode 100644
index 00000000..68ff25d2
--- /dev/null
+++ b/examples/utils/token_calculator_example.py
@@ -0,0 +1,14 @@
+"""
+Example for calclating the tokenizer
+"""
+from scrapegraphai.utils.token_calculator import truncate_text_tokens
+
+INPUT_TEXT = "http://nba.com"
+
+MODEL_NAME = "gpt-3.5-turbo"
+ENCODING_NAME = "EMBEDDING_ENCODING"
+
+tokenized_chunks = truncate_text_tokens(INPUT_TEXT, MODEL_NAME, ENCODING_NAME)
+
+for i, chunk in enumerate(tokenized_chunks):
+ print(f"Chunk {i+1}: {chunk}")
diff --git a/examples/vision_speech_example.py b/examples/utils/vision_speech_example.py
similarity index 100%
rename from examples/vision_speech_example.py
rename to examples/utils/vision_speech_example.py
diff --git a/scrapegraphai/builders/__init__.py b/scrapegraphai/builders/__init__.py
index 4ab8b612..03fd2d1a 100644
--- a/scrapegraphai/builders/__init__.py
+++ b/scrapegraphai/builders/__init__.py
@@ -2,4 +2,4 @@
__init__.py file for builders folder
"""
-from .graph_builder import GraphBuilder
\ No newline at end of file
+from .graph_builder import GraphBuilder
diff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.py
index b2d86dec..3460a5c7 100644
--- a/scrapegraphai/builders/graph_builder.py
+++ b/scrapegraphai/builders/graph_builder.py
@@ -1,7 +1,12 @@
+"""
+Module for making the graph building
+"""
+import graphviz
from langchain_core.prompts import ChatPromptTemplate
from langchain.chains import create_extraction_chain
from ..models import OpenAI
-from ..utils import nodes_metadata, graph_schema
+from ..helpers import nodes_metadata, graph_schema
+
class GraphBuilder:
"""
@@ -11,19 +16,24 @@ class GraphBuilder:
Attributes:
prompt (str): The user's natural language prompt for the scraping task.
- llm (ChatOpenAI): An instance of the ChatOpenAI class configured with the specified llm_config.
+ llm (ChatOpenAI): An instance of the ChatOpenAI class configured
+ with the specified llm_config.
nodes_description (str): A string description of all available nodes and their arguments.
- chain (LLMChain): The extraction chain responsible for processing the prompt and creating the graph.
+ chain (LLMChain): The extraction chain responsible for
+ processing the prompt and creating the graph.
Methods:
- build_graph(): Executes the graph creation process based on the user prompt and returns the graph configuration.
- convert_json_to_graphviz(json_data): Converts a JSON graph configuration to a Graphviz object for visualization.
+ build_graph(): Executes the graph creation process based on the user prompt
+ and returns the graph configuration.
+ convert_json_to_graphviz(json_data): Converts a JSON graph configuration
+ to a Graphviz object for visualization.
Args:
prompt (str): The user's natural language prompt describing the desired scraping operation.
url (str): The target URL from which data is to be scraped.
- llm_config (dict): Configuration parameters for the language model, where 'api_key' is mandatory,
- and 'model_name', 'temperature', and 'streaming' can be optionally included.
+ llm_config (dict): Configuration parameters for the
+ language model, where 'api_key' is mandatory,
+ and 'model_name', 'temperature', and 'streaming' can be optionally included.
Raises:
ValueError: If 'api_key' is not included in llm_config.
@@ -38,7 +48,7 @@ class GraphBuilder:
self.llm = self._create_llm()
self.nodes_description = self._generate_nodes_description()
self.chain = self._create_extraction_chain()
-
+
def _create_llm(self):
"""
Creates an instance of the OpenAI class with the provided language model configuration.
@@ -77,7 +87,8 @@ class GraphBuilder:
def _create_extraction_chain(self):
"""
- Creates an extraction chain for processing the user prompt and generating the graph configuration.
+ Creates an extraction chain for processing the user prompt and
+ generating the graph configuration.
Returns:
LLMChain: An instance of the LLMChain class.
@@ -90,20 +101,22 @@ class GraphBuilder:
Based on the user's input: "{input}", identify the essential nodes required for the task and suggest a graph configuration that outlines the flow between the chosen nodes.
""".format(nodes_description=self.nodes_description, input="{input}")
- extraction_prompt = ChatPromptTemplate.from_template(create_graph_prompt_template)
+ extraction_prompt = ChatPromptTemplate.from_template(
+ create_graph_prompt_template)
return create_extraction_chain(prompt=extraction_prompt, schema=graph_schema, llm=self.llm)
def build_graph(self):
"""
- Executes the graph creation process based on the user prompt and returns the graph configuration.
+ Executes the graph creation process based on the user prompt and
+ returns the graph configuration.
Returns:
dict: A JSON representation of the graph configuration.
"""
return self.chain.invoke(self.user_prompt)
-
+
@staticmethod
- def convert_json_to_graphviz(json_data, format='pdf'):
+ def convert_json_to_graphviz(json_data, format: str = 'pdf'):
"""
Converts a JSON graph configuration to a Graphviz object for visualization.
@@ -113,11 +126,10 @@ class GraphBuilder:
Returns:
graphviz.Digraph: A Graphviz object representing the graph configuration.
"""
- import graphviz
graph = graphviz.Digraph(comment='ScrapeGraphAI Generated Graph', format=format,
- node_attr={'color': 'lightblue2', 'style': 'filled'})
-
+ node_attr={'color': 'lightblue2', 'style': 'filled'})
+
graph_config = json_data["text"][0]
# Retrieve nodes, edges, and the entry point from the JSON data
@@ -142,4 +154,4 @@ class GraphBuilder:
else:
graph.edge(edge['from'], edge['to'])
- return graph
\ No newline at end of file
+ return graph
diff --git a/scrapegraphai/graphs/speech_summary_graph.py b/scrapegraphai/graphs/speech_summary_graph.py
index 4aaa0a0e..4cf3a32e 100644
--- a/scrapegraphai/graphs/speech_summary_graph.py
+++ b/scrapegraphai/graphs/speech_summary_graph.py
@@ -1,3 +1,7 @@
+"""
+Module for extracting the summary from the speach
+"""
+from scrapegraphai.utils.save_audio_from_bytes import save_audio_from_bytes
from ..models import OpenAI, OpenAITextToSpeech
from .base_graph import BaseGraph
from ..nodes import (
@@ -7,8 +11,8 @@ from ..nodes import (
GenerateAnswerNode,
ParseHTMLNode,
TextToSpeechNode,
- )
-from scrapegraphai.utils import save_audio_from_bytes
+)
+
class SpeechSummaryGraph:
"""
@@ -17,7 +21,8 @@ class SpeechSummaryGraph:
Attributes:
url (str): The URL of the web page to scrape and summarize.
- llm_config (dict): Configuration parameters for the language model, with 'api_key' mandatory.
+ llm_config (dict): Configuration parameters for the language model,
+ with 'api_key' mandatory.
summary_prompt (str): The prompt used to guide the summarization process.
output_path (Path): The path where the generated MP3 file will be saved.
@@ -40,9 +45,9 @@ class SpeechSummaryGraph:
self.llm_config = llm_config
self.llm = self._create_llm()
self.output_path = output_path
- self.text_to_speech_model = OpenAITextToSpeech(llm_config, model="tts-1", voice="alloy")
+ self.text_to_speech_model = OpenAITextToSpeech(
+ llm_config, model="tts-1", voice="alloy")
self.graph = self._create_graph()
-
def _create_llm(self):
"""
diff --git a/scrapegraphai/helpers/__init__.py b/scrapegraphai/helpers/__init__.py
new file mode 100644
index 00000000..daf2d09e
--- /dev/null
+++ b/scrapegraphai/helpers/__init__.py
@@ -0,0 +1,6 @@
+"""
+__init__.py for th e helpers folder
+
+"""
+from .nodes_metadata import nodes_metadata
+from .schemas import graph_schema
diff --git a/scrapegraphai/utils/nodes_metadata.py b/scrapegraphai/helpers/nodes_metadata.py
similarity index 85%
rename from scrapegraphai/utils/nodes_metadata.py
rename to scrapegraphai/helpers/nodes_metadata.py
index b576a755..e5e6f243 100644
--- a/scrapegraphai/utils/nodes_metadata.py
+++ b/scrapegraphai/helpers/nodes_metadata.py
@@ -43,12 +43,14 @@ nodes_metadata = {
"type": "conditional_node",
"args": {
"key_name": "The key in the state to check for a condition.",
- "next_nodes": "A list of two nodes specifying the next node to execute based on the condition's outcome."
+ "next_nodes": """A list of two nodes specifying the next node
+ to execute based on the condition's outcome."""
},
"returns": "The name of the next node to execute."
},
"ImageToTextNode": {
- "description": "Converts image content to text by extracting visual information and interpreting it.",
+ "description": """Converts image content to text by
+ extracting visual information and interpreting it.""",
"type": "node",
"args": {
"image_data": "Data of the image to be processed."
@@ -56,11 +58,12 @@ nodes_metadata = {
"returns": "Updated state with the textual description of the image under 'image_text' key."
},
"TextToSpeechNode": {
- "description": "Converts text into spoken words, allowing for auditory representation of the text.",
+ "description": """Converts text into spoken words, allow
+ ing for auditory representation of the text.""",
"type": "node",
"args": {
"text": "The text to be converted into speech."
},
"returns": "Updated state with the speech audio file or data under 'speech_audio' key."
}
-}
\ No newline at end of file
+}
diff --git a/scrapegraphai/helpers/schemas.py b/scrapegraphai/helpers/schemas.py
new file mode 100644
index 00000000..96ee5ff0
--- /dev/null
+++ b/scrapegraphai/helpers/schemas.py
@@ -0,0 +1,62 @@
+"""
+Schemas representing the configuration of a graph or node in the ScrapeGraphAI library
+"""
+
+graph_schema = {
+ "name": "ScrapeGraphAI Graph Configuration",
+ "description": "JSON schema for representing graphs in the ScrapeGraphAI library",
+ "type": "object",
+ "properties": {
+ "nodes": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "node_name": {
+ "type": "string",
+ "description": "The unique identifier for the node."
+ },
+ "node_type": {
+ "type": "string",
+ "description": "The type of node, must be 'node' or 'conditional_node'."
+ },
+ "args": {
+ "type": "object",
+ "description": "The arguments required for the node's execution."
+ },
+ "returns": {
+ "type": "object",
+ "description": "The return values of the node's execution."
+ },
+ },
+ "required": ["node_name", "node_type", "args", "returns"]
+ }
+ },
+ "edges": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "from": {
+ "type": "string",
+ "description": "The node_name of the starting node of the edge."
+ },
+ "to": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": """An array containing the node_names of the ending nodes of the edge.
+ If the 'from' node is a conditional node, this array must contain exactly two node_names."""
+ }
+ },
+ "required": ["from", "to"]
+ }
+ },
+ "entry_point": {
+ "type": "string",
+ "description": "The node_name of the entry point node."
+ }
+ },
+ "required": ["nodes", "edges", "entry_point"]
+}
diff --git a/scrapegraphai/models/openai.py b/scrapegraphai/models/openai.py
index 887cc728..7c76a4b1 100644
--- a/scrapegraphai/models/openai.py
+++ b/scrapegraphai/models/openai.py
@@ -1,6 +1,12 @@
+"""
+openai configuration wrapper
+"""
from langchain_openai import ChatOpenAI
+
class OpenAI(ChatOpenAI):
+ """Class for wrapping openai module"""
+
def __init__(self, llm_config: dict):
"""
A wrapper for the ChatOpenAI class that provides default configuration
diff --git a/scrapegraphai/models/openai_itt.py b/scrapegraphai/models/openai_itt.py
index d3950a7b..0ab8f4ef 100644
--- a/scrapegraphai/models/openai_itt.py
+++ b/scrapegraphai/models/openai_itt.py
@@ -1,10 +1,12 @@
"""
-This module contains the OpenAIImageToText class, which is a subclass of ChatOpenAI that is specialized for converting images to text.
+This module contains the OpenAIImageToText class,
+which is a subclass of ChatOpenAI that is specialized for converting images to text.
"""
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
+
class OpenAIImageToText(ChatOpenAI):
"""
A class that uses OpenAI's Chat API to convert an image to text.
@@ -56,5 +58,4 @@ class OpenAIImageToText(ChatOpenAI):
# Use the invoke method from the superclass (ChatOpenAI)
result = self.invoke([message]).content
-
return result
diff --git a/scrapegraphai/models/openai_tts.py b/scrapegraphai/models/openai_tts.py
index 47c6b1f2..7286a4ca 100644
--- a/scrapegraphai/models/openai_tts.py
+++ b/scrapegraphai/models/openai_tts.py
@@ -5,6 +5,7 @@ to convert text into speech.
from openai import OpenAI
+
class OpenAITextToSpeech:
"""
A class that uses OpenAI's API to convert text to speech.
@@ -17,17 +18,20 @@ class OpenAITextToSpeech:
voice (str): The voice model to use for generating speech.
Methods:
- run(text): Converts the provided text to speech and returns the bytes of the generated speech.
+ run(text): Converts the provided text to speech and returns the
+ bytes of the generated speech.
"""
- def __init__(self, llm_config, model="tts-1", voice="alloy"):
+ def __init__(self, llm_config: dict, model: str = "tts-1", voice: str = "alloy"):
"""
Initializes an instance of the OpenAITextToSpeech class.
Args:
llm_config (dict): The configuration for the language model.
- model (str, optional): The model to use for text-to-speech conversion. Defaults to "tts-1".
- voice (str, optional): The voice model to use for generating speech. Defaults to "alloy".
+ model (str, optional): The model to use for text-to-speech conversion.
+ Defaults to "tts-1".
+ voice (str, optional): The voice model to use for generating speech.
+ Defaults to "alloy".
"""
# convert model_name to model
@@ -41,7 +45,7 @@ class OpenAITextToSpeech:
Args:
text (str): The text to convert to speech.
-
+
"""
response = self.client.audio.speech.create(
model=self.model,
diff --git a/scrapegraphai/utils/__init__.py b/scrapegraphai/utils/__init__.py
index e3f37f6c..e0bf7d52 100644
--- a/scrapegraphai/utils/__init__.py
+++ b/scrapegraphai/utils/__init__.py
@@ -1,6 +1,6 @@
"""
__init__.py file for utils folder
"""
-from .nodes_metadata import nodes_metadata
-from .schemas import graph_schema
-from .save_audio_from_bytes import save_audio_from_bytes
\ No newline at end of file
+from .save_audio_from_bytes import save_audio_from_bytes
+from .convert_to_csv import convert_to_csv
+from .convert_to_json import convert_to_json
diff --git a/scrapegraphai/utils/save_audio_from_bytes.py b/scrapegraphai/utils/save_audio_from_bytes.py
index 55b54573..f250edbf 100644
--- a/scrapegraphai/utils/save_audio_from_bytes.py
+++ b/scrapegraphai/utils/save_audio_from_bytes.py
@@ -4,6 +4,7 @@ This utility function saves the byte response as an audio file.
from pathlib import Path
+
def save_audio_from_bytes(byte_response, output_path):
"""
Saves the byte response as an audio file.
@@ -15,6 +16,5 @@ def save_audio_from_bytes(byte_response, output_path):
if not isinstance(output_path, Path):
output_path = Path(output_path)
- # Write the byte response to the specified file path
with open(output_path, 'wb') as audio_file:
audio_file.write(byte_response)
diff --git a/scrapegraphai/utils/schemas.py b/scrapegraphai/utils/schemas.py
deleted file mode 100644
index 3ba2d624..00000000
--- a/scrapegraphai/utils/schemas.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""
-Schemas representing the configuration of a graph or node in the ScrapeGraphAI library
-"""
-
-graph_schema = {
- "name": "ScrapeGraphAI Graph Configuration",
- "description": "JSON schema for representing graphs in the ScrapeGraphAI library",
- "type": "object",
- "properties": {
- "nodes": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "node_name": {
- "type": "string",
- "description": "The unique identifier for the node."
- },
- "node_type": {
- "type": "string",
- "description": "The type of node, must be 'node' or 'conditional_node'."
- },
- "args": {
- "type": "object",
- "description": "The arguments required for the node's execution."
- },
- "returns": {
- "type": "object",
- "description": "The return values of the node's execution."
- },
- },
- "required": ["node_name", "node_type", "args", "returns"]
- }
- },
- "edges": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "from": {
- "type": "string",
- "description": "The node_name of the starting node of the edge."
- },
- "to": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "An array containing the node_names of the ending nodes of the edge. If the 'from' node is a conditional node, this array must contain exactly two node_names."
- }
- },
- "required": ["from", "to"]
- }
- },
- "entry_point": {
- "type": "string",
- "description": "The node_name of the entry point node."
- }
- },
- "required": ["nodes", "edges", "entry_point"]
-}
\ No newline at end of file
diff --git a/tests/utils/remover_test.py b/tests/utils/remover_test.py
new file mode 100644
index 00000000..ad08a4d5
--- /dev/null
+++ b/tests/utils/remover_test.py
@@ -0,0 +1,63 @@
+"""
+Test for the remover method
+"""
+import unittest
+
+from scrapegraphai.utils.remover import remover
+
+
+class TestRemover(unittest.TestCase):
+ """Test class """
+
+ def test_remover_basic(self):
+ """First test"""
+ html_content = """
+ <html>
+ <head>
+ <title>Test Page</title>
+ </head>
+ <body>
+ <h1>This is a Test</h1>
+ <p>Hello, World!</p>
+ <script>alert("This is a script");</script>
+ </body>
+ </html>
+ """
+ expected_result = """<title>Test Page</title>
+ <body><h1>This is a Test</h1><p>Hello, World!</p></body>"""
+ self.assertEqual(remover(html_content), expected_result)
+
+ def test_remover_only_body(self):
+ """Second test"""
+ html_content = """
+ <html>
+ <head>
+ <title>Test Page</title>
+ </head>
+ <body>
+ <h1>This is a Test</h1>
+ <p>Hello, World!</p>
+ <script>alert("This is a script");</script>
+ </body>
+ </html>
+ """
+ expected_result = '<h1>This is a Test</h1><p>Hello, World!</p>'
+ self.assertEqual(
+ remover(html_content, only_body=True), expected_result)
+
+ def test_remover_no_body(self):
+ """Third test"""
+ html_content = """
+ <html>
+ <head>
+ <title>Test Page</title>
+ </head>
+ <p>This is a paragraph.</p>
+ </html>
+ """
+ expected_result = '<title>Test Page</title>'
+ self.assertEqual(remover(html_content), expected_result)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/result.csv b/tests/utils/result.csv
similarity index 100%
rename from tests/result.csv
rename to tests/utils/result.csv
diff --git a/tests/result.json b/tests/utils/result.json
similarity index 100%
rename from tests/result.json
rename to tests/utils/result.json
diff --git a/tests/utils/save_audio_from_bytes_test.py b/tests/utils/save_audio_from_bytes_test.py
new file mode 100644
index 00000000..e08c2f43
--- /dev/null
+++ b/tests/utils/save_audio_from_bytes_test.py
@@ -0,0 +1,35 @@
+"""
+Test file for the class save_audio_from_bytes
+"""
+import unittest
+import os
+from tempfile import TemporaryDirectory
+from pathlib import Path
+from scrapegraphai.utils.save_audio_from_bytes import save_audio_from_bytes
+
+
+class TestSaveAudioFromBytes(unittest.TestCase):
+ """
+ Test class
+ """
+
+ def test_save_audio_from_bytes(self):
+ """
+ First test
+ """
+ with TemporaryDirectory() as temp_dir:
+ temp_dir_path = Path(temp_dir)
+
+ byte_response = b'\x12\x34\x56\x78\x90'
+
+ output_path = temp_dir_path / "generated_speech.wav"
+
+ save_audio_from_bytes(byte_response, output_path)
+
+ self.assertTrue(output_path.exists())
+
+ self.assertTrue(os.path.getsize(output_path) > 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_convert_to_csv.py b/tests/utils/test_convert_to_csv.py
similarity index 92%
rename from tests/test_convert_to_csv.py
rename to tests/utils/test_convert_to_csv.py
index a61f09a8..174e9838 100644
--- a/tests/test_convert_to_csv.py
+++ b/tests/utils/test_convert_to_csv.py
@@ -14,5 +14,5 @@ class TestConvertToCsvFunction(unittest.TestCase):
"""
example = {"trial": [1, 2, 3]}
filename = "result"
- path = "../Scrapegraph-ai/tests"
+ path = "../Scrapegraph-ai/tests/utils"
convert_to_csv(example, filename, path)
diff --git a/tests/test_convert_to_json.py b/tests/utils/test_convert_to_json.py
similarity index 92%
rename from tests/test_convert_to_json.py
rename to tests/utils/test_convert_to_json.py
index d8d2c7f5..6a269e3d 100644
--- a/tests/test_convert_to_json.py
+++ b/tests/utils/test_convert_to_json.py
@@ -16,5 +16,5 @@ class TestConvertToJSonFunction(unittest.TestCase):
"""
example = {"trial": [1, 2, 3]}
filename = "result"
- path = "../Scrapegraph-ai/tests"
+ path = "../Scrapegraph-ai/test/utils"
convert_to_json(example, filename, path)
diff --git a/tests/utils/token_calculator_test.py b/tests/utils/token_calculator_test.py
new file mode 100644
index 00000000..708dcca4
--- /dev/null
+++ b/tests/utils/token_calculator_test.py
@@ -0,0 +1,32 @@
+"""
+Test fo testing the tokenizer
+"""
+import unittest
+from scrapegraphai.utils.token_calculator import truncate_text_tokens
+
+
+class TestTruncateTextTokens(unittest.TestCase):
+ """
+ Class for testing the tokenizer
+ """
+
+ def test_truncate_text_tokens(self):
+ """
+ Principal text
+ """
+ input_text = "This is a sample text to be tokenized into chunks."
+ expected_output = [
+ "This is a sample text to be tokenized into",
+ "chunks."
+ ]
+ model_name = "gpt-3.5-turbo"
+ encoding_name = "EMBEDDING_ENCODING"
+
+ output_chunks = truncate_text_tokens(
+ input_text, model_name, encoding_name)
+
+ self.assertEqual(output_chunks, expected_output)
+
+
+if __name__ == '__main__':
+ unittest.main()