Spaces:
Sleeping

File size: 8,759 Bytes
9ad1916
 
 
 
 
 
 
 
 
 
 
 
 
6c348e7
9ad1916
 
6c348e7
 
9ad1916
 
 
 
6c348e7
 
 
 
 
 
9ad1916
 
 
 
 
 
 
6c348e7
9ad1916
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c348e7
 
 
 
 
9ad1916
 
 
 
6c348e7
9ad1916
6c348e7
 
 
 
 
 
9ad1916
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddb046e
9ad1916
6c348e7
9ad1916
 
 
 
 
 
6c348e7
9ad1916
6c348e7
 
 
 
 
9ad1916
ddb046e
9ad1916
 
 
 
6c348e7
 
 
 
 
 
 
ddb046e
6c348e7
 
9ad1916
 
 
 
 
ddb046e
9ad1916
ddb046e
9ad1916
 
 
 
 
 
 
 
ddb046e
 
 
9ad1916
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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()


@cache
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