Spaces:
Sleeping
Sleeping
Download backend.py from ejschwartz/degpt: direct link, hf CLI and curl.
- Browser
- Download file 8.76 kB
-
https://huggingface.co/spaces/ejschwartz/degpt/resolve/main/backend.py
- Command line
-
hf download hf://spaces/ejschwartz/degpt/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/ejschwartz/degpt/resolve/main/backend.py
8.76 kB
| import importlib | |
| import io | |
| import logging | |
| import re | |
| import subprocess | |
| import sys | |
| from contextvars import ContextVar | |
| from functools import cache | |
| from pathlib import Path | |
| from tempfile import TemporaryDirectory | |
| from urllib.request import urlopen | |
| from zipfile import ZipFile | |
| import httpx2 | |
| from openai import OpenAI | |
| from provider import DEFAULT_BASE_URL, ProviderError, PublicProviderTransport, parse_base_url | |
| DEGPT = "0f632cc52fabd70c7e7b3b9ad1ed7aef517a3714" | |
| CINSPECTOR = "e827cfd9fccb1c5d7c4e0169c0da0bd2006de63b" | |
| C_GRAMMAR = "25ca2718aacaf0feda8b0709471332f303a0cef5" | |
| DEFAULT_MODEL = "gpt-4.1-mini" | |
| MODEL_OPTIONS = { | |
| DEFAULT_MODEL: {"temperature": 0.2}, | |
| "gpt-4.1": {"temperature": 0.2}, | |
| "gpt-5.4-mini": {"reasoning_effort": "none"}, | |
| } | |
| MODES = { | |
| "Automatic": None, | |
| "Rename variables": "RENAME_VAR", | |
| "Add comments": "ADD_COMMENT", | |
| "Simplify": "SIMPLIFY", | |
| } | |
| MAX_CODE_LENGTH = 16_000 | |
| _request: ContextVar[tuple[OpenAI, str, bool]] = ContextVar("request") | |
| class InputError(ValueError): | |
| pass | |
| class ModelReplyError(ValueError): | |
| pass | |
| class QueryChatGPT: | |
| def __init__(self): | |
| self.system_prompt = "" | |
| def insert_system_prompt(self, prompt): | |
| self.system_prompt = prompt | |
| def query(self, prompt): | |
| client, model, compatible = _request.get() | |
| options = ({"max_tokens": 4_096} if compatible | |
| else {"max_completion_tokens": 4_096, **MODEL_OPTIONS.get(model, {})}) | |
| completion = client.chat.completions.create( | |
| model=model, | |
| messages=[ | |
| {"role": "system", "content": self.system_prompt}, | |
| {"role": "user", "content": prompt}, | |
| ], | |
| **options, | |
| ) | |
| choices = getattr(completion, "choices", None) | |
| message = getattr(choices[0], "message", None) if choices else None | |
| content = getattr(message, "content", None) | |
| if not isinstance(content, str) or not content.strip(): | |
| raise ModelReplyError("The model returned no usable text. Check the model and API base URL.") | |
| return content | |
| def _fetch(url): | |
| with urlopen(url, timeout=30) as response: | |
| return response.read() | |
| def _raw(repository, revision, path): | |
| return _fetch(f"https://raw.githubusercontent.com/{repository}/{revision}/{path}") | |
| def _install_cinspector(workspace): | |
| repository = "PeiweiHu/cinspector" | |
| archive = _fetch(f"https://codeload.github.com/{repository}/zip/{CINSPECTOR}") | |
| prefix = f"cinspector-{CINSPECTOR}/" | |
| with ZipFile(io.BytesIO(archive)) as source: | |
| for member in source.namelist(): | |
| if member.startswith(f"{prefix}cinspector/") and member.endswith(".py"): | |
| path = Path(member.removeprefix(prefix)) | |
| if path.is_absolute() or ".." in path.parts: | |
| raise RuntimeError("Unexpected file in the cinspector archive") | |
| target = workspace / path | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_bytes(source.read(member)) | |
| for name in ("parser.c", "tree_sitter/parser.h"): | |
| target = workspace / "grammar" / name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_bytes(_raw("tree-sitter/tree-sitter-c", C_GRAMMAR, f"src/{name}")) | |
| subprocess.run( | |
| ["cc", "-shared", "-fPIC", "-O2", "-I", "grammar", "grammar/parser.c", | |
| "-o", "cinspector/cinspector-tree-sitter.so"], | |
| cwd=workspace, | |
| check=True, | |
| timeout=60, | |
| ) | |
| def _install_roles(workspace): | |
| package = workspace / "_degpt_upstream" | |
| package.mkdir() | |
| (package / "__init__.py").touch() | |
| for name in ("role.py", "util.py", "prompt.json"): | |
| source = _raw("PeiweiHu/DeGPT", DEGPT, f"degpt/{name}").decode() | |
| if name.endswith(".py"): | |
| source = source.replace("logger = Log().get(__file__)", "logger = _quiet_logger()") | |
| source = "from backend import _quiet_logger\n" + source | |
| if name == "role.py": | |
| source = source.replace("from util import", "from .util import") | |
| source = source.replace("from mssc import SemanticComparison\n", "") | |
| source = source.replace( | |
| "from chat import QueryChatGPT, llm_configured, load_config", | |
| "from backend import QueryChatGPT", | |
| ) | |
| (package / name).write_text(source, encoding="utf-8") | |
| def _quiet_logger(): | |
| logger = logging.Logger("degpt") | |
| logger.disabled = True | |
| return logger | |
| def _rename_identifiers(mapping, code): | |
| if not isinstance(mapping, dict) or any( | |
| not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", name) | |
| for name in mapping.values() | |
| ): | |
| return code | |
| from cinspector.interfaces import CCode | |
| source = code.encode() | |
| # Apply each mapping once so overlapping renames cannot cycle or cascade. | |
| identifiers = CCode(code).get_by_type_name("identifier") | |
| replacements = sorted( | |
| (node.internal.start_byte, node.internal.end_byte, mapping[node.src].encode()) | |
| for node in identifiers | |
| if node.src in mapping | |
| ) | |
| for start, end, name in reversed(replacements): | |
| source = source[:start] + name + source[end:] | |
| return source.decode() | |
| def load_roles(): | |
| runtime = TemporaryDirectory(prefix="degpt-") | |
| workspace = Path(runtime.name) | |
| _install_cinspector(workspace) | |
| _install_roles(workspace) | |
| sys.path.insert(0, str(workspace)) | |
| roles = importlib.import_module("_degpt_upstream.role") | |
| roles.print = lambda *args, **kwargs: None | |
| importlib.import_module("_degpt_upstream.util").print = roles.print | |
| roles.Advisor.replace_variable_name = staticmethod(_rename_identifiers) | |
| return roles, runtime | |
| def _is_single_function(code, roles): | |
| root = roles.Util().get_tree(code).root_node | |
| return not root.has_error and sum(node.type == "function_definition" for node in root.children) == 1 | |
| def optimize(code, mode, key, model=DEFAULT_MODEL, base_url=DEFAULT_BASE_URL, progress=lambda *args: None): | |
| if not code.strip(): | |
| raise InputError("Paste a decompiled C function.") | |
| if len(code) > MAX_CODE_LENGTH: | |
| raise InputError(f"Use a function under {MAX_CODE_LENGTH:,} characters.") | |
| if mode not in MODES: | |
| raise InputError("Select a cleanup mode.") | |
| key = key.strip() | |
| if not key: | |
| raise InputError("Enter your API key to run DeGPT.") | |
| if not re.fullmatch(r"[!-~]{1,512}", key): | |
| raise InputError("Enter an API key without spaces or line breaks.") | |
| model = model.strip() | |
| if not model or len(model) > 256 or not model.isprintable(): | |
| raise InputError("Select a model or enter a valid model ID.") | |
| url = parse_base_url(base_url) | |
| progress(0, "Validating function") | |
| roles, _ = load_roles() | |
| if not _is_single_function(code, roles): | |
| raise InputError("Paste one complete C function with valid syntax.") | |
| compatible = str(url) != DEFAULT_BASE_URL and url.host != "api.openai.com" | |
| transport = PublicProviderTransport(url) if compatible else None | |
| with httpx2.Client(transport=transport, trust_env=False, follow_redirects=False, timeout=25) as http_client: | |
| with OpenAI(api_key=key, admin_api_key="", base_url=str(url), organization="", project="", | |
| timeout=25, max_retries=0, http_client=http_client) as client: | |
| token = _request.set((client, model, compatible)) | |
| try: | |
| revision = _apply_passes(code, mode, roles, progress) | |
| finally: | |
| _request.reset(token) | |
| status = "Revision ready. Review it for changes in behavior." if revision != code else "No usable changes were suggested." | |
| return revision, status | |
| def _apply_passes(code, mode, roles, progress): | |
| if mode == "Automatic": | |
| progress(None, "Choosing cleanup passes") | |
| try: | |
| _, choices = roles.Referee().get_direction(code) | |
| except AssertionError: | |
| raise ModelReplyError("DeGPT could not read the model’s suggested passes. Try again or select a pass.") from None | |
| passes = roles.RoleModel().sort_directions(choices) | |
| else: | |
| passes = [roles.DType[MODES[mode]]] | |
| names = {roles.DType[value]: name for name, value in MODES.items() if value} | |
| for index, cleanup in enumerate(passes): | |
| progress(index / len(passes), f"Pass {index + 1} of {len(passes)}: {names.get(cleanup, str(cleanup))}") | |
| candidate = roles.single_opt(code, cleanup)["output"] | |
| if (candidate.strip() != code.strip() and len(candidate) <= MAX_CODE_LENGTH | |
| and _is_single_function(candidate, roles)): | |
| code = candidate | |
| return code | |