Spaces:
Sleeping
Sleeping
Download workflow.py from RevolutionGroup/deer-fire-scraper: direct link, hf CLI and curl.
- Browser
- Download file 4.77 kB
-
https://huggingface.co/spaces/RevolutionGroup/deer-fire-scraper/resolve/main/workflow.py
- Command line
-
hf download hf://spaces/RevolutionGroup/deer-fire-scraper/workflow.py
-
curl -L -o workflow.py https://huggingface.co/spaces/RevolutionGroup/deer-fire-scraper/resolve/main/workflow.py
4.77 kB
| import asyncio | |
| from typing import Annotated, Any, Dict, List, Optional, TypedDict | |
| from langchain_core.runnables import RunnableConfig | |
| from langgraph.graph import StateGraph, START, END | |
| from firecrawl import FirecrawlApp | |
| from deerflow.config.app_config import get_app_config | |
| # --- Engine Logic: Deer-Flow Scraping Motor --- | |
| class WorkflowState(TypedDict): | |
| """Estado del flujo de orquestaci贸n de scraping.""" | |
| url: str | |
| result: Optional[str] | |
| retries: int | |
| error: Optional[str] | |
| class ActionNode: | |
| """Abstracci贸n base para Action Nodes con l贸gica integrada de reintentos y timeout.""" | |
| def __init__(self, name: str, timeout: int = 60, max_retries: int = 3): | |
| self.name = name | |
| self.timeout = timeout | |
| self.max_retries = max_retries | |
| async def execute(self, state: WorkflowState, config: RunnableConfig) -> WorkflowState: | |
| raise NotImplementedError | |
| class ScrapeNode(ActionNode): | |
| """ActionNode especializado en web scraping a trav茅s de la API de Firecrawl.""" | |
| def __init__(self): | |
| super().__init__(name="scrape", timeout=60, max_retries=3) | |
| self._client = None | |
| def get_client(self) -> FirecrawlApp: | |
| """Inicializa el cliente de Firecrawl de forma tard铆a (lazy).""" | |
| if self._client: | |
| return self._client | |
| import os | |
| api_key = os.environ.get("FIRECRAWL_API_KEY") | |
| if not api_key: | |
| try: | |
| config = get_app_config().get_tool_config("web_search") | |
| api_key = config.model_extra.get("api_key") if config else None | |
| except Exception: | |
| api_key = None | |
| if not api_key: | |
| raise ValueError("No se ha proporcionado la API Key de Firecrawl. Por favor, config煤rala en la barra lateral o en las variables de entorno.") | |
| self._client = FirecrawlApp(api_key=api_key) | |
| return self._client | |
| async def execute(self, state: WorkflowState, config: RunnableConfig) -> WorkflowState: | |
| """Ejecuta la l贸gica de scraping con el cliente inicializado bajo demanda.""" | |
| url = state.get("url") | |
| retries = state.get("retries", 0) | |
| try: | |
| client = self.get_client() | |
| # Requisito: Timeout de 60s por nodo | |
| response = await asyncio.wait_for( | |
| asyncio.to_thread(client.scrape, url, formats=["markdown"]), | |
| timeout=self.timeout | |
| ) | |
| # Soporte dual: diccionario (SDK antiguo/API) u objeto (SDK nuevo) | |
| if isinstance(response, dict): | |
| markdown_content = response.get("markdown", "") | |
| else: | |
| markdown_content = getattr(response, "markdown", "") or "" | |
| return { | |
| **state, | |
| "result": markdown_content, | |
| "error": None | |
| } | |
| except asyncio.TimeoutError: | |
| return self._handle_error(state, "Node execution timed out (60s limit)") | |
| except Exception as e: | |
| return self._handle_error(state, str(e)) | |
| def _handle_error(self, state: WorkflowState, error_msg: str) -> WorkflowState: | |
| """Actualiza el estado interno de reintentos.""" | |
| retries = int(state.get("retries", 0)) | |
| return { | |
| **state, | |
| "retries": retries + 1, | |
| "error": error_msg | |
| } | |
| class Flow: | |
| """Motor de orquestaci贸n para flujos de scraping en Deer-Flow.""" | |
| def __init__(self, concurrency_limit: int = 10): | |
| # El l铆mite de concurrencia de 10 ejecuciones se define aqu铆 para el motor | |
| self.concurrency_limit = concurrency_limit | |
| self.builder = StateGraph(WorkflowState) | |
| self._init_orchestration() | |
| def _init_orchestration(self): | |
| """Construye el Grafo de Estados con pol铆tica de reintentos (max 3).""" | |
| node = ScrapeNode() | |
| # A帽adir nodos al grafo | |
| self.builder.add_node("scrape", node.execute) | |
| # Punto de entrada | |
| self.builder.add_edge(START, "scrape") | |
| # L贸gica de ruteo: Pol铆tica de reintentos (Max 3) integrada en el grafo | |
| def should_continue(state: WorkflowState): | |
| retries = int(state.get("retries", 0)) | |
| if state.get("error") and retries <= 3: | |
| return "scrape" # Ciclo de reintento | |
| return END | |
| self.builder.add_conditional_edges( | |
| "scrape", | |
| should_continue, | |
| {"scrape": "scrape", END: END} | |
| ) | |
| def compile(self): | |
| """Compila el flujo en un grafo ejecutable compatible con Deer-Flow.""" | |
| return self.builder.compile() | |
| # --- Exportaci贸n del Motor Funcional --- | |
| workflow = Flow(concurrency_limit=10).compile() | |