Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Fix whitespace formatting errors (W291, W292, W293)
copilot-swe-agent[bot]7cb49e450ae7
diff --git a/scrapegraphai/graphs/markdownify_graph.py b/scrapegraphai/graphs/markdownify_graph.pyindex 78d33b12..0bf2804c 100644--- a/scrapegraphai/graphs/markdownify_graph.py+++ b/scrapegraphai/graphs/markdownify_graph.py@@ -80,4 +80,4 @@ class MarkdownifyGraph(BaseGraph):- Dictionary with the markdown result in the "markdown" key- List of execution logs"""- return super().execute(initial_state)\ No newline at end of file+ return super().execute(initial_state)diff --git a/scrapegraphai/helpers/models_tokens.py b/scrapegraphai/helpers/models_tokens.pyindex c700a6dc..9d531e9a 100644--- a/scrapegraphai/helpers/models_tokens.py+++ b/scrapegraphai/helpers/models_tokens.py@@ -32,7 +32,6 @@ models_tokens = {"o1-preview": 128000,"o1-mini": 128000,"o1": 128000,- "gpt-4.5-preview": 128000,"o3-mini": 200000,},"azure_openai": {diff --git a/scrapegraphai/models/xai.py b/scrapegraphai/models/xai.pyindex 86969483..065af3ed 100644--- a/scrapegraphai/models/xai.py+++ b/scrapegraphai/models/xai.py@@ -19,4 +19,4 @@ class XAI(ChatOpenAI):llm_config["openai_api_key"] = llm_config.pop("api_key")llm_config["openai_api_base"] = "https://api.x.ai/v1"- super().__init__(**llm_config)\ No newline at end of file+ super().__init__(**llm_config)diff --git a/scrapegraphai/nodes/markdownify_node.py b/scrapegraphai/nodes/markdownify_node.pyindex 2119908a..da1407a4 100644--- a/scrapegraphai/nodes/markdownify_node.py+++ b/scrapegraphai/nodes/markdownify_node.py@@ -64,4 +64,4 @@ class MarkdownifyNode(BaseNode):# Update state with markdown contentstate.update({self.output[0]: markdown_content})- return state\ No newline at end of file+ return statediff --git a/scrapegraphai/utils/code_error_analysis.py b/scrapegraphai/utils/code_error_analysis.pyindex d2c6a42d..e799aff6 100644--- a/scrapegraphai/utils/code_error_analysis.py+++ b/scrapegraphai/utils/code_error_analysis.py@@ -80,10 +80,10 @@ class ValidationAnalysisState(CodeAnalysisState):def get_optimal_analysis_template(error_type: str) -> str:"""Returns the optimal prompt template based on the error type.-+Args:error_type (str): Type of error to analyze.-+Returns:str: The prompt template text."""@@ -106,10 +106,10 @@ def syntax_focused_analysis(state: Dict[str, Any], llm_model) -> str:Returns:str: The result of the syntax error analysis.-+Raises:InvalidStateError: If state is missing required keys.-+Example:>>> state = {'generated_code': 'print("Hello World")',@@ -123,24 +123,24 @@ def syntax_focused_analysis(state: Dict[str, Any], llm_model) -> str:generated_code=state.get("generated_code", ""),errors=state.get("errors", {}))-+# Check if syntax errors existif "syntax" not in validated_state.errors:raise InvalidStateError("No syntax errors found in state dictionary")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_analysis_template("syntax"),input_variables=["generated_code", "errors"])chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"generated_code": validated_state.generated_code,"errors": validated_state.errors["syntax"]})-+except KeyError as e:raise InvalidStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -157,10 +157,10 @@ def execution_focused_analysis(state: Dict[str, Any], llm_model) -> str:Returns:str: The result of the execution error analysis.-+Raises:InvalidStateError: If state is missing required keys.-+Example:>>> state = {'generated_code': 'print(x)',@@ -178,14 +178,14 @@ def execution_focused_analysis(state: Dict[str, Any], llm_model) -> str:html_code=state.get("html_code", ""),html_analysis=state.get("html_analysis", ""))-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_analysis_template("execution"),input_variables=["generated_code", "errors", "html_code", "html_analysis"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"generated_code": validated_state.generated_code,@@ -193,7 +193,7 @@ def execution_focused_analysis(state: Dict[str, Any], llm_model) -> str:"html_code": validated_state.html_code,"html_analysis": validated_state.html_analysis,})-+except KeyError as e:raise InvalidStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -211,10 +211,10 @@ def validation_focused_analysis(state: Dict[str, Any], llm_model) -> str:Returns:str: The result of the validation error analysis.-+Raises:InvalidStateError: If state is missing required keys.-+Example:>>> state = {'generated_code': 'return {"name": "John"}',@@ -232,14 +232,14 @@ def validation_focused_analysis(state: Dict[str, Any], llm_model) -> str:json_schema=state.get("json_schema", {}),execution_result=state.get("execution_result", {}))-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_analysis_template("validation"),input_variables=["generated_code", "errors", "json_schema", "execution_result"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"generated_code": validated_state.generated_code,@@ -247,7 +247,7 @@ def validation_focused_analysis(state: Dict[str, Any], llm_model) -> str:"json_schema": validated_state.json_schema,"execution_result": validated_state.execution_result,})-+except KeyError as e:raise InvalidStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -268,10 +268,10 @@ def semantic_focused_analysis(Returns:str: The result of the semantic error analysis.-+Raises:InvalidStateError: If state or comparison_result is missing required keys.-+Example:>>> state = {'generated_code': 'def add(a, b): return a + b'@@ -288,28 +288,28 @@ def semantic_focused_analysis(generated_code=state.get("generated_code", ""),errors=state.get("errors", {}))-+# Validate comparison_resultif "differences" not in comparison_result:raise InvalidStateError("comparison_result missing 'differences' key")if "explanation" not in comparison_result:raise InvalidStateError("comparison_result missing 'explanation' key")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_analysis_template("semantic"),input_variables=["generated_code", "differences", "explanation"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated inputsreturn chain.invoke({"generated_code": validated_state.generated_code,"differences": json.dumps(comparison_result["differences"], indent=2),"explanation": comparison_result["explanation"],})-+except KeyError as e:raise InvalidStateError(f"Missing required key: {e}")except Exception as e:- raise AnalysisError(f"Semantic analysis failed: {str(e)}")\ No newline at end of file+ raise AnalysisError(f"Semantic analysis failed: {str(e)}")diff --git a/scrapegraphai/utils/code_error_correction.py b/scrapegraphai/utils/code_error_correction.pyindex 9727c9ad..38ba266e 100644--- a/scrapegraphai/utils/code_error_correction.py+++ b/scrapegraphai/utils/code_error_correction.py@@ -11,10 +11,10 @@ comparing generated and reference results."""import json-from typing import Any, Dict, Optional+from typing import Any, Dictfrom functools import lru_cache-from pydantic import BaseModel, Field, validator+from pydantic import BaseModel, Fieldfrom langchain_core.prompts import PromptTemplatefrom langchain_core.output_parsers import StrOutputParser@@ -39,7 +39,7 @@ class InvalidCorrectionStateError(CodeGenerationError):class CorrectionState(BaseModel):"""Base model for code correction state validation."""generated_code: str = Field(..., description="The original generated code to correct")-+class Config:extra = "allow"@@ -60,10 +60,10 @@ def get_optimal_correction_template(error_type: str) -> str:"""Returns the optimal prompt template for code correction based on the error type.Results are cached for performance.-+Args:error_type (str): Type of error to correct.-+Returns:str: The prompt template text."""@@ -87,10 +87,10 @@ def syntax_focused_code_generation(state: Dict[str, Any], analysis: str, llm_modReturns:str: The corrected code.-+Raises:InvalidCorrectionStateError: If state is missing required keys.-+Example:>>> state = {'generated_code': 'print("Hello World"'@@ -103,23 +103,23 @@ def syntax_focused_code_generation(state: Dict[str, Any], analysis: str, llm_modvalidated_state = CorrectionState(generated_code=state.get("generated_code", ""))-+if not analysis or not isinstance(analysis, str):raise InvalidCorrectionStateError("Analysis must be a non-empty string")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_correction_template("syntax"),input_variables=["analysis", "generated_code"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"analysis": analysis,"generated_code": validated_state.generated_code})-+except KeyError as e:raise InvalidCorrectionStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -137,10 +137,10 @@ def execution_focused_code_generation(state: Dict[str, Any], analysis: str, llm_Returns:str: The corrected code.-+Raises:InvalidCorrectionStateError: If state is missing required keys or analysis is invalid.-+Example:>>> state = {'generated_code': 'print(x)'@@ -153,23 +153,23 @@ def execution_focused_code_generation(state: Dict[str, Any], analysis: str, llm_validated_state = CorrectionState(generated_code=state.get("generated_code", ""))-+if not analysis or not isinstance(analysis, str):raise InvalidCorrectionStateError("Analysis must be a non-empty string")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_correction_template("execution"),input_variables=["analysis", "generated_code"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"analysis": analysis,"generated_code": validated_state.generated_code})-+except KeyError as e:raise InvalidCorrectionStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -187,10 +187,10 @@ def validation_focused_code_generation(state: Dict[str, Any], analysis: str, llmReturns:str: The corrected code.-+Raises:InvalidCorrectionStateError: If state is missing required keys or analysis is invalid.-+Example:>>> state = {'generated_code': 'return {"name": "John"}',@@ -205,24 +205,24 @@ def validation_focused_code_generation(state: Dict[str, Any], analysis: str, llmgenerated_code=state.get("generated_code", ""),json_schema=state.get("json_schema", {}))-+if not analysis or not isinstance(analysis, str):raise InvalidCorrectionStateError("Analysis must be a non-empty string")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_correction_template("validation"),input_variables=["analysis", "generated_code", "json_schema"],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"analysis": analysis,"generated_code": validated_state.generated_code,"json_schema": validated_state.json_schema,})-+except KeyError as e:raise InvalidCorrectionStateError(f"Missing required key in state dictionary: {e}")except Exception as e:@@ -240,10 +240,10 @@ def semantic_focused_code_generation(state: Dict[str, Any], analysis: str, llm_mReturns:str: The corrected code.-+Raises:InvalidCorrectionStateError: If state is missing required keys or analysis is invalid.-+Example:>>> state = {'generated_code': 'def add(a, b): return a + b',@@ -260,10 +260,10 @@ def semantic_focused_code_generation(state: Dict[str, Any], analysis: str, llm_mexecution_result=state.get("execution_result", {}),reference_answer=state.get("reference_answer", {}))-+if not analysis or not isinstance(analysis, str):raise InvalidCorrectionStateError("Analysis must be a non-empty string")-+# Create prompt template and chainprompt = PromptTemplate(template=get_optimal_correction_template("semantic"),@@ -275,7 +275,7 @@ def semantic_focused_code_generation(state: Dict[str, Any], analysis: str, llm_m],)chain = prompt | llm_model | StrOutputParser()-+# Execute chain with validated statereturn chain.invoke({"analysis": analysis,@@ -283,8 +283,8 @@ def semantic_focused_code_generation(state: Dict[str, Any], analysis: str, llm_m"generated_result": json.dumps(validated_state.execution_result, indent=2),"reference_result": json.dumps(validated_state.reference_answer, indent=2),})-+except KeyError as e:raise InvalidCorrectionStateError(f"Missing required key in state dictionary: {e}")except Exception as e:- raise CodeGenerationError(f"Semantic code generation failed: {str(e)}")\ No newline at end of file+ raise CodeGenerationError(f"Semantic code generation failed: {str(e)}")diff --git a/scrapegraphai/utils/research_web.py b/scrapegraphai/utils/research_web.pyindex 195e11ca..df1b07c9 100644--- a/scrapegraphai/utils/research_web.py+++ b/scrapegraphai/utils/research_web.py@@ -1,5 +1,5 @@"""-research_web module for web searching across different search engines with improved+research_web module for web searching across different search engines with improvederror handling, validation, and security features."""@@ -48,7 +48,7 @@ class SearchConfig(BaseModel):serper_api_key: Optional[str] = Field(None, description="API key for Serper")region: Optional[str] = Field(None, description="Country/region code")language: str = Field("en", description="Language code")-+@validator('search_engine')def validate_search_engine(cls, v):"""Validate search engine."""@@ -56,14 +56,14 @@ class SearchConfig(BaseModel):if v.lower() not in valid_engines:raise ValueError(f"Search engine must be one of: {', '.join(valid_engines)}")return v.lower()-+@validator('query')def validate_query(cls, v):"""Validate search query."""if not v or not isinstance(v, str):raise ValueError("Query must be a non-empty string")return v-+@validator('max_results')def validate_max_results(cls, v):"""Validate max results."""@@ -80,17 +80,17 @@ PDF_REGEX = re.compile(r'\.pdf(#.*)?(\?.*)?$', re.IGNORECASE)def rate_limited(calls: int, period: int = 60):"""Decorator to limit the rate of function calls.-+Args:calls (int): Maximum number of calls allowed in the period.period (int): Time period in seconds.-+Returns:Callable: Decorated function with rate limiting."""min_interval = period / float(calls)last_called = [0.0]-+def decorator(func):@wraps(func)def wrapper(*args, **kwargs):@@ -108,10 +108,10 @@ def rate_limited(calls: int, period: int = 60):def sanitize_search_query(query: str) -> str:"""Sanitizes search query to prevent injection attacks.-+Args:query (str): The search query.-+Returns:str: Sanitized query."""@@ -135,7 +135,7 @@ USER_AGENTS = [def get_random_user_agent() -> str:"""Returns a random user agent from the list.-+Returns:str: Random user agent string."""@@ -167,10 +167,10 @@ def search_on_web(serper_api_key (str): API key for Serperregion (str): Country/region code (e.g., 'mx' for Mexico)language (str): Language code (e.g., 'es' for Spanish)-+Returns:List[str]: List of URLs from search results-+Raises:SearchConfigError: If search configuration is invalidSearchRequestError: If search request fails@@ -179,7 +179,7 @@ def search_on_web(try:# Sanitize query for securitysanitized_query = sanitize_search_query(query)-+# Validate search configurationconfig = SearchConfig(query=sanitized_query,@@ -192,12 +192,12 @@ def search_on_web(region=region,language=language)-+# Format proxy onceformatted_proxy = Noneif config.proxy:formatted_proxy = format_proxy(config.proxy)-+results = []if config.search_engine == "duckduckgo":# Create a DuckDuckGo search object with max_results@@ -209,25 +209,25 @@ def search_on_web(elif config.search_engine == "bing":results = _search_bing(- config.query,- config.max_results,- config.timeout,+ config.query,+ config.max_results,+ config.timeout,formatted_proxy)elif config.search_engine == "searxng":results = _search_searxng(- config.query,- config.max_results,- config.port,+ config.query,+ config.max_results,+ config.port,config.timeout)elif config.search_engine == "serper":results = _search_serper(- config.query,- config.max_results,- config.serper_api_key,+ config.query,+ config.max_results,+ config.serper_api_key,config.timeout)@@ -246,40 +246,40 @@ def _search_bing() -> List[str]:"""Helper function for Bing search with improved error handling.-+Args:query (str): Search querymax_results (int): Maximum number of results to returntimeout (int): Request timeout in secondsproxy (str, optional): Proxy configuration-+Returns:List[str]: List of URLs from search results"""headers = {"User-Agent": get_random_user_agent()}-+params = {"q": query,"count": max_results}-+proxies = {"http": proxy, "https": proxy} if proxy else None-+try:response = requests.get(- "https://www.bing.com/search",- params=params,- headers=headers,- proxies=proxies,+ "https://www.bing.com/search",+ params=params,+ headers=headers,+ proxies=proxies,timeout=timeout)response.raise_for_status()-+soup = BeautifulSoup(response.text, "html.parser")results = []-+# Extract URLs from Bing search resultsfor link in soup.select("li.b_algo h2 a"):url = link.get("href")@@ -287,7 +287,7 @@ def _search_bing(results.append(url)if len(results) >= max_results:break-+return resultsexcept Exception as e:raise SearchRequestError(f"Bing search failed: {str(e)}")@@ -298,20 +298,20 @@ def _search_searxng() -> List[str]:"""Helper function for SearXNG search.-+Args:query (str): Search querymax_results (int): Maximum number of results to returnport (int): Port for SearXNGtimeout (int): Request timeout in seconds-+Returns:List[str]: List of URLs from search results"""headers = {"User-Agent": get_random_user_agent()}-+params = {"q": query,"format": "json",@@ -321,7 +321,7 @@ def _search_searxng("engines": "duckduckgo,bing,brave","results": max_results}-+try:response = requests.get(f"http://localhost:{port}/search",@@ -330,7 +330,7 @@ def _search_searxng(timeout=timeout)response.raise_for_status()-+json_data = response.json()results = [result["url"] for result in json_data.get("results", [])]return results[:max_results]@@ -343,29 +343,29 @@ def _search_serper() -> List[str]:"""Helper function for Serper search.-+Args:query (str): Search querymax_results (int): Maximum number of results to returnapi_key (str): API key for Serpertimeout (int): Request timeout in seconds-+Returns:List[str]: List of URLs from search results"""if not api_key:raise SearchConfigError("Serper API key is required")-+headers = {"X-API-KEY": api_key,"Content-Type": "application/json"}-+data = {"q": query,"num": max_results}-+try:response = requests.post("https://google.serper.dev/search",@@ -374,17 +374,17 @@ def _search_serper(timeout=timeout)response.raise_for_status()-+json_data = response.json()results = []-+# Extract organic search resultsfor item in json_data.get("organic", []):if "link" in item:results.append(item["link"])if len(results) >= max_results:break-+return resultsexcept Exception as e:raise SearchRequestError(f"Serper search failed: {str(e)}")@@ -393,34 +393,34 @@ def _search_serper(def format_proxy(proxy_config: Union[str, Dict, ProxyConfig]) -> str:"""Format proxy configuration into a string.-+Args:proxy_config: Proxy configuration as string, dict, or ProxyConfig-+Returns:str: Formatted proxy string"""if isinstance(proxy_config, str):return proxy_config-+if isinstance(proxy_config, dict):proxy_config = ProxyConfig(**proxy_config)-+# Format proxy with authentication if providedif proxy_config.username and proxy_config.password:auth = f"{proxy_config.username}:{proxy_config.password}@"return f"http://{auth}{proxy_config.server}"-+return f"http://{proxy_config.server}"def filter_pdf_links(urls: List[str]) -> List[str]:"""Filter out PDF links from search results.-+Args:urls (List[str]): List of URLs-+Returns:List[str]: Filtered list of URLs without PDFs"""@@ -430,28 +430,28 @@ def filter_pdf_links(urls: List[str]) -> List[str]:def verify_request_signature(request_data: Dict, signature: str, secret_key: str) -> bool:"""Verify the signature of an incoming request.-+Args:request_data (Dict): Request data to verifysignature (str): Provided signaturesecret_key (str): Secret key for verification-+Returns:bool: True if signature is valid, False otherwise"""import hmacimport hashlibimport json-+# Sort keys for consistent serializationdata_string = json.dumps(request_data, sort_keys=True)-+# Create HMAC signaturecomputed_signature = hmac.new(secret_key.encode(),data_string.encode(),hashlib.sha256).hexdigest()-+# Compare signatures using constant-time comparison to prevent timing attacks- return hmac.compare_digest(computed_signature, signature)\ No newline at end of file+ return hmac.compare_digest(computed_signature, signature)