Download utils/utils.py from Agents-MCP-Hackathon/data_science_agent: direct link, hf CLI and curl.
- Browser
- Download file 1.27 kB
-
https://huggingface.co/spaces/Agents-MCP-Hackathon/data_science_agent/resolve/main/utils/utils.py
- Command line
-
hf download hf://spaces/Agents-MCP-Hackathon/data_science_agent/utils/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Agents-MCP-Hackathon/data_science_agent/resolve/main/utils/utils.py
1.27 kB
| import re | |
| import json | |
| from typing import Any, List | |
| def parse_json_codefences(text: str) -> List[Any]: | |
| """ | |
| Extracts all ```json ... ``` code blocks from `text`, parses each as JSON, | |
| and returns a list of resulting Python objects. | |
| """ | |
| # Regex to match ```json ... ``` fences (non-greedy, multiline) | |
| pattern = re.compile(r"```json\s+(.*?)\s+```", re.DOTALL | re.IGNORECASE) | |
| results = [] | |
| for match in pattern.finditer(text): | |
| json_str = match.group(1).strip() | |
| try: | |
| data = json.loads(json_str) | |
| if isinstance(data, list): | |
| results.extend(data) | |
| else: | |
| results.append(data) | |
| except json.JSONDecodeError as e: | |
| print(f"⚠️ Failed to parse JSON block:\n{json_str}\nError: {e}") | |
| return results | |
| def parse_python_codefences(text: str) -> List[str]: | |
| """ | |
| Extracts all ```python ... ``` code blocks from `text` | |
| """ | |
| # Regex to match ```python ... ``` fences (non-greedy, multiline) | |
| pattern = re.compile(r"```python\s+(.*?)\s+```", re.DOTALL | re.IGNORECASE) | |
| results = "" | |
| for match in pattern.finditer(text): | |
| python_str = match.group(1).strip() | |
| results = python_str | |
| return results | |