Skip to content

Python scraper based on AI

working text2speech and image2text

PeriniMda16360b1f31
diff --git a/.gitignore b/.gitignore
index c8faf323..2b7d506d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,5 +22,6 @@ docs/source/_static/
venv/
.vscode/
-# exclude pdf
+# exclude pdf, mp3
*.pdf
+*.mp3
diff --git a/examples/vision_speech_example.py b/examples/vision_speech_example.py
new file mode 100644
index 00000000..21bed5ab
--- /dev/null
+++ b/examples/vision_speech_example.py
@@ -0,0 +1,34 @@
+"""
+Basic example of scraping pipeline using SmartScraper
+"""
+
+import os
+from dotenv import load_dotenv
+from scrapegraphai.models import OpenAIImageToText, OpenAITextToSpeech
+from scrapegraphai.utils import save_audio_from_bytes
+
+load_dotenv()
+
+# Define the configuration for the language model
+openai_key = os.getenv("OPENAI_APIKEY")
+llm_config = {
+ "api_key": openai_key,
+ "model_name": "gpt-4-vision-preview",
+}
+
+model = OpenAIImageToText(llm_config)
+answer = model.run("https://raw.githubusercontent.com/VinciGit00/Scrapegraph-ai/main/docs/assets/scrapegraphai_logo.png")
+print(answer)
+
+text_to_speech = OpenAITextToSpeech(llm_config, model="tts-1", voice="alloy")
+
+text = "Today is a wonderful day to build something people love!"
+audio = text_to_speech.run(text)
+
+# Save the audio to a file
+curr_dir = os.path.dirname(os.path.realpath(__file__))
+file_path = os.path.join(curr_dir, "text2speech.mp3")
+
+save_audio_from_bytes(audio, file_path)
+
+print(f"Speech file saved to: {file_path}")
\ No newline at end of file
diff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.py
index 0954bbfb..b2d86dec 100644
--- a/scrapegraphai/builders/graph_builder.py
+++ b/scrapegraphai/builders/graph_builder.py
@@ -41,10 +41,10 @@ class GraphBuilder:
def _create_llm(self):
"""
- Creates an instance of the ChatOpenAI class with the provided language model configuration.
+ Creates an instance of the OpenAI class with the provided language model configuration.
Returns:
- ChatOpenAI: An instance of the ChatOpenAI class.
+ OpenAI: An instance of the OpenAI class.
Raises:
ValueError: If 'api_key' is not provided in llm_config.
diff --git a/scrapegraphai/models/__init__.py b/scrapegraphai/models/__init__.py
index b9aa68be..39691b17 100644
--- a/scrapegraphai/models/__init__.py
+++ b/scrapegraphai/models/__init__.py
@@ -2,4 +2,6 @@
__init__.py file for models folder
"""
-from .openai import OpenAI
\ No newline at end of file
+from .openai import OpenAI
+from .openai_itt import OpenAIImageToText
+from .openai_tts import OpenAITextToSpeech
\ No newline at end of file
diff --git a/scrapegraphai/models/openai_itt.py b/scrapegraphai/models/openai_itt.py
new file mode 100644
index 00000000..d3950a7b
--- /dev/null
+++ b/scrapegraphai/models/openai_itt.py
@@ -0,0 +1,60 @@
+"""
+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.
+
+ Args:
+ llm_config (dict): The configuration for the language model.
+
+ Attributes:
+ max_tokens (int): The maximum number of tokens to generate in the response.
+
+ Methods:
+ run(image_url): Runs the image-to-text conversion using the provided image URL.
+
+ """
+
+ def __init__(self, llm_config: dict):
+ """
+ Initializes an instance of the OpenAIImageToText class.
+
+ Args:
+ llm_config (dict): The configuration for the language model.
+
+ """
+ super().__init__(**llm_config, max_tokens=256)
+
+ def run(self, image_url: str):
+ """
+ Runs the image-to-text conversion using the provided image URL.
+
+ Args:
+ image_url (str): The URL of the image to convert to text.
+
+ Returns:
+ str: The generated text description of the image.
+
+ """
+ message = HumanMessage(
+ content=[
+ {"type": "text", "text": "What is this image showing"},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": image_url,
+ "detail": "auto",
+ },
+ },
+ ]
+ )
+
+ # 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
new file mode 100644
index 00000000..47c6b1f2
--- /dev/null
+++ b/scrapegraphai/models/openai_tts.py
@@ -0,0 +1,52 @@
+"""
+This module contains the OpenAITextToSpeech class, which uses OpenAI's API
+to convert text into speech.
+"""
+
+from openai import OpenAI
+
+class OpenAITextToSpeech:
+ """
+ A class that uses OpenAI's API to convert text to speech.
+
+ Args:
+ llm_config (dict): The configuration for the language model.
+
+ Attributes:
+ model (str): The model to use for text-to-speech conversion.
+ 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.
+ """
+
+ def __init__(self, llm_config, model="tts-1", voice="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".
+ """
+
+ # convert model_name to model
+ self.client = OpenAI(api_key=llm_config.get("api_key"))
+ self.model = model
+ self.voice = voice
+
+ def run(self, text):
+ """
+ Converts the provided text to speech and returns the bytes of the generated speech.
+
+ Args:
+ text (str): The text to convert to speech.
+
+ """
+ response = self.client.audio.speech.create(
+ model=self.model,
+ voice=self.voice,
+ input=text
+ )
+
+ return response.content
diff --git a/scrapegraphai/nodes/get_probable_tags_node.py b/scrapegraphai/nodes/get_probable_tags_node.py
index 4861a3f9..068e7636 100644
--- a/scrapegraphai/nodes/get_probable_tags_node.py
+++ b/scrapegraphai/nodes/get_probable_tags_node.py
@@ -83,6 +83,6 @@ class GetProbableTagsNode(BaseNode):
print("Possible tags: ", *probable_tags)
- # Update the nested 'keys' dictionary with probable tags
+ # Update the dictionary with probable tags
state.update({"tags": probable_tags})
return state
diff --git a/scrapegraphai/nodes/image_to_text_node.py b/scrapegraphai/nodes/image_to_text_node.py
index d75c40fc..59979fc0 100644
--- a/scrapegraphai/nodes/image_to_text_node.py
+++ b/scrapegraphai/nodes/image_to_text_node.py
@@ -1,61 +1,32 @@
"""
-Module for creating the basic node
+Module for the ImageToTextNode class.
"""
-from langchain_openai import ChatOpenAI
-from .base_node import BaseNode
-
-from langchain_core.messages import HumanMessage, SystemMessage
+from .base_node import BaseNode
class ImageToTextNode(BaseNode):
"""
- An abstract base class for nodes in a graph-based workflow. Each node is
- intended to perform a specific action when executed as part of the graph's
- processing flow.
+ A class representing a node that processes an image and returns the text description.
Attributes:
- node_name (str): A unique identifier for the node.
- node_type (str): Specifies the node's type, which influences how the
- node interacts within the graph. Valid values are
- "node" for standard nodes and "conditional_node" for
- nodes that determine the flow based on conditions.
+ llm (OpenAIImageToText): An instance of the OpenAIImageToText class.
Methods:
- execute(state): An abstract method that subclasses must implement. This
- method should contain the logic that the node executes
- when it is reached in the graph's flow. It takes the
- graph's current state as input and returns the updated
- state after execution.
-
- Args:
- node_name (str): The unique identifier name for the node. This name is
- used to reference the node within the graph.
- node_type (str): The type of the node, limited to "node" or
- "conditional_node". This categorization helps in
- determining the node's role and behavior within the
- graph.
-
- Raises:
- ValueError: If the provided `node_type` is not one of the allowed
- values ("node" or "conditional_node"), a ValueError is
- raised to indicate the incorrect usage.
+ execute(state, url): Execute the node's logic and return the updated state.
"""
def __init__(self, llm, node_name: str = "ParseImageToText"):
"""
- Initialize the node with a unique identifier and a specified node type.
+ Initializes an instance of the ImageToTextNode class.
Args:
- node_name (str): The unique identifier name for the node.
- node_type (str): The type of the node, limited to "node" or "conditional_node".
-
- Raises:
- ValueError: If node_type is not "node" or "conditional_node".
+ llm (OpenAIImageToText): An instance of the OpenAIImageToText class.
+ node_name (str, optional): The name of the node. Defaults to "ParseImageToText".
"""
super().__init__(node_name, "node")
self.llm = llm
- def execute(self, state: dict, url: str) -> str:
+ def execute(self, state: dict, url: str) -> dict:
"""
Execute the node's logic and return the updated state.
Args:
@@ -63,26 +34,7 @@ class ImageToTextNode(BaseNode):
url (str): url of the image where to
:return: The updated state after executing this node.
"""
-
- if not self.llm.model_name == "gpt-4-vision-preview":
- raise ValueError("Model is not gpt-4-vision-preview")
-
- chat = ChatOpenAI(model=self.llm.model_name, max_tokens=256)
- result = chat.invoke(
- [
- HumanMessage(
- content=[
- {"type": "text", "text": "What is this image showing"},
- {
- "type": "image_url",
- "image_url": {
- "url": url,
- "detail": "auto",
- },
- },
- ]
- )
- ]
- )
+ text_answer = self.llm.run(url)
- return result
+ state.update({"image_text": text_answer})
+ return state
diff --git a/scrapegraphai/nodes/text_to_speech_node.py b/scrapegraphai/nodes/text_to_speech_node.py
index 39209278..127a9d7d 100644
--- a/scrapegraphai/nodes/text_to_speech_node.py
+++ b/scrapegraphai/nodes/text_to_speech_node.py
@@ -3,74 +3,37 @@
Module for parsing the text to voice
"""
-from openai import OpenAI
from .base_node import BaseNode
-
class TextToSpeechNode(BaseNode):
"""
- A node responsible for parsing text content from a document using specified tags and readinf
- it with the selected voiceq.
- This node enhances the scraping workflow by allowing for targeted extraction of
- content, thereby optimizing the processing of large HTML documents.
+ A class representing a node that processes text and returns the voice.
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".
+ llm (OpenAITextToSpeech): An instance of the OpenAITextToSpeech class.
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.
+ execute(state, text): Execute the node's logic and return the updated state.
"""
- def __init__(self, llm, node_name: str = "ParseTextToSpeach"):
+ def __init__(self, llm, node_name: str = "TextToSpeechNode"):
"""
- Initializes the ParseHTMLNode with a node name.
+ Initializes an instance of the TextToSpeechNode class.
"""
super().__init__(node_name, "node")
self.llm = llm
- def execute(self, state: dict, text: str, output_path: str = str, model: str = "tts-1", voice="alloy") -> dict:
+ def execute(self, state: dict, text: str) -> dict:
"""
- 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.
-
+ Execute the node's logic and return the updated state.
Args:
- state (dict): The current state of the graph, expected to contain
- 'document' within 'keys', and optionally 'tags' for targeted parsing.
- text (str):The text you want to read
- outpath_path (strOptional): Path for saving
- model (str): type of model. Possible options: "tts-1" or tts-1-hd
- voice (str): type of the voice. Possible choices: "alloy", "echo",
- "fable", "onyx", "nova", or "shimmer"
-
- Returns:
- dict: The updated state with the 'parsed_document' key containing the parsed content,
- if tags were provided, or the original document otherwise.
+ state (dict): The current state of the graph.
+ text (str): The text to convert to speech.
- Raises:
- KeyError: If 'document' is not found in the state, indicating that the necessary
- information for parsing is missing.
+ :return: The updated state after executing this node.
"""
- if output_path is not None:
- try:
- client = OpenAI(
- api_key=self.llm.openai_api_key)
- response = client.audio.speech.create(
- model=model,
- voice=voice,
- input=text,
- )
+ audio = self.llm.run(text)
- response.stream_to_file(f"{output_path}/output.mp3")
- except Exception as e:
- print(f"Error while saving the audio file: {e}")
- else:
- print("The output path is not specified correctly.")
+ state.update({"audio": audio})
+ return state
diff --git a/scrapegraphai/utils/__init__.py b/scrapegraphai/utils/__init__.py
index a72f8b13..e3f37f6c 100644
--- a/scrapegraphai/utils/__init__.py
+++ b/scrapegraphai/utils/__init__.py
@@ -2,4 +2,5 @@
__init__.py file for utils folder
"""
from .nodes_metadata import nodes_metadata
-from .schemas import graph_schema
\ No newline at end of file
+from .schemas import graph_schema
+from .save_audio_from_bytes import save_audio_from_bytes
\ No newline at end of file
diff --git a/scrapegraphai/utils/save_audio_from_bytes.py b/scrapegraphai/utils/save_audio_from_bytes.py
new file mode 100644
index 00000000..55b54573
--- /dev/null
+++ b/scrapegraphai/utils/save_audio_from_bytes.py
@@ -0,0 +1,20 @@
+"""
+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.
+
+ Args:
+ byte_response (bytes): The byte response containing the generated speech.
+ output_path (str or Path): The file path where the generated speech should be saved.
+ """
+ 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
index 1624eed6..3ba2d624 100644
--- a/scrapegraphai/utils/schemas.py
+++ b/scrapegraphai/utils/schemas.py
@@ -1,3 +1,7 @@
+"""
+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",