repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
Scrapegraph-ai | tests/fixtures/helpers.py | .py | """
Test utilities and helpers for ScrapeGraphAI tests.
This module provides:
- Assertion helpers
- Data validation utilities
- Mock response builders
- Test data generators
"""
import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from unittest.mock import Mock
# ================... | 421 | 11,244 |
Scrapegraph-ai | tests/fixtures/mock_server/server.py | .py | """
Mock HTTP server for consistent testing without external dependencies.
This server provides:
- Static HTML pages with predictable content
- JSON/XML/CSV endpoints
- Rate limiting simulation
- Error condition simulation
- Dynamic content generation
"""
import json
import time
from http.server import BaseHTTPReques... | 347 | 11,702 |
Scrapegraph-ai | tests/nodes/search_link_node_test.py | .py | from unittest.mock import patch
import pytest
from langchain_ollama import ChatOllama
from scrapegraphai.nodes import SearchLinkNode
@pytest.fixture
def setup():
"""
Setup the SearchLinkNode and initial state for testing.
"""
# Define the configuration for the graph
graph_config = {
"llm... | 64 | 1,986 |
Scrapegraph-ai | tests/nodes/search_internet_node_test.py | .py | import unittest
from langchain_ollama import ChatOllama
from scrapegraphai.nodes import SearchInternetNode
class TestSearchInternetNode(unittest.TestCase):
def setUp(self):
# Configuration for the graph
self.graph_config = {
"llm": {"model": "llama3", "temperature": 0, "streaming": T... | 56 | 1,661 |
Scrapegraph-ai | tests/nodes/fetch_node_test.py | .py | from langchain_core.documents import Document
from scrapegraphai.nodes import FetchNode
def test_fetch_html(mocker):
title = "ScrapeGraph AI"
link_url = "https://github.com/VinciGit00/Scrapegraph-ai"
img_url = "https://raw.githubusercontent.com/VinciGit00/Scrapegraph-ai/main/docs/assets/scrapegraphai_log... | 77 | 2,191 |
Scrapegraph-ai | tests/nodes/robot_node_test.py | .py | from unittest.mock import MagicMock
import pytest
from scrapegraphai.nodes import RobotsNode
@pytest.fixture
def mock_llm_model():
mock_model = MagicMock()
mock_model.model = "ollama/llama3"
mock_model.__call__ = MagicMock(return_value=["yes"])
return mock_model
@pytest.fixture
def robots_node(moc... | 85 | 2,370 |
Scrapegraph-ai | scrapegraphai/__init__.py | .py | """
__init__.py file for scrapegraphai folder
"""
from .utils.logging import get_logger, set_verbosity_info
logger = get_logger(__name__)
set_verbosity_info()
| 9 | 161 |
Scrapegraph-ai | scrapegraphai/docloaders/scrape_do.py | .py | """
Scrape_do module
"""
import os
import urllib.parse
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def scrape_do_fetch(
token, target_url, use_proxy=False, geoCode=None, super_proxy=False
):
"""
Fetches the IP address of the machine associated with... | 51 | 1,644 |
Scrapegraph-ai | scrapegraphai/docloaders/plasmate.py | .py | """
PlasmateLoader — lightweight page fetcher using Plasmate (https://github.com/plasmate-labs/plasmate).
Plasmate is an open-source Rust browser engine that outputs a Structured Object Model (SOM)
instead of raw HTML. It requires no Chrome process, uses ~64MB RAM per session vs ~300MB,
and delivers 10-100x fewer toke... | 204 | 7,659 |
Scrapegraph-ai | scrapegraphai/docloaders/browser_base.py | .py | """
browserbase integration module
"""
import asyncio
from typing import List
def browser_base_fetch(
api_key: str,
project_id: str,
link: List[str],
text_content: bool = True,
async_mode: bool = False,
) -> List[str]:
"""
BrowserBase Fetch
This module provides an interface to the Br... | 62 | 1,784 |
Scrapegraph-ai | scrapegraphai/docloaders/__init__.py | .py | """
This module handles document loading functionalities for the ScrapeGraphAI application.
Note: ChromiumLoader and PlasmateLoader are lazy-imported to avoid triggering
torchcodec/FFmpeg DLL loading at import time (sentence_transformers -> torchcodec chain).
"""
from .browser_base import browser_base_fetch
from .scr... | 31 | 817 |
Scrapegraph-ai | scrapegraphai/docloaders/chromium.py | .py | import asyncio
from typing import Any, AsyncIterator, Iterator, List, Optional, Union
import aiohttp
import async_timeout
from langchain_core.documents import Document
from ..utils import Proxy, dynamic_import, get_logger, parse_or_search_proxy
logger = get_logger("web-loader")
class ChromiumLoader:
"""Scrapes... | 491 | 21,336 |
Scrapegraph-ai | scrapegraphai/graphs/xml_scraper_graph.py | .py | """
XMLScraperGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateAnswerNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class XMLScraperGraph(AbstractGraph):
"""
XMLScraperGraph is a scraping pipeline that... | 99 | 3,252 |
Scrapegraph-ai | scrapegraphai/graphs/csv_scraper_graph.py | .py | """
Module for creating the smart scraper
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateAnswerCSVNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class CSVScraperGraph(AbstractGraph):
"""
A class representing a gr... | 104 | 3,793 |
Scrapegraph-ai | scrapegraphai/graphs/document_scraper_multi_graph.py | .py | """
DocumentScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .do... | 105 | 3,437 |
Scrapegraph-ai | scrapegraphai/graphs/screenshot_scraper_graph.py | .py | """
ScreenshotScraperGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchScreenNode, GenerateAnswerFromImageNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class ScreenshotScraperGraph(AbstractGraph):
"""
A graph instan... | 83 | 2,550 |
Scrapegraph-ai | scrapegraphai/graphs/omni_scraper_graph.py | .py | """
This module implements the Omni Scraper Graph for the ScrapeGraphAI application.
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..models import OpenAIImageToText
from ..nodes import FetchNode, GenerateAnswerOmniNode, ImageToTextNode, ParseNode
from .abstract_graph import AbstractGraph
... | 136 | 4,593 |
Scrapegraph-ai | scrapegraphai/graphs/document_scraper_graph.py | .py | """
This module implements the Document Scraper Graph for the ScrapeGraphAI application.
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateAnswerNode, ParseNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class DocumentScrape... | 115 | 3,933 |
Scrapegraph-ai | scrapegraphai/graphs/xml_scraper_multi_graph.py | .py | """
XMLScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .xml_scr... | 103 | 3,319 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_lite_graph.py | .py | """
SmartScraperGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, ParseNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class SmartScraperLiteGraph(AbstractGraph):
"""
SmartScraperLiteGraph is a scraping pipeline... | 104 | 3,274 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_multi_batch_graph.py | .py | """
SmartScraperMultiBatchGraph Module
A scraping pipeline that uses the OpenAI Batch API for LLM calls,
providing 50% cost savings compared to real-time API calls.
"""
import asyncio
from copy import deepcopy
from typing import Dict, List, Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode... | 217 | 7,728 |
Scrapegraph-ai | scrapegraphai/graphs/__init__.py | .py | """
This module defines the graph structures and related functionalities for the ScrapeGraphAI application.
"""
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .code_generator_graph import CodeGeneratorGraph
from .csv_scraper_graph import CSVScraperGraph
from .csv_scraper_multi_graph i... | 65 | 2,366 |
Scrapegraph-ai | scrapegraphai/graphs/markdownify_graph.py | .py | """
markdownify_graph module
"""
from typing import Dict, List, Optional, Tuple
from ..nodes import (
FetchNode,
MarkdownifyNode,
)
from .base_graph import BaseGraph
class MarkdownifyGraph(BaseGraph):
"""
A graph that converts HTML content to Markdown format.
This graph takes a URL or HTML cont... | 82 | 2,290 |
Scrapegraph-ai | scrapegraphai/graphs/omni_search_graph.py | .py | """
OmniSearchGraph Module
"""
from copy import deepcopy
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode, SearchInternetNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from... | 110 | 3,688 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_graph.py | .py | """
SmartScraperGraph Module
"""
import logging
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import (
ConditionalNode,
FetchNode,
GenerateAnswerNode,
ParseNode,
ReasoningNode,
)
from ..prompts import REGEN_ADDITIONAL_INFO
from .abstract_graph import AbstractGraph
... | 293 | 10,336 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_multi_graph.py | .py | """
SmartScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .smart... | 112 | 3,720 |
Scrapegraph-ai | scrapegraphai/graphs/base_graph.py | .py | """
base_graph module
"""
import time
import warnings
from typing import Tuple
from ..telemetry import log_graph_execution
from ..utils import CustomLLMCallbackManager
from ..utils.logging import get_logger
logger = get_logger(__name__)
# ANSI escape sequence for hyperlink
CLICKABLE_URL = "\033]8;;https://scrapegra... | 397 | 14,365 |
Scrapegraph-ai | scrapegraphai/graphs/script_creator_graph.py | .py | """
ScriptCreatorGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateScraperNode, ParseNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class ScriptCreatorGraph(AbstractGraph):
"""
ScriptCreatorGraph define... | 126 | 4,077 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_multi_lite_graph.py | .py | """
SmartScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .smart... | 106 | 3,752 |
Scrapegraph-ai | scrapegraphai/graphs/csv_scraper_multi_graph.py | .py | """
CSVScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .csv_scr... | 104 | 3,286 |
Scrapegraph-ai | scrapegraphai/graphs/speech_graph.py | .py | """
SpeechGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..models import OpenAITextToSpeech
from ..nodes import FetchNode, GenerateAnswerNode, ParseNode, TextToSpeechNode
from ..utils.logging import get_logger
from ..utils.save_audio_from_bytes import save_audio_from_bytes
fro... | 121 | 4,318 |
Scrapegraph-ai | scrapegraphai/graphs/search_link_graph.py | .py | """
SearchLinkGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, SearchLinkNode, SearchLinksWithContext
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class SearchLinkGraph(AbstractGraph):
"""
SearchLinkGraph is a sc... | 104 | 3,536 |
Scrapegraph-ai | scrapegraphai/graphs/json_scraper_multi_graph.py | .py | """
JSONScraperMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
from .json_s... | 105 | 3,329 |
Scrapegraph-ai | scrapegraphai/graphs/search_graph.py | .py | """
SearchGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeAnswersNode, SearchInternetNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
fr... | 129 | 4,415 |
Scrapegraph-ai | scrapegraphai/graphs/smart_scraper_multi_concat_graph.py | .py | """
SmartScraperMultiCondGraph Module with ConditionalNode
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import (
ConcatAnswersNode,
ConditionalNode,
GraphIteratorNode,
MergeAnswersNode,
)
from ..utils.copy import safe_deepcopy
from ... | 129 | 4,243 |
Scrapegraph-ai | scrapegraphai/graphs/json_scraper_graph.py | .py | """
JSONScraperGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateAnswerNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class JSONScraperGraph(AbstractGraph):
"""
JSONScraperGraph defines a scraping pipel... | 100 | 3,157 |
Scrapegraph-ai | scrapegraphai/graphs/depth_search_graph.py | .py | """
depth search graph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import (
DescriptionNode,
FetchNodeLevelK,
GenerateAnswerNodeKLevel,
ParseNodeDepthK,
RAGNode,
)
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class Dept... | 157 | 5,173 |
Scrapegraph-ai | scrapegraphai/graphs/code_generator_graph.py | .py | """
SmartScraperGraph Module
"""
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import (
FetchNode,
GenerateAnswerNode,
GenerateCodeNode,
HtmlAnalyzerNode,
ParseNode,
PromptRefinerNode,
)
from ..utils.save_code_to_file import save_code_to_file
from .abstract_gra... | 193 | 6,629 |
Scrapegraph-ai | scrapegraphai/graphs/script_creator_multi_graph.py | .py | """
ScriptCreatorMultiGraph Module
"""
from copy import deepcopy
from typing import List, Optional, Type
from pydantic import BaseModel
from ..nodes import GraphIteratorNode, MergeGeneratedScriptsNode
from ..utils.copy import safe_deepcopy
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
f... | 100 | 3,429 |
Scrapegraph-ai | scrapegraphai/graphs/abstract_graph.py | .py | """
AbstractGraph Module
"""
import asyncio
import uuid
import warnings
from abc import ABC, abstractmethod
from typing import Optional, Type
from langchain.chat_models import init_chat_model
from langchain_core.rate_limiters import InMemoryRateLimiter
from pydantic import BaseModel
from ..helpers import models_toke... | 345 | 11,804 |
Scrapegraph-ai | scrapegraphai/builders/__init__.py | .py | """
This module contains the builders for constructing various components in the ScrapeGraphAI application.
"""
from .graph_builder import GraphBuilder
__all__ = [
"GraphBuilder",
]
| 10 | 188 |
Scrapegraph-ai | scrapegraphai/builders/graph_builder.py | .py | """
GraphBuilder Module
"""
from langchain_classic.chains import create_extraction_chain
from langchain_community.chat_models import ErnieBotChat
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from ..helpers import graph_schema, nodes_metadata
class GraphBuilder:
"... | 182 | 6,820 |
Scrapegraph-ai | scrapegraphai/telemetry/telemetry.py | .py | import configparser
import functools
import importlib.metadata
import json
import logging
import os
import threading
import uuid
from typing import Callable, Dict
from urllib import request
VERSION = importlib.metadata.version("scrapegraphai")
TRACK_URL = "https://sgai-oss-tracing.onrender.com/v1/telemetry"
TIMEOUT = 2... | 204 | 5,566 |
Scrapegraph-ai | scrapegraphai/telemetry/__init__.py | .py | """
This module contains the telemetry module for the scrapegraphai package.
"""
from .telemetry import disable_telemetry, log_event, log_graph_execution
__all__ = [
"disable_telemetry",
"log_event",
"log_graph_execution",
]
| 12 | 239 |
Scrapegraph-ai | scrapegraphai/prompts/generate_answer_node_pdf_prompts.py | .py | """
Generate anwer node pdf prompt
"""
TEMPLATE_CHUNKS_PDF = """
You are a scraper and you have just scraped the
following content from a PDF.
You are now asked to answer a user question about the content you have scraped.\n
The PDF is big so I am giving you one chunk at the time to be merged later with the other chu... | 45 | 2,225 |
Scrapegraph-ai | scrapegraphai/prompts/get_probable_tags_node_prompts.py | .py | """
Get probable tags node prompts
"""
TEMPLATE_GET_PROBABLE_TAGS = """
PROMPT:
You are a website scraper that knows all the types of html tags.
You are now asked to list all the html tags where you think you can find the information of the asked question.\n
INSTRUCTIONS: {format_instructions... | 13 | 441 |
Scrapegraph-ai | scrapegraphai/prompts/prompt_refiner_node_prompts.py | .py | """
Prompts refiner prompts helper
"""
TEMPLATE_REFINER = """
**Task**: Analyze the user's request and the provided JSON schema to clearly map the desired data extraction.\n
Break down the user's request into key components, and then explicitly connect these components to the
corresponding elements within the JSON sch... | 64 | 2,325 |
Scrapegraph-ai | scrapegraphai/prompts/search_internet_node_prompts.py | .py | """
Search internet node prompts helper
"""
TEMPLATE_SEARCH_INTERNET = """
PROMPT:
You are a search engine and you need to generate a search query based on the user's prompt. \n
Given the following user prompt, return a query that can be
used to search the internet for relevant information. \n
You should return only t... | 17 | 733 |
Scrapegraph-ai | scrapegraphai/prompts/merge_answer_node_prompts.py | .py | """
Merge answer node prompts
"""
TEMPLATE_COMBINED = """
You are a website scraper and you have just scraped some content from multiple websites.\n
You are now asked to provide an answer to a USER PROMPT based on the content you have scraped.\n
You need to merge the content from the different websites into a single a... | 17 | 847 |
Scrapegraph-ai | scrapegraphai/prompts/search_node_with_context_prompts.py | .py | """
Search node with context prompts helper
"""
TEMPLATE_SEARCH_WITH_CONTEXT_CHUNKS = """
You are a website scraper and you have just scraped the
following content from a website.
You are now asked to extract all the links that they have to do with the asked user question.\n
The website is big so I am giving you one c... | 25 | 1,024 |
Scrapegraph-ai | scrapegraphai/prompts/__init__.py | .py | """
__init__.py for the prompts folder
"""
from .generate_answer_node_csv_prompts import (
TEMPLATE_CHUKS_CSV,
TEMPLATE_MERGE_CSV,
TEMPLATE_NO_CHUKS_CSV,
)
from .generate_answer_node_omni_prompts import (
TEMPLATE_CHUNKS_OMNI,
TEMPLATE_MERGE_OMNI,
TEMPLATE_NO_CHUNKS_OMNI,
)
from .generate_answe... | 110 | 3,508 |
Scrapegraph-ai | scrapegraphai/prompts/html_analyzer_node_prompts.py | .py | """
HTML analysis prompts helper
"""
TEMPLATE_HTML_ANALYSIS = """
Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
**Initial Analysis**:... | 71 | 4,123 |
Scrapegraph-ai | scrapegraphai/prompts/generate_answer_node_csv_prompts.py | .py | """
Generate answer csv schema
"""
TEMPLATE_CHUKS_CSV = """
You are a scraper and you have just scraped the
following content from a csv.
You are now asked to answer a user question about the content you have scraped.\n
The csv is big so I am giving you one chunk at the time to be merged later with the other chunks.\n... | 40 | 1,812 |
Scrapegraph-ai | scrapegraphai/prompts/generate_code_node_prompts.py | .py | """
Generate code prompts helper
"""
TEMPLATE_INIT_CODE_GENERATION = """
**Task**: Create a Python function named `extract_data(html: str) -> dict()` using BeautifulSoup that extracts relevant information from the given HTML code string and returns it in a dictionary matching the Desired JSON Output Schema.
**User's ... | 213 | 6,192 |
Scrapegraph-ai | scrapegraphai/prompts/generate_answer_node_omni_prompts.py | .py | """
Generate answer node omni prompts helper
"""
TEMPLATE_CHUNKS_OMNI = """
You are a website scraper and you have just scraped the
following content from a website.
You are now asked to answer a user question about the content you have scraped.\n
The website is big so I am giving you one chunk at the time to be merge... | 44 | 2,107 |
Scrapegraph-ai | scrapegraphai/prompts/merge_generated_scripts_prompts.py | .py | """
merge_generated_scripts_prompts module
"""
TEMPLATE_MERGE_SCRIPTS_PROMPT = """
You are a python expert in web scraping and you have just generated multiple scripts to scrape different URLs.\n
The scripts are generated based on a user question and the content of the websites.\n
You need to create one single script ... | 16 | 792 |
Scrapegraph-ai | scrapegraphai/prompts/generate_answer_node_prompts.py | .py | """
Generate answer node prompts
"""
TEMPLATE_CHUNKS_MD = """
You are a website scraper and you have just scraped the
following content from a website converted in markdown format.
You are now asked to answer a user question about the content you have scraped.\n
The website is big so I am giving you one chunk at the t... | 93 | 4,877 |
Scrapegraph-ai | scrapegraphai/prompts/description_node_prompts.py | .py | """
This module contains prompts for description nodes in the ScrapeGraphAI application.
"""
DESCRIPTION_NODE_PROMPT = """
You are a scraper and you have just scraped the
following content from a website. \n
Please provide a description summary of maximum of 20 words. \n
CONTENT OF THE WEBSITE: {content}
"""
| 11 | 312 |
Scrapegraph-ai | scrapegraphai/prompts/robots_node_prompts.py | .py | """
Robot node prompts helper
"""
TEMPLATE_ROBOT = """
You are a website scraper and you need to scrape a website.
You need to check if the website allows scraping of the provided path. \n
You are provided with the robots.txt file of the website and you must reply if it is legit to scrape or not the website. \n
provid... | 17 | 719 |
Scrapegraph-ai | scrapegraphai/prompts/reasoning_node_prompts.py | .py | """
Reasoning prompts helper module
"""
TEMPLATE_REASONING = """
**Task**: Analyze the user's request and the provided JSON schema to guide an LLM in extracting information directly from a markdown file previously parsed froma a HTML file.
**User's Request**:
{user_input}
**Target JSON Schema**:
```json
{json_schema... | 73 | 3,031 |
Scrapegraph-ai | scrapegraphai/prompts/search_link_node_prompts.py | .py | """
Search link node prompts helper
"""
TEMPLATE_RELEVANT_LINKS = """
You are a website scraper and you have just scraped the following content from a website.
Content: {content}
Assume relevance broadly, including any links that might be related or potentially useful
in relation to the task.
Sort it in order of imp... | 28 | 675 |
Scrapegraph-ai | scrapegraphai/utils/convert_to_md.py | .py | """
convert_to_md module
"""
from urllib.parse import urlparse
import html2text
def convert_to_md(html: str, url: str = None) -> str:
"""Convert HTML to Markdown.
This function uses the html2text library to convert the provided HTML content to Markdown
format.
The function returns the converted Mark... | 37 | 961 |
Scrapegraph-ai | scrapegraphai/utils/copy.py | .py | """
copy module
"""
import copy
from typing import Any
class DeepCopyError(Exception):
"""
Custom exception raised when an object cannot be deep-copied.
"""
pass
def is_boto3_client(obj):
"""
Function for understanding if the script is using boto3 or not
"""
import sys
boto3_m... | 72 | 1,580 |
Scrapegraph-ai | scrapegraphai/utils/data_export.py | .py | """
data_export module
This module provides functions to export data to various file formats.
"""
import csv
import json
import xml.etree.ElementTree as ET
from typing import Any, Dict, List
from .logging import get_logger
logger = get_logger(__name__)
def export_to_json(data: List[Dict[str, Any]], filename: str) ... | 67 | 1,981 |
Scrapegraph-ai | scrapegraphai/utils/custom_callback.py | .py | """
Custom callback for LLM token usage statistics.
This module has been taken and modified from the OpenAI callback manager in langchian-community.
https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/callbacks/openai_info.py
"""
import threading
from contextlib import contextmana... | 194 | 6,563 |
Scrapegraph-ai | scrapegraphai/utils/logging.py | .py | """
A centralized logging system for any library.
This module provides functions to manage logging for a library. It includes
functions to get and set the verbosity level, add and remove handlers, and
control propagation. It also includes a function to set formatting for all
handlers bound to the root logger.
Source co... | 231 | 6,016 |
Scrapegraph-ai | scrapegraphai/utils/cleanup_html.py | .py | """
Module for minimizing the code
"""
import json
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup, Comment
from minify_html import minify
def extract_from_script_tags(soup):
script_content = []
for script in soup.find_all("script"):
content = script.string
if conte... | 175 | 5,382 |
Scrapegraph-ai | scrapegraphai/utils/code_error_analysis.py | .py | """
This module contains the functions that generate prompts for various types of code error analysis.
Functions:
- syntax_focused_analysis: Focuses on syntax-related errors in the generated code.
- execution_focused_analysis: Focuses on execution-related errors,
including generated code and HTML analysis.
- validatio... | 336 | 11,577 |
Scrapegraph-ai | scrapegraphai/utils/schema_trasform.py | .py | """
This utility function transforms the pydantic schema into a more comprehensible schema.
"""
def transform_schema(pydantic_schema):
"""
Transform the pydantic schema into a more comprehensible JSON schema.
Args:
pydantic_schema (dict): The pydantic schema.
Returns:
dict: The trans... | 54 | 2,238 |
Scrapegraph-ai | scrapegraphai/utils/llm_callback_manager.py | .py | """
This module provides a custom callback manager for LLM models.
Classes:
- CustomLLMCallbackManager: Manages exclusive access to callbacks for different types of LLM models.
"""
import threading
from contextlib import contextmanager
from langchain_aws import ChatBedrock
from langchain_community.callbacks.manager ... | 77 | 2,698 |
Scrapegraph-ai | scrapegraphai/utils/cleanup_code.py | .py | """
This utility function extracts the code from a given string.
"""
import re
def extract_code(code: str) -> str:
"""
Module for extracting code
"""
pattern = r"```(?:python)?\n(.*?)```"
match = re.search(pattern, code, re.DOTALL)
return match.group(1) if match else code
| 17 | 302 |
Scrapegraph-ai | scrapegraphai/utils/__init__.py | .py | """
__init__.py file for utils folder
"""
from .cleanup_code import extract_code
from .cleanup_html import cleanup_html, reduce_html
from .code_error_analysis import (
execution_focused_analysis,
semantic_focused_analysis,
syntax_focused_analysis,
validation_focused_analysis,
)
from .code_error_correct... | 118 | 3,370 |
Scrapegraph-ai | scrapegraphai/utils/research_web.py | .py | """
research_web module for web searching across different search engines with improved
error handling, validation, and security features.
"""
import random
import re
import time
from functools import wraps
from typing import Dict, List, Optional, Union
import requests
from bs4 import BeautifulSoup
from pydantic impo... | 484 | 14,667 |
Scrapegraph-ai | scrapegraphai/utils/parse_state_keys.py | .py | """
Parse_state_key module
"""
import re
def parse_expression(expression, state: dict) -> list:
"""
Parses a complex boolean expression involving state keys.
Args:
expression (str): The boolean expression to parse.
state (dict): Dictionary of state keys used to evaluate the expression.
... | 104 | 3,512 |
Scrapegraph-ai | scrapegraphai/utils/model_costs.py | .py | """
Cost for 1k tokens in input
"""
MODEL_COST_PER_1K_TOKENS_INPUT = {
### MistralAI
# General Purpose
"open-mistral-nemo": 0.00015,
"open-mistral-nemo-2407": 0.00015,
"mistral-large": 0.002,
"mistral-large-2407": 0.002,
"mistral-small": 0.0002,
"mistral-small-2409": 0.0002,
# Speci... | 187 | 5,864 |
Scrapegraph-ai | scrapegraphai/utils/sys_dynamic_import.py | .py | """
high-level module for dynamic importing of python modules at runtime
source code inspired by https://gist.github.com/DiTo97/46f4b733396b8d7a8f1d4d22db902cfc
"""
import importlib.util
import sys
import typing
if typing.TYPE_CHECKING:
import types
def srcfile_import(modpath: str, modname: str) -> "types.Modu... | 67 | 1,631 |
Scrapegraph-ai | scrapegraphai/utils/proxy_rotation.py | .py | """
Module for rotating proxies
"""
import ipaddress
import random
import re
from typing import List, Optional, Set, TypedDict
from urllib.parse import urlparse
import requests
from fp.errors import FreeProxyException
from fp.fp import FreeProxy
class ProxyBrokerCriteria(TypedDict, total=False):
"""
proxy b... | 212 | 5,572 |
Scrapegraph-ai | scrapegraphai/utils/batch_api.py | .py | """
OpenAI Batch API utility functions.
Provides helpers for creating, polling, and retrieving results
from the OpenAI Batch API, enabling 50% cost savings on LLM calls
when real-time responses are not needed.
Reference: https://platform.openai.com/docs/guides/batch
"""
import io
import json
import logging
import ti... | 317 | 9,073 |
Scrapegraph-ai | scrapegraphai/utils/output_parser.py | .py | """
Functions to retrieve the correct output parser and format instructions for the LLM model.
"""
from typing import Any, Callable, Dict, Type, Union
from langchain_core.output_parsers import JsonOutputParser
from pydantic import BaseModel as BaseModelV2
from pydantic.v1 import BaseModel as BaseModelV1
def get_str... | 101 | 2,685 |
Scrapegraph-ai | scrapegraphai/utils/dict_content_compare.py | .py | """
This module contains utility functions for comparing the content of two dictionaries.
Functions:
- normalize_dict: Recursively normalizes the values in a dictionary,
converting strings to lowercase and stripping whitespace.
- normalize_list: Recursively normalizes the values in a list,
converting strings to lowerc... | 79 | 2,380 |
Scrapegraph-ai | scrapegraphai/utils/save_audio_from_bytes.py | .py | """
This utility function saves the byte response as an audio file.
"""
from pathlib import Path
from typing import Union
def save_audio_from_bytes(byte_response: bytes, output_path: Union[str, Path]) -> None:
"""
Saves the byte response as an audio file to the specified path.
Args:
byte_respons... | 29 | 845 |
Scrapegraph-ai | scrapegraphai/utils/prettify_exec_info.py | .py | """
Prettify the execution information of the graph.
"""
from typing import Union
def prettify_exec_info(
complete_result: list[dict], as_string: bool = True
) -> Union[str, list[dict]]:
"""
Formats the execution information of a graph showing node statistics.
Args:
complete_result (list[dic... | 52 | 1,581 |
Scrapegraph-ai | scrapegraphai/utils/code_error_correction.py | .py | """
This module contains the functions for code generation to correct different types of errors.
Functions:
- syntax_focused_code_generation: Generates corrected code based on syntax error analysis.
- execution_focused_code_generation: Generates corrected code based on execution error analysis.
- validation_focused_co... | 320 | 10,761 |
Scrapegraph-ai | scrapegraphai/utils/tokenizer.py | .py | """
Module for counting tokens and splitting text into chunks
"""
from .tokenizers.tokenizer_openai import num_tokens_openai
def num_tokens_calculus(string: str) -> int:
"""
Returns the number of tokens in a text string.
"""
num_tokens_fn = num_tokens_openai
num_tokens = num_tokens_fn(string)
... | 17 | 341 |
Scrapegraph-ai | scrapegraphai/utils/save_code_to_file.py | .py | """
save_code_to_file module
"""
def save_code_to_file(code: str, filename: str) -> None:
"""
Saves the generated code to a Python file.
Args:
code (str): The generated code to be saved.
filename (str): name of the output file
"""
with open(filename, "w") as file:
file.wri... | 16 | 329 |
Scrapegraph-ai | scrapegraphai/utils/split_text_into_chunks.py | .py | """
split_text_into_chunks module
"""
from typing import List
from .tokenizer import num_tokens_calculus
def split_text_into_chunks(text: str, chunk_size: int, use_semchunk=True) -> List[str]:
"""
Splits the text into chunks based on the number of tokens.
Args:
text (str): The text to split.
... | 60 | 1,492 |
Scrapegraph-ai | scrapegraphai/utils/screenshot_scraping/screenshot_preparation.py | .py | """
screenshot_preparation module
"""
from io import BytesIO
import numpy as np
from playwright.async_api import async_playwright
from ..logging import get_logger
logger = get_logger(__name__)
async def take_screenshot(url: str, save_path: str = None, quality: int = 100):
"""
Takes a screenshot of a webpa... | 257 | 8,410 |
Scrapegraph-ai | scrapegraphai/utils/screenshot_scraping/text_detection.py | .py | """
text_detection_module
"""
def detect_text(image, languages: list = ["en"]):
"""
Detects and extracts text from a given image.
Parameters:
image (PIL Image): The input image to extract text from.
languages (list): A list of languages to detect text in. Defaults to ["en"].
... | 40 | 1,581 |
Scrapegraph-ai | scrapegraphai/utils/screenshot_scraping/__init__.py | .py | from .screenshot_preparation import (
crop_image,
select_area_with_ipywidget,
select_area_with_opencv,
take_screenshot,
)
from .text_detection import detect_text
__all__ = [
"crop_image",
"select_area_with_ipywidget",
"select_area_with_opencv",
"take_screenshot",
"detect_text",
]
| 16 | 318 |
Scrapegraph-ai | scrapegraphai/utils/tokenizers/tokenizer_openai.py | .py | """
Tokenization utilities for OpenAI models
"""
import tiktoken
from ..logging import get_logger
def num_tokens_openai(text: str) -> int:
"""
Estimate the number of tokens in a given text using OpenAI's tokenization method,
adjusted for different OpenAI models.
Args:
text (str): The text t... | 30 | 638 |
Scrapegraph-ai | scrapegraphai/utils/tokenizers/tokenizer_mistral.py | .py | """
Tokenization utilities for Mistral models
"""
from langchain_core.language_models.chat_models import BaseChatModel
from ..logging import get_logger
def num_tokens_mistral(text: str, llm_model: BaseChatModel) -> int:
"""
Estimate the number of tokens in a given text using Mistral's tokenization method,
... | 56 | 1,690 |
Scrapegraph-ai | scrapegraphai/utils/tokenizers/tokenizer_ollama.py | .py | """
Tokenization utilities for Ollama models
"""
from langchain_core.language_models.chat_models import BaseChatModel
from ..logging import get_logger
def num_tokens_ollama(text: str, llm_model: BaseChatModel) -> int:
"""
Estimate the number of tokens in a given text using Ollama's tokenization method,
... | 31 | 870 |
Scrapegraph-ai | scrapegraphai/models/openai_itt.py | .py | """
OpenAIImageToText Module
"""
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
class OpenAIImageToText(ChatOpenAI):
"""
A wrapper for the OpenAIImageToText class that provides default configuration
and could be extended with additional methods if needed.
Ar... | 48 | 1,302 |
Scrapegraph-ai | scrapegraphai/models/nvidia.py | .py | """
NVIDIA Module
"""
class Nvidia:
"""
A wrapper for the ChatNVIDIA class that provides default configuration
and could be extended with additional methods if needed.
Note: This class uses __new__ instead of __init__ because langchain_nvidia_ai_endpoints
is an optional dependency. We cannot inhe... | 33 | 1,137 |
Scrapegraph-ai | scrapegraphai/models/atlascloud.py | .py | """
Atlas Cloud Module
"""
from langchain_openai import ChatOpenAI
class AtlasCloud(ChatOpenAI):
"""
A wrapper for ChatOpenAI configured for Atlas Cloud's OpenAI-compatible
LLM API.
Args:
llm_config (dict): Configuration parameters for the language model.
"""
def __init__(self, **ll... | 23 | 547 |
Scrapegraph-ai | scrapegraphai/models/xai.py | .py | """
xAI Grok Module
"""
from langchain_openai import ChatOpenAI
class XAI(ChatOpenAI):
"""
A wrapper for the ChatOpenAI class (xAI uses an OpenAI-compatible API) that
provides default configuration and could be extended with additional methods
if needed.
Args:
llm_config (dict): Configur... | 24 | 615 |
Scrapegraph-ai | scrapegraphai/models/__init__.py | .py | """
This module contains the model definitions used in the ScrapeGraphAI application.
"""
from .atlascloud import AtlasCloud
from .clod import CLoD
from .deepseek import DeepSeek
from .minimax import MiniMax
from .nvidia import Nvidia
from .oneapi import OneApi
from .openai_itt import OpenAIImageToText
from .openai_tt... | 16 | 496 |
Scrapegraph-ai | scrapegraphai/models/openai_tts.py | .py | """
OpenAITextToSpeech Module
"""
from openai import OpenAI
class OpenAITextToSpeech:
"""
Implements a text-to-speech model using the OpenAI API.
Attributes:
client (OpenAI): The OpenAI client used to interact with the API.
model (str): The model to use for text-to-speech conversion.
... | 43 | 1,223 |
Scrapegraph-ai | scrapegraphai/models/oneapi.py | .py | """
OneAPI Module
"""
from langchain_openai import ChatOpenAI
class OneApi(ChatOpenAI):
"""
A wrapper for the OneApi class that provides default configuration
and could be extended with additional methods if needed.
Args:
llm_config (dict): Configuration parameters for the language model.
... | 21 | 509 |
Scrapegraph-ai | scrapegraphai/models/clod.py | .py | """
CLōD Module
"""
from langchain_openai import ChatOpenAI
class CLoD(ChatOpenAI):
"""
A wrapper for the ChatOpenAI class (CLōD uses an OpenAI-like API) that
provides default configuration and could be extended with additional methods
if needed.
Args:
llm_config (dict): Configuration pa... | 24 | 612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.