Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
removed unused imports and comments + removed dead code
Marco Vinciguerrad0969feb7c62
diff --git a/scrapegraphai/models/deepseek.py b/scrapegraphai/models/deepseek.pyindex 1901269e..70ed3a9c 100644--- a/scrapegraphai/models/deepseek.py+++ b/scrapegraphai/models/deepseek.py@@ -3,7 +3,6 @@ DeepSeek Module"""from langchain_openai import ChatOpenAI-class DeepSeek(ChatOpenAI):"""A wrapper for the ChatOpenAI class (DeepSeek uses an OpenAI-like API) thatdiff --git a/scrapegraphai/models/oneapi.py b/scrapegraphai/models/oneapi.pyindex 9b20621b..6071fd54 100644--- a/scrapegraphai/models/oneapi.py+++ b/scrapegraphai/models/oneapi.py@@ -3,7 +3,6 @@ OneAPI Module"""from langchain_openai import ChatOpenAI-class OneApi(ChatOpenAI):"""A wrapper for the OneApi class that provides default configurationdiff --git a/scrapegraphai/models/openai_itt.py b/scrapegraphai/models/openai_itt.pyindex 5bbdf8ad..2d59b1b8 100644--- a/scrapegraphai/models/openai_itt.py+++ b/scrapegraphai/models/openai_itt.py@@ -1,11 +1,9 @@"""OpenAIImageToText Module"""-from langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage-class OpenAIImageToText(ChatOpenAI):"""A wrapper for the OpenAIImageToText class that provides default configuration@@ -43,6 +41,5 @@ class OpenAIImageToText(ChatOpenAI):])- # Use the invoke method from the superclass (ChatOpenAI)result = self.invoke([message]).contentreturn resultdiff --git a/scrapegraphai/models/openai_tts.py b/scrapegraphai/models/openai_tts.pyindex 6b84ba29..9cd591ec 100644--- a/scrapegraphai/models/openai_tts.py+++ b/scrapegraphai/models/openai_tts.py@@ -1,10 +1,8 @@"""OpenAITextToSpeech Module"""-from openai import OpenAI-class OpenAITextToSpeech:"""Implements a text-to-speech model using the OpenAI API.@@ -20,7 +18,6 @@ class OpenAITextToSpeech:def __init__(self, tts_config: dict):- # convert model_name to modelself.client = OpenAI(api_key=tts_config.get("api_key"),base_url=tts_config.get("base_url", None))self.model = tts_config.get("model", "tts-1")diff --git a/scrapegraphai/utils/copy.py b/scrapegraphai/utils/copy.pyindex 0cdda362..5e018f8b 100644--- a/scrapegraphai/utils/copy.py+++ b/scrapegraphai/utils/copy.py@@ -12,7 +12,6 @@ class DeepCopyError(Exception):pass-def is_boto3_client(obj):"""Function for understanding if the script is using boto3 or not@@ -30,7 +29,6 @@ def is_boto3_client(obj):return Falsereturn False-def safe_deepcopy(obj: Any) -> Any:"""Attempts to create a deep copy of the object using `copy.deepcopy`diff --git a/scrapegraphai/utils/custom_callback.py b/scrapegraphai/utils/custom_callback.pyindex a3992a5b..f39581c3 100644--- a/scrapegraphai/utils/custom_callback.py+++ b/scrapegraphai/utils/custom_callback.py@@ -8,15 +8,12 @@ from contextlib import contextmanagerimport threadingfrom typing import Any, Dict, List, Optionalfrom contextvars import ContextVar-from langchain_core.callbacks import BaseCallbackHandlerfrom langchain_core.messages import AIMessagefrom langchain_core.outputs import ChatGeneration, LLMResultfrom langchain_core.tracers.context import register_configure_hook-from .model_costs import MODEL_COST_PER_1K_TOKENS_INPUT, MODEL_COST_PER_1K_TOKENS_OUTPUT-def get_token_cost_for_model(model_name: str, num_tokens: int, is_completion: bool = False) -> float:@@ -36,7 +33,6 @@ def get_token_cost_for_model(return 0.0if is_completion:return MODEL_COST_PER_1K_TOKENS_OUTPUT[model_name] * (num_tokens / 1000)-return MODEL_COST_PER_1K_TOKENS_INPUT[model_name] * (num_tokens / 1000)@@ -154,4 +150,4 @@ def get_custom_callback(llm_model_name: str):cb = CustomCallbackHandler(llm_model_name)custom_callback.set(cb)yield cb- custom_callback.set(None)\ No newline at end of file+ custom_callback.set(None)diff --git a/scrapegraphai/utils/llm_callback_manager.py b/scrapegraphai/utils/llm_callback_manager.pyindex a6b9c893..03bdaf0b 100644--- a/scrapegraphai/utils/llm_callback_manager.py+++ b/scrapegraphai/utils/llm_callback_manager.py@@ -3,14 +3,16 @@ This module provides a custom callback manager for the LLM models."""import threadingfrom contextlib import contextmanager-from .custom_callback import get_custom_callback-from langchain_community.callbacks import get_openai_callbackfrom langchain_community.callbacks.manager import get_bedrock_anthropic_callbackfrom langchain_openai import ChatOpenAI, AzureChatOpenAIfrom langchain_aws import ChatBedrock+from .custom_callback import get_custom_callbackclass CustomLLMCallbackManager:+ """+ custom LLLM calback class+ """_lock = threading.Lock()@contextmanager@@ -22,7 +24,8 @@ class CustomLLMCallbackManager:yield cbfinally:CustomLLMCallbackManager._lock.release()- elif isinstance(llm_model, ChatBedrock) and llm_model_name is not None and "claude" in llm_model_name:+ elif isinstance(llm_model, ChatBedrock) and \+ llm_model_name is not None and "claude" in llm_model_name:try:with get_bedrock_anthropic_callback() as cb:yield cb@@ -35,4 +38,4 @@ class CustomLLMCallbackManager:finally:CustomLLMCallbackManager._lock.release()else:- yield None\ No newline at end of file+ yield Nonediff --git a/scrapegraphai/utils/logging.py b/scrapegraphai/utils/logging.pyindex 44f40aff..332d1909 100644--- a/scrapegraphai/utils/logging.py+++ b/scrapegraphai/utils/logging.py@@ -1,11 +1,9 @@"""A centralized logging system for any library.-This module provides functions to manage logging for a library. It includesfunctions to get and set the verbosity level, add and remove handlers, andcontrol propagation. It also includes a function to set formatting for allhandlers bound to the root logger.-Source code inspired by: https://gist.github.com/DiTo97/9a0377f24236b66134eb96da1ec1693f"""diff --git a/scrapegraphai/utils/model_costs.py b/scrapegraphai/utils/model_costs.pyindex a34ee9cd..c6cce423 100644--- a/scrapegraphai/utils/model_costs.py+++ b/scrapegraphai/utils/model_costs.py@@ -2,6 +2,10 @@This file contains the cost of models per 1k tokens for input and output.The file is on a best effort basis and may not be up to date. Any contributions are welcome."""++"""+Cost for 1k tokens in input+"""MODEL_COST_PER_1K_TOKENS_INPUT = {### MistralAI# General Purpose@@ -53,8 +57,10 @@ MODEL_COST_PER_1K_TOKENS_INPUT = {"amazon.titan-text-premier-v1:0": 0.0005,}+"""+Cost for 1k tokens in output+"""MODEL_COST_PER_1K_TOKENS_OUTPUT = {- ### MistralAI# General Purpose"open-mistral-nemo": 0.00015,"open-mistral-nemo-2407": 0.00015,@@ -102,4 +108,4 @@ MODEL_COST_PER_1K_TOKENS_OUTPUT = {"amazon.titan-text-express-v1": 0.0006,"amazon.titan-text-lite-v1": 0.0002,"amazon.titan-text-premier-v1:0": 0.0015,-}\ No newline at end of file+}diff --git a/scrapegraphai/utils/output_parser.py b/scrapegraphai/utils/output_parser.pyindex 39ae092e..3eabfa8b 100644--- a/scrapegraphai/utils/output_parser.py+++ b/scrapegraphai/utils/output_parser.py@@ -1,12 +1,13 @@"""Functions to retrieve the correct output parser and format instructions for the LLM model."""+from typing import Union, Dict, Any, Type, Callablefrom pydantic import BaseModel as BaseModelV2from pydantic.v1 import BaseModel as BaseModelV1-from typing import Union, Dict, Any, Type, Callablefrom langchain_core.output_parsers import JsonOutputParser-def get_structured_output_parser(schema: Union[Dict[str, Any], Type[BaseModelV1 | BaseModelV2], Type]) -> Callable:+def get_structured_output_parser(schema: Union[Dict[str, Any],+ Type[BaseModelV1 | BaseModelV2], Type]) -> Callable:"""Get the correct output parser for the LLM model.@@ -15,7 +16,7 @@ def get_structured_output_parser(schema: Union[Dict[str, Any], Type[BaseModelV1"""if issubclass(schema, BaseModelV1):return _base_model_v1_output_parser-+if issubclass(schema, BaseModelV2):return _base_model_v2_output_parser@@ -29,12 +30,14 @@ def get_pydantic_output_parser(schema: Union[Dict[str, Any], Type[BaseModelV1 |JsonOutputParser: The output parser object."""if issubclass(schema, BaseModelV1):- raise ValueError("pydantic.v1 and langchain_core.pydantic_v1 are not supported with this LLM model. Please use pydantic v2 instead.")-+ raise ValueError("""pydantic.v1 and langchain_core.pydantic_v1+ are not supported with this LLM model. Please use pydantic v2 instead.""")+if issubclass(schema, BaseModelV2):return JsonOutputParser(pydantic_object=schema)- raise ValueError("The schema is not a pydantic subclass. With this LLM model you must use a pydantic schemas.")+ raise ValueError("""The schema is not a pydantic subclass.+ With this LLM model you must use a pydantic schemas.""")def _base_model_v1_output_parser(x: BaseModelV1) -> dict:"""@@ -47,8 +50,7 @@ def _base_model_v1_output_parser(x: BaseModelV1) -> dict:dict: The parsed output."""work_dict = x.dict()-- # recursive dict parser+def recursive_dict_parser(work_dict: dict) -> dict:dict_keys = work_dict.keys()for key in dict_keys:@@ -56,7 +58,7 @@ def _base_model_v1_output_parser(x: BaseModelV1) -> dict:work_dict[key] = work_dict[key].dict()recursive_dict_parser(work_dict[key])return work_dict-+return recursive_dict_parser(work_dict)diff --git a/scrapegraphai/utils/proxy_rotation.py b/scrapegraphai/utils/proxy_rotation.pyindex 586e640e..9484b0ef 100644--- a/scrapegraphai/utils/proxy_rotation.py+++ b/scrapegraphai/utils/proxy_rotation.py@@ -1,7 +1,6 @@"""Module for rotating proxies"""-import ipaddressimport randomimport re@@ -162,7 +161,7 @@ def _search_proxy(proxy: Proxy) -> ProxySettings:"""- # remove max_shape from criteria+ # remove max_shape from criteriacriteria = proxy.get("criteria", {}).copy()criteria.pop("max_shape", None)diff --git a/scrapegraphai/utils/research_web.py b/scrapegraphai/utils/research_web.pyindex 7e978ffd..dcd168f1 100644--- a/scrapegraphai/utils/research_web.py+++ b/scrapegraphai/utils/research_web.py@@ -45,7 +45,8 @@ def search_on_web(query: str, search_engine: str = "Google",elif search_engine.lower() == "bing":headers = {- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"+ "User-Agent": """Mozilla/5.0 (Windows NT 10.0; Win64; x64)+ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"""}search_url = f"https://www.bing.com/search?q={query}"response = requests.get(search_url, headers=headers)diff --git a/scrapegraphai/utils/screenshot_scraping/screenshot_preparation.py b/scrapegraphai/utils/screenshot_scraping/screenshot_preparation.pyindex 6bbc562f..394b02fb 100644--- a/scrapegraphai/utils/screenshot_scraping/screenshot_preparation.py+++ b/scrapegraphai/utils/screenshot_scraping/screenshot_preparation.py@@ -20,15 +20,16 @@ async def take_screenshot(url: str, save_path: str = None, quality: int = 100):try:from PIL import Imageexcept:- raise ImportError("The dependencies for screenshot scraping are not installed. Please install them using `pip install scrapegraphai[screenshot_scraper]`.")+ raise ImportError("""The dependencies for screenshot scraping are not installed.+ Please install them using `pip install scrapegraphai[screenshot_scraper]`.""")async with async_playwright() as p:browser = await p.chromium.launch(headless=True)page = await browser.new_page()await page.goto(url)- image_bytes = await page.screenshot(path=save_path,- type="jpeg",- full_page=True,+ image_bytes = await page.screenshot(path=save_path,+ type="jpeg",+ full_page=True,quality=quality)await browser.close()return Image.open(BytesIO(image_bytes))@@ -48,7 +49,8 @@ def select_area_with_opencv(image):import cv2 as cvfrom PIL import ImageGrabexcept ImportError:- raise ImportError("The dependencies for screenshot scraping are not installed. Please install them using `pip install scrapegraphai[screenshot_scraper]`.")+ raise ImportError("""The dependencies for screenshot scraping are not installed.+ Please install them using `pip install scrapegraphai[screenshot_scraper]`.""")fullscreen_screenshot = ImageGrab.grab()@@ -129,7 +131,8 @@ def select_area_with_ipywidget(image):from ipywidgets import interact, IntSliderimport ipywidgets as widgetsexcept:- raise ImportError("The dependencies for screenshot scraping are not installed. Please install them using `pip install scrapegraphai[screenshot_scraper]`.")+ raise ImportError("""The dependencies for screenshot scraping are not installed.+ Please install them using `pip install scrapegraphai[screenshot_scraper]`.""")from PIL import Image@@ -192,7 +195,7 @@ def select_area_with_ipywidget(image):interact(update_plot, top_bottom=top_bottom_slider,left_right=left_right_slider, image_size=image_size_bt)-+return left_right_slider, top_bottom_slider@@ -205,14 +208,16 @@ def crop_image(image, LEFT=None, TOP=None, RIGHT=None, BOTTOM=None, save_path:TOP (int, optional): The y-coordinate of the top edge of the crop area. Defaults to None.RIGHT (int, optional): The x-coordinate ofthe right edge of the crop area. Defaults to None.- BOTTOM (int, optional): The y-coordinate of the bottom edge of the crop area. Defaults to None.+ BOTTOM (int, optional): The y-coordinate of the+ bottom edge of the crop area. Defaults to None.save_path (str, optional): The path to save the cropped image. Defaults to None.Returns:PIL.Image: The cropped image.Notes:If any of the coordinates (LEFT, TOP, RIGHT, BOTTOM) is None,it will be set to the corresponding edge of the image.- If save_path is specified, the cropped image will be saved as a JPEG file at the specified path.+ If save_path is specified, the cropped image will be saved+ as a JPEG file at the specified path."""if LEFT is None:diff --git a/scrapegraphai/utils/split_text_into_chunks.py b/scrapegraphai/utils/split_text_into_chunks.pyindex 73b2856b..22204e40 100644--- a/scrapegraphai/utils/split_text_into_chunks.py+++ b/scrapegraphai/utils/split_text_into_chunks.py@@ -2,10 +2,11 @@split_text_into_chunks module"""from typing import List-from .tokenizer import num_tokens_calculus # Import the new tokenizing functionfrom langchain_core.language_models.chat_models import BaseChatModel+from .tokenizer import num_tokens_calculus-def split_text_into_chunks(text: str, chunk_size: int, model: BaseChatModel, use_semchunk=True) -> List[str]:+def split_text_into_chunks(text: str, chunk_size: int,+ model: BaseChatModel, use_semchunk=True) -> List[str]:"""Splits the text into chunks based on the number of tokens.@@ -30,8 +31,7 @@ def split_text_into_chunks(text: str, chunk_size: int, model: BaseChatModel, usememoize=False)return chunks- else:-+ else:tokens = num_tokens_calculus(text, model)if tokens <= chunk_size:diff --git a/scrapegraphai/utils/tokenizer.py b/scrapegraphai/utils/tokenizer.pyindex 2e20a244..78006dda 100644--- a/scrapegraphai/utils/tokenizer.py+++ b/scrapegraphai/utils/tokenizer.py@@ -8,7 +8,9 @@ from langchain_mistralai import ChatMistralAIfrom langchain_core.language_models.chat_models import BaseChatModeldef num_tokens_calculus(string: str, llm_model: BaseChatModel) -> int:- """Returns the number of tokens in a text string."""+ """+ Returns the number of tokens in a text string.+ """if isinstance(llm_model, ChatOpenAI):from .tokenizers.tokenizer_openai import num_tokens_openai