File size: 7,783 Bytes
9da2f0b
 
 
2d24635
 
af139e1
 
 
 
9da2f0b
 
 
 
 
 
 
 
 
 
af139e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9da2f0b
 
af139e1
9da2f0b
af139e1
 
 
 
9da2f0b
af139e1
 
 
 
9da2f0b
 
 
af139e1
 
 
 
 
9da2f0b
af139e1
9da2f0b
af139e1
450ebd0
9da2f0b
450ebd0
af139e1
450ebd0
af139e1
 
 
 
 
 
 
 
 
 
 
 
9da2f0b
450ebd0
af139e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9da2f0b
 
af139e1
 
 
 
9da2f0b
 
af139e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9da2f0b
 
af139e1
9da2f0b
 
af139e1
 
 
9da2f0b
f78beac
6d93267
f78beac
44edba7
9da2f0b
 
 
 
 
 
 
af139e1
 
e04c711
 
 
af139e1
 
450ebd0
af139e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04c711
 
 
af139e1
 
 
 
 
e04c711
af139e1
e04c711
 
9da2f0b
af139e1
 
9da2f0b
 
 
 
af139e1
9da2f0b
 
 
af139e1
 
9da2f0b
 
 
 
af139e1
9da2f0b
b11bed8
 
af139e1
b11bed8
9da2f0b
2d24635
af139e1
9da2f0b
af139e1
 
 
 
 
 
 
 
450ebd0
2d24635
af139e1
 
 
 
e04c711
 
af139e1
 
 
 
 
 
 
 
e04c711
 
9da2f0b
af139e1
 
 
 
 
e04c711
 
9da2f0b
af139e1
 
 
 
 
e04c711
 
9da2f0b
af139e1
 
 
 
 
e04c711
 
9da2f0b
af139e1
 
 
 
 
 
 
 
937049b
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import ast
import operator as op
import re
import gradio as gr

# ----------------------------
# Safe arithmetic evaluator
# ----------------------------
ALLOWED_OPERATORS = {
    ast.Add: op.add,
    ast.Sub: op.sub,
    ast.Mult: op.mul,
    ast.Div: op.truediv,
    ast.Mod: op.mod,
    ast.Pow: op.pow,
    ast.UAdd: op.pos,
    ast.USub: op.neg,
}

def _safe_eval_node(node):
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
        return node.value

    if isinstance(node, ast.BinOp) and type(node.op) in ALLOWED_OPERATORS:
        return ALLOWED_OPERATORS[type(node.op)](
            _safe_eval_node(node.left),
            _safe_eval_node(node.right),
        )

    if isinstance(node, ast.UnaryOp) and type(node.op) in ALLOWED_OPERATORS:
        return ALLOWED_OPERATORS[type(node.op)](_safe_eval_node(node.operand))

    raise ValueError("Unsupported expression")

def safe_eval(expr: str):
    expr = expr.replace("×", "*").replace("÷", "/").replace("−", "-")
    tree = ast.parse(expr, mode="eval")
    return _safe_eval_node(tree.body)

def format_result(value):
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    return str(value)

# ----------------------------
# Calculator actions
# ----------------------------
def append_value(current, value):
    if current in ("0", "Error"):
        current = ""

    if value in "+-*/":
        if not current and value != "-":
            return "0", "0"
        if current.endswith(("+", "-", "*", "/", ".")):
            current = current[:-1]

    return current + value, current + value

def clear_display():
    return "0", "0"

def backspace(current):
    if current in ("0", "Error", ""):
        return "0", "0"
    new_value = current[:-1]
    if not new_value:
        new_value = "0"
    return new_value, new_value

def evaluate(current):
    try:
        result = safe_eval(current)
        result = format_result(result)
        return result, result
    except:
        return "Error", "Error"

def toggle_sign(current):
    if current in ("0", "Error", ""):
        return "-", "-"

    m = re.search(r"(-?\d+(?:\.\d+)?)$", current)
    if not m:
        return current, current

    start, end = m.span()
    num = m.group(0)

    if num.startswith("-"):
        num = num[1:]
    else:
        num = "-" + num

    new_value = current[:start] + num
    return new_value, new_value

