Spaces:
Runtime error
Runtime error
Download services/developer_service.py from cloudaiRambo/cloudairambo: direct link, hf CLI and curl.
- Browser
- Download file 6.72 kB
-
https://huggingface.co/spaces/cloudaiRambo/cloudairambo/resolve/main/services/developer_service.py
- Command line
-
hf download hf://spaces/cloudaiRambo/cloudairambo/services/developer_service.py
-
curl -L -o developer_service.py https://huggingface.co/spaces/cloudaiRambo/cloudairambo/resolve/main/services/developer_service.py
6.72 kB
| # backend/services/developer_service.py | |
| import json | |
| import re | |
| import hashlib | |
| import base64 | |
| import tempfile | |
| import csv | |
| import os | |
| from typing import Any, Dict, List, Tuple | |
| from urllib.parse import urlparse, parse_qs, unquote | |
| import sqlparse | |
| import xmltodict | |
| from pygments import highlight | |
| from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer | |
| from pygments.formatters import HtmlFormatter | |
| import requests | |
| # ------------------------- | |
| # Code Formatter (raw + HTML) | |
| # ------------------------- | |
| def format_code_raw(code: str, lang: str = None) -> str: | |
| """ | |
| Return beautified code where possible (sql uses sqlparse). | |
| For other languages we return original code (or trimmed) but still can apply simple indentation for JSON/XML. | |
| """ | |
| if not lang: | |
| # try to guess | |
| try: | |
| lexer = guess_lexer(code) | |
| lang = lexer.aliases[0] | |
| except Exception: | |
| lang = None | |
| if lang: | |
| lang = lang.lower() | |
| # SQL formatted via sqlparse | |
| if lang and lang in ("sql", "pgsql", "mysql"): | |
| return sqlparse.format(code, reindent=True, keyword_case="upper") | |
| # JSON pretty if it is JSON | |
| try: | |
| parsed = json.loads(code) | |
| return json.dumps(parsed, indent=4, ensure_ascii=False) | |
| except Exception: | |
| pass | |
| # XML pretty if XML | |
| try: | |
| parsed = xmltodict.parse(code) | |
| return xmltodict.unparse(parsed, pretty=True) | |
| except Exception: | |
| pass | |
| # fallback: return code (cleaned) | |
| return code.rstrip() + "\n" | |
| def format_code_html(code: str, lang: str = None) -> str: | |
| """ | |
| Return HTML highlighted version using pygments. | |
| If lang is None, attempt to guess. | |
| """ | |
| try: | |
| if lang: | |
| lexer = get_lexer_by_name(lang) | |
| else: | |
| lexer = guess_lexer(code) | |
| except Exception: | |
| lexer = TextLexer() | |
| formatter = HtmlFormatter(full=True, style="friendly") | |
| return highlight(code, lexer, formatter) | |
| # ------------------------- | |
| # JSON Utilities | |
| # ------------------------- | |
| def json_pretty(text: str) -> str: | |
| obj = json.loads(text) | |
| return json.dumps(obj, indent=4, ensure_ascii=False) | |
| def json_minify(text: str) -> str: | |
| obj = json.loads(text) | |
| return json.dumps(obj, separators=(",", ":"), ensure_ascii=False) | |
| def json_validate(text: str) -> Tuple[bool, str]: | |
| try: | |
| json.loads(text) | |
| return True, "Valid JSON" | |
| except Exception as e: | |
| return False, str(e) | |
| # ------------------------- | |
| # XML Utilities | |
| # ------------------------- | |
| def xml_pretty(text: str) -> str: | |
| parsed = xmltodict.parse(text) | |
| return xmltodict.unparse(parsed, pretty=True) | |
| def xml_validate(text: str) -> Tuple[bool, str]: | |
| try: | |
| xmltodict.parse(text) | |
| return True, "Valid XML" | |
| except Exception as e: | |
| return False, str(e) | |
| # ------------------------- | |
| # SQL Formatter | |
| # ------------------------- | |
| def sql_format(text: str) -> str: | |
| return sqlparse.format(text, reindent=True, keyword_case="upper") | |
| # ------------------------- | |
| # Base64 Converter | |
| # ------------------------- | |
| def base64_encode(text: str) -> str: | |
| return base64.b64encode(text.encode()).decode() | |
| def base64_decode(text: str) -> str: | |
| return base64.b64decode(text.encode()).decode("utf-8", "ignore") | |
| # ------------------------- | |
| # JSON -> CSV Converter | |
| # ------------------------- | |
| def json_to_csv(json_text: str) -> str: | |
| """ | |
| Accepts a JSON array of objects. Returns a path to a CSV file. | |
| """ | |
| data = json.loads(json_text) | |
| if not isinstance(data, list): | |
| raise ValueError("JSON must be an array of objects") | |
| # collect all keys | |
| keys = set() | |
| for row in data: | |
| if isinstance(row, dict): | |
| keys.update(row.keys()) | |
| else: | |
| raise ValueError("Each item in array must be an object") | |
| keys = list(keys) | |
| tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv") | |
| tmpname = tmp.name | |
| tmp.close() | |
| with open(tmpname, "w", newline="", encoding="utf-8") as cf: | |
| writer = csv.DictWriter(cf, fieldnames=keys) | |
| writer.writeheader() | |
| for row in data: | |
| writer.writerow({k: row.get(k, "") for k in keys}) | |
| return tmpname | |
| # ------------------------- | |
| # URL Analyzer | |
| # ------------------------- | |
| def analyze_url(url: str) -> Dict[str, Any]: | |
| parsed = urlparse(url) | |
| qs = parse_qs(parsed.query) | |
| # decode query values | |
| decoded_qs = {k: [unquote(v) for v in vals] for k, vals in qs.items()} | |
| return { | |
| "scheme": parsed.scheme, | |
| "netloc": parsed.netloc, | |
| "hostname": parsed.hostname, | |
| "port": parsed.port, | |
| "path": parsed.path, | |
| "params": parsed.params, | |
| "query": decoded_qs, | |
| "fragment": parsed.fragment, | |
| "username": parsed.username, | |
| "password": parsed.password, | |
| } | |
| # ------------------------- | |
| # Regex Tester | |
| # ------------------------- | |
| def regex_test(pattern: str, text: str) -> Dict[str, Any]: | |
| try: | |
| compiled = re.compile(pattern) | |
| except re.error as e: | |
| return {"valid": False, "error": str(e)} | |
| matches = compiled.findall(text) | |
| details = [] | |
| for m in compiled.finditer(text): | |
| details.append({ | |
| "match": m.group(), | |
| "start": m.start(), | |
| "end": m.end(), | |
| "groups": m.groups() | |
| }) | |
| return {"valid": True, "matches": matches, "details": details} | |
| # ------------------------- | |
| # Hash Generator | |
| # ------------------------- | |
| def generate_hash(text: str, algo: str = "md5") -> str: | |
| algo = algo.lower() | |
| if algo not in ("md5", "sha1", "sha256", "sha512"): | |
| raise ValueError("Unsupported algorithm") | |
| h = getattr(hashlib, algo)() | |
| h.update(text.encode()) | |
| return h.hexdigest() | |
| # ------------------------- | |
| # API Tester | |
| # ------------------------- | |
| def api_request(method: str, url: str, headers: dict = None, params: dict = None, | |
| body: str = None, timeout: int = 20) -> Dict[str, Any]: | |
| """ | |
| Simple API tester using requests. Returns status, headers, body (text), elapsed_ms. | |
| """ | |
| method = method.upper() | |
| headers = headers or {} | |
| params = params or {} | |
| try: | |
| resp = requests.request(method, url, headers=headers, params=params, data=body, timeout=timeout) | |
| # try to decode JSON | |
| try: | |
| resp_body = resp.json() | |
| except Exception: | |
| resp_body = resp.text | |
| return { | |
| "status_code": resp.status_code, | |
| "headers": dict(resp.headers), | |
| "body": resp_body, | |
| "elapsed_ms": int(resp.elapsed.total_seconds() * 1000) | |
| } | |
| except Exception as e: | |
| return {"error": str(e)} | |