Spaces:
Sleeping

File size: 4,598 Bytes
9ad1916
 
6c348e7
9ad1916
6c348e7
 
9ad1916
 
 
 
 
 
 
 
 
 
 
 
 
 
6c348e7
9ad1916
6c348e7
 
 
 
 
 
 
 
 
 
 
 
 
9ad1916
6c348e7
9ad1916
 
6c348e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad1916
6c348e7
ddb046e
6c348e7
 
9ad1916
ddb046e
 
6c348e7
9ad1916
 
6c348e7
9ad1916
6c348e7
9ad1916
6c348e7
9ad1916
6c348e7
 
 
9ad1916
6c348e7
9ad1916
 
 
 
 
6c348e7
 
 
 
9ad1916
 
6c348e7
 
 
 
 
 
 
 
9ad1916
 
 
6c348e7
9ad1916
 
 
 
 
 
 
6c348e7
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
import gradio as gr
from gradio.components.textbox import InputHTMLAttributes
from openai import APIConnectionError, APIResponseValidationError, APIStatusError, APITimeoutError, AuthenticationError, RateLimitError

from backend import DEFAULT_MODEL, MODEL_OPTIONS, InputError, ModelReplyError, MODES, load_roles, optimize
from provider import DEFAULT_BASE_URL, ProviderError


EXAMPLE = """int fib(int param_1) {
    int iVar1;
    int iVar2;
    if (param_1 < 2) {
        iVar2 = param_1;
    } else {
        iVar1 = fib(param_1 + -1);
        iVar2 = fib(param_1 + -2) + iVar1;
    }
    return iVar2;
}"""

CHECK_KEY = """(code, mode, key, model, baseUrl) => {
    const field = document.querySelector('#openai-api-key input');
    if (field && !key?.trim()) {
        if (!field.hasAttribute('aria-invalid')) {
            field.setAttribute('aria-invalid', 'true');
            field.setAttribute('aria-errormessage', 'api-key-required');
            field.addEventListener('input', function clearError() {
                if (field.value.trim()) {
                    field.removeAttribute('aria-invalid');
                    field.removeAttribute('aria-errormessage');
                    field.removeEventListener('input', clearError);
                }
            });
        }
        field.focus();
    }
    return [code, mode, key, model, baseUrl];
}"""

FORM_CSS = """
:is(#original-code, #revised-code) :is(.cm-editor, .empty) {
    block-size: 16rem;
}
#openai-api-key input[aria-invalid="true"] {
    outline: 2px solid #dc2626 !important;
    outline-offset: 2px;
}
#api-key-required {
    display: none;
    color: var(--error-text-color, #dc2626);
}
#api-key-control:has(input[aria-invalid="true"]) #api-key-required {
    display: block;
}
"""


def run(code, mode, key, model, base_url, progress=gr.Progress()):
    if not (key or "").strip():
        return gr.skip(), ""
    try:
        return optimize(code or "", mode, key, model or "", base_url or "",
                        lambda value, description: progress(value, desc=description))
    except (InputError, ModelReplyError, ProviderError) as error:
        return "", str(error)
    except AuthenticationError:
        return "", "The provider rejected the API key. Check that it belongs to the selected provider."
    except RateLimitError:
        return "", "The provider reported a rate or quota limit. Check your API usage or try again later."
    except APITimeoutError:
        return "", "The provider timed out. Try a shorter function or a single cleanup pass."
    except APIConnectionError:
        return "", "Could not reach the provider. Check the API base URL or try again shortly."
    except APIResponseValidationError:
        return "", "The provider returned an invalid chat completion. Check the API base URL."
    except APIStatusError:
        return "", "The provider could not complete the request. Check the model ID and your access to it."


with gr.Blocks(title="DeGPT", analytics_enabled=False) as app:
    gr.Markdown("# DeGPT\nImprove the readability of a decompiled C function.")
    with gr.Row():
        original = gr.Code(value=EXAMPLE, label="Original C", language="c", lines=16, max_lines=16,
                           interactive=True, elem_id="original-code")
        revision = gr.Code(value="", label="Revised C", language="c", lines=16, max_lines=16,
                           interactive=False, elem_id="revised-code")
    with gr.Row():
        mode = gr.Dropdown(list(MODES), value="Automatic", label="Cleanup mode")
        model = gr.Dropdown(list(MODEL_OPTIONS), value=DEFAULT_MODEL, allow_custom_value=True, label="Model")
    with gr.Row():
        base_url = gr.Textbox(value=DEFAULT_BASE_URL, label="API base URL")
        with gr.Column(elem_id="api-key-control"):
            key = gr.Textbox(label="API key", type="password", elem_id="openai-api-key",
                             html_attributes=InputHTMLAttributes(autocomplete="off", spellcheck=False))
            gr.HTML('<p role="alert">Enter your API key to run DeGPT.</p>', elem_id="api-key-required")
    gr.Markdown("Your code and API key are sent to the provider at the selected base URL.")
    submit = gr.Button("Run DeGPT", variant="primary")
    status = gr.Markdown()

    submit.click(run, inputs=[original, mode, key, model, base_url], outputs=[revision, status], js=CHECK_KEY,
                 concurrency_limit=2, api_visibility="private")

app.queue(max_size=16)


if __name__ == "__main__":
    load_roles()
    app.launch(css=FORM_CSS, run_history=False, enable_monitoring=False)