def percent(current):
    if current in ("0", "Error", ""):
        return "0", "0"

    if current.endswith((".", "+", "-", "*", "/")):
        return current, current

    new_value = current + "/100"
    return new_value, new_value

def parens(current):
    if current in ("0", "Error"):
        current = ""

    open_count = current.count("(")
    close_count = current.count(")")

    if not current or current.endswith(("+", "-", "*", "/", "(")):
        ch = "("
    elif open_count > close_count:
        ch = ")"
    else:
        ch = "("

    new_value = current + ch
    return new_value, new_value

def make_append(v):
    def fn(current):
        return append_value(current, v)
    return fn

# ----------------------------
# UI
# ----------------------------
CSS = """
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@300;400;600&display=swap');

*{font-family: 'Orbitron', sans-serif !important;}

body, .gradio-container {
    background: #000 !important;
    color: white !important;
}

.phone {
    max-width: 390px;
    margin: 0 auto;
    padding: 16px 14px 20px;
}

.display textarea {
    background: #000 !important;
    color: #fff !important;
    border: none !important;
    box-shadow: none !important;
    text-align: right !important;
    font-size: 72px !important;
    font-weight: 300 !important;
    height: 170px !important;
    padding: 10px 0 0 0 !important;
    resize: none !important;
}

.divider {
    height: 1px;
    background: rgba(255,255,255,0.18);
    margin: 10px 0 18px 0;
}

.topbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: rgba(255,255,255,0.8);
    font-size: 18px;
    margin-bottom: 8px;
    opacity: 0.9;
}

button {
    height: 82px !important;
    min-height: 82px !important;
    border-radius: 999px !important;
    font-size: 30px !important;
    font-weight: 500 !important;
    border: none !important;
    box-shadow: none !important;
}

.digit button {
    background: #272727 !important;
    color: #fff !important;
}

.utility button {
    background: #a5a5a5 !important;
    color: #000 !important;
}

.operator button {
    background: #bfbfbf !important;
    color: #000 !important;
}

.equals button {
    background: #34c759 !important;
    color: #fff !important;
}

.zero button {
    border-radius: 999px !important;
}
"""

with gr.Blocks(css=CSS, title="Calculator") as demo:
    with gr.Column(elem_classes="phone"):
        display = gr.Textbox(
            value="0",
            show_label=False,
            interactive=False,
            container=False,
            lines=1,
            elem_classes="display",
        )
        state = gr.State("0")

        gr.HTML("""
        <div class="divider"></div>
        """)

        # Row 1
        with gr.Row():
            with gr.Column(scale=1, min_width=0):
                gr.Button("C", elem_classes=["utility"]).click(clear_display, None, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("()", elem_classes=["utility"]).click(parens, state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("%", elem_classes=["utility"]).click(percent, state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("÷", elem_classes=["operator"]).click(make_append("/"), state, [state, display])

        # Row 2
        with gr.Row():
            for label in ["7", "8", "9"]:
                with gr.Column(scale=1, min_width=0):
                    gr.Button(label, elem_classes=["digit"]).click(make_append(label), state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("×", elem_classes=["operator"]).click(make_append("*"), state, [state, display])

        # Row 3
        with gr.Row():
            for label in ["4", "5", "6"]:
                with gr.Column(scale=1, min_width=0):
                    gr.Button(label, elem_classes=["digit"]).click(make_append(label), state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("−", elem_classes=["operator"]).click(make_append("-"), state, [state, display])

        # Row 4
        with gr.Row():
            for label in ["1", "2", "3"]:
                with gr.Column(scale=1, min_width=0):
                    gr.Button(label, elem_classes=["digit"]).click(make_append(label), state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("+", elem_classes=["operator"]).click(make_append("+"), state, [state, display])

        # Row 5
        with gr.Row():
            with gr.Column(scale=1, min_width=0):
                gr.Button("+/-", elem_classes=["utility"]).click(toggle_sign, state, [state, display])
            with gr.Column(scale=2, min_width=0):
                gr.Button("0", elem_classes=["digit", "zero"]).click(make_append("0"), state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button(".", elem_classes=["digit"]).click(make_append("."), state, [state, display])
            with gr.Column(scale=1, min_width=0):
                gr.Button("=", elem_classes=["equals"]).click(evaluate, state, [state, display])

demo.launch(server_name="0.0.0.0", server_port=7860)