File size: 14,516 Bytes
907ed07
 
a655c51
907ed07
 
 
a655c51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b75348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a655c51
7b75348
 
 
 
 
 
 
 
 
 
 
907ed07
 
d21ad6b
a655c51
d21ad6b
 
 
 
a655c51
d21ad6b
 
 
 
 
 
 
 
 
 
 
7b75348
a655c51
7b75348
 
d21ad6b
 
a655c51
 
 
 
d21ad6b
8d65db3
907ed07
d21ad6b
907ed07
a655c51
8d65db3
7b75348
907ed07
d21ad6b
a655c51
d21ad6b
7b75348
 
d21ad6b
11db94d
 
 
7b75348
 
a655c51
7b75348
 
 
a655c51
7b75348
a655c51
7b75348
 
 
 
11db94d
8d65db3
 
7b75348
8d65db3
11db94d
 
a655c51
8d65db3
a655c51
11db94d
7b75348
11db94d
7b75348
11db94d
8d65db3
 
7b75348
8d65db3
11db94d
 
a655c51
8d65db3
a655c51
907ed07
7b75348
d21ad6b
7b75348
d21ad6b
8d65db3
 
7b75348
8d65db3
11db94d
907ed07
a655c51
8d65db3
a655c51
11db94d
7b75348
907ed07
11db94d
 
907ed07
11db94d
907ed07
8d65db3
 
 
 
11db94d
 
a655c51
8d65db3
a655c51
11db94d
7b75348
11db94d
 
a655c51
11db94d
 
8d65db3
a655c51
 
 
 
11db94d
8d65db3
a655c51
 
 
 
11db94d
8d65db3
 
 
 
 
907ed07
8d65db3
907ed07
a655c51
 
 
 
 
 
d21ad6b
a655c51
7b75348
 
907ed07
d21ad6b
a655c51
7b75348
 
 
 
907ed07
d21ad6b
907ed07
8d65db3
 
a655c51
 
d21ad6b
907ed07
a655c51
8d65db3
a655c51
7b75348
 
907ed07
d21ad6b
a655c51
7b75348
 
 
 
907ed07
d21ad6b
907ed07
8d65db3
 
7b75348
 
d21ad6b
907ed07
a655c51
8d65db3
a655c51
7b75348
 
907ed07
d21ad6b
a655c51
7b75348
 
 
 
907ed07
d21ad6b
907ed07
8d65db3
 
7b75348
 
d21ad6b
907ed07
a655c51
d21ad6b
a655c51
7b75348
 
907ed07
8d65db3
907ed07
d21ad6b
 
907ed07
8d65db3
 
7b75348
 
d21ad6b
907ed07
a655c51
d21ad6b
a655c51
7b75348
 
907ed07
8d65db3
907ed07
d21ad6b
 
907ed07
8d65db3
 
7b75348
 
d21ad6b
907ed07
a655c51
d21ad6b
a655c51
7b75348
 
907ed07
d21ad6b
907ed07
d21ad6b
a655c51
d21ad6b
8d65db3
d21ad6b
 
907ed07
d21ad6b
907ed07
d21ad6b
 
907ed07
8d65db3
 
7b75348
 
d21ad6b
907ed07
a655c51
d21ad6b
a655c51
7b75348
 
d21ad6b
 
a655c51
7b75348
 
 
 
907ed07
d21ad6b
a655c51
7b75348
 
 
 
d21ad6b
 
a655c51
7b75348
 
 
 
d21ad6b
 
 
8d65db3
 
7b75348
 
d21ad6b
 
7b75348
d21ad6b
 
 
a655c51
d21ad6b
 
 
907ed07
7b75348
a655c51
8d65db3
 
 
 
907ed07
 
8d65db3
 
a655c51
8d65db3
907ed07
 
 
8d65db3
a655c51
8d65db3
 
907ed07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b75348
 
8d65db3
 
 
 
907ed07
 
 
8d65db3
907ed07
 
8d65db3
907ed07
8d65db3
 
907ed07
 
8d65db3
d21ad6b
8d65db3
d21ad6b
907ed07
 
8d65db3
907ed07
8d65db3
907ed07
 
 
8d65db3
 
 
 
 
907ed07
 
 
8d65db3
 
907ed07
 
 
8d65db3
d21ad6b
8d65db3
907ed07
 
8d65db3
907ed07
8d65db3
d21ad6b
8d65db3
 
907ed07
 
 
 
8d65db3
 
907ed07
 
8d65db3
 
907ed07
 
 
8d65db3
907ed07
 
7b75348
907ed07
 
 
 
7b75348
907ed07
 
 
7b75348
907ed07
 
 
 
 
 
 
 
8d65db3
a655c51
8d65db3
a655c51
8d65db3
7b75348
 
8d65db3
a655c51
907ed07
 
 
 
 
8d65db3
907ed07
 
 
 
7b75348
a655c51
7b75348
d21ad6b
8d65db3
 
 
907ed07
 
7b75348
907ed07
8d65db3
907ed07
 
 
 
8d65db3
907ed07
 
 
 
 
 
 
 
 
d21ad6b
907ed07
8d65db3
907ed07
 
d21ad6b
907ed07
8d65db3
907ed07
 
7b75348
 
 
8d65db3
 
d21ad6b
8d65db3
907ed07
 
8d65db3
 
907ed07
 
 
 
d21ad6b
907ed07
8d65db3
907ed07
8d65db3
907ed07
 
 
 
 
 
 
 
 
8d65db3
7b75348
907ed07
 
 
 
d21ad6b
11db94d
d21ad6b
907ed07
 
d21ad6b
907ed07
 
 
 
d21ad6b
907ed07
8d65db3
 
907ed07
 
d21ad6b
907ed07
 
 
 
 
 
 
d21ad6b
907ed07
 
 
 
 
8d65db3
907ed07
 
 
d21ad6b
 
11db94d
 
7b75348
 
 
d21ad6b
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
import math
import gradio as gr
import spaces


# ============================================================
# ZeroGPU Compatibility
# ============================================================

@spaces.GPU
def gpu_startup_check():
    """
    ZeroGPU startup compatibility function.

    The scientific calculator itself does not require GPU.
    This function exists because Hugging Face ZeroGPU
    requires at least one @spaces.GPU function.
    """
    return True


# ============================================================
# Operations
# ============================================================

OPERATIONS = [
    "Addition (+)",
    "Subtraction (-)",
    "Multiplication (×)",
    "Division (÷)",
    "Power (xʸ)",
    "Square Root (√x)",
    "Logarithm (log₁₀)",
    "Natural Log (ln)",
    "Sine (sin)",
    "Cosine (cos)",
    "Tangent (tan)",
    "Factorial (n!)",
]


BINARY_OPERATIONS = {
    "Addition (+)",
    "Subtraction (-)",
    "Multiplication (×)",
    "Division (÷)",
    "Power (xʸ)",
}


# ============================================================
# Number Formatting
# ============================================================

def format_number(value):

    if isinstance(value, int):
        return str(value)

    if isinstance(value, float):

        if not math.isfinite(value):
            return str(value)

        if value.is_integer():
            return str(int(value))

        return f"{value:.12g}"

    return str(value)


# ============================================================
# Scientific Calculator
# ============================================================

def calculate(operation, num1, num2):

    # --------------------------------------------------------
    # Validate first number
    # --------------------------------------------------------

    if num1 is None:
        return "Please enter the first number.", ""

    try:
        num1 = float(num1)

    except (TypeError, ValueError):
        return "Error: Invalid first number.", ""

    # --------------------------------------------------------
    # Validate second number for binary operations
    # --------------------------------------------------------

    if operation in BINARY_OPERATIONS:

        if num2 is None:
            return "Please enter the second number.", ""

        try:
            num2 = float(num2)

        except (TypeError, ValueError):
            return "Error: Invalid second number.", ""

    # ========================================================
    # Addition
    # ========================================================

    if operation == "Addition (+)":

        result = num1 + num2

        return (
            format_number(result),
            f"{format_number(num1)} + {format_number(num2)} = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Subtraction
    # ========================================================

    if operation == "Subtraction (-)":

        result = num1 - num2

        return (
            format_number(result),
            f"{format_number(num1)} - {format_number(num2)} = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Multiplication
    # ========================================================

    if operation == "Multiplication (×)":

        result = num1 * num2

        return (
            format_number(result),
            f"{format_number(num1)} × {format_number(num2)} = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Division
    # ========================================================

    if operation == "Division (÷)":

        if num2 == 0:
            return "Error: Cannot divide by zero.", ""

        result = num1 / num2

        return (
            format_number(result),
            f"{format_number(num1)} ÷ {format_number(num2)} = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Power
    # ========================================================

    if operation == "Power (xʸ)":

        try:

            result = num1 ** num2

            if isinstance(result, complex):
                return (
                    "Error: Complex numbers are not supported.",
                    ""
                )

            if not math.isfinite(result):
                return (
                    "Error: Result is too large.",
                    ""
                )

            return (
                format_number(result),
                f"{format_number(num1)} ^ {format_number(num2)} = "
                f"{format_number(result)}"
            )

        except (OverflowError, ValueError):

            return (
                "Error: Cannot calculate this power.",
                ""
            )

    # ========================================================
    # Square Root
    # ========================================================

    if operation == "Square Root (√x)":

        if num1 < 0:

            return (
                "Error: Square root of a negative number is not real.",
                ""
            )

        result = math.sqrt(num1)

        return (
            format_number(result),
            f"√{format_number(num1)} = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Logarithm Base 10
    # ========================================================

    if operation == "Logarithm (log₁₀)":

        if num1 <= 0:

            return (
                "Error: Logarithm requires a positive number.",
                ""
            )

        result = math.log10(num1)

        return (
            format_number(result),
            f"log₁₀({format_number(num1)}) = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Natural Logarithm
    # ========================================================

    if operation == "Natural Log (ln)":

        if num1 <= 0:

            return (
                "Error: Natural logarithm requires a positive number.",
                ""
            )

        result = math.log(num1)

        return (
            format_number(result),
            f"ln({format_number(num1)}) = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Sine
    # ========================================================

    if operation == "Sine (sin)":

        result = math.sin(math.radians(num1))

        if abs(result) < 1e-12:
            result = 0.0

        return (
            format_number(result),
            f"sin({format_number(num1)}°) = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Cosine
    # ========================================================

    if operation == "Cosine (cos)":

        result = math.cos(math.radians(num1))

        if abs(result) < 1e-12:
            result = 0.0

        return (
            format_number(result),
            f"cos({format_number(num1)}°) = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Tangent
    # ========================================================

    if operation == "Tangent (tan)":

        radians = math.radians(num1)

        if abs(math.cos(radians)) < 1e-12:

            return (
                "Error: Tangent is undefined at this angle.",
                ""
            )

        result = math.tan(radians)

        if abs(result) < 1e-12:
            result = 0.0

        return (
            format_number(result),
            f"tan({format_number(num1)}°) = "
            f"{format_number(result)}"
        )

    # ========================================================
    # Factorial
    # ========================================================

    if operation == "Factorial (n!)":

        if num1 < 0:

            return (
                "Error: Factorial requires a non-negative number.",
                ""
            )

        if not num1.is_integer():

            return (
                "Error: Factorial requires a whole number.",
                ""
            )

        if num1 > 170:

            return (
                "Error: Number is too large for factorial.",
                ""
            )

        result = math.factorial(int(num1))

        return (
            format_number(result),
            f"{format_number(num1)}! = "
            f"{format_number(result)}"
        )

    return "Error: Invalid operation.", ""


# ============================================================
# Second Number Visibility
# ============================================================

def update_second_number(operation):

    if operation in BINARY_OPERATIONS:

        return gr.Number(
            label="Second Number",
            placeholder="Enter second number",
            visible=True
        )

    return gr.Number(
        label="Second Number",
        placeholder="Not required",
        visible=False
    )


# ============================================================
# Clear Calculator
# ============================================================

def clear_calculator():

    return (
        None,
        None,
        "Addition (+)",
        "",
        ""
    )


# ============================================================
# Custom CSS
# ============================================================

CUSTOM_CSS = """

body {
    background: #f5f7fb;
}

.gradio-container {
    max-width: 1100px !important;
    margin: auto !important;
    padding: 20px !important;
}

.header {
    text-align: center;
    padding: 25px 15px;
    margin-bottom: 20px;
}

.header h1 {
    font-size: 38px;
    font-weight: 700;
    margin-bottom: 8px;
}

.header p {
    font-size: 16px;
    opacity: 0.75;
}

.calc-card {
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    padding: 25px;
    background: white;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.06);
}

.result-box textarea {
    font-size: 24px !important;
    font-weight: 600 !important;
    text-align: center !important;
}

.calculation-box textarea {
    font-size: 17px !important;
    text-align: center !important;
}

.footer {
    text-align: center;
    margin-top: 25px;
    padding: 15px;
    font-size: 14px;
    opacity: 0.65;
}

@media (max-width: 700px) {

    .gradio-container {
        padding: 10px !important;
    }

    .header h1 {
        font-size: 30px;
    }

    .calc-card {
        padding: 18px;
    }
}

"""


# ============================================================
# Gradio Application
# ============================================================

with gr.Blocks(
    title="Scientific Calculator"
) as app:

    # --------------------------------------------------------
    # Header
    # --------------------------------------------------------

    gr.HTML(
        """
        <div class="header">

            <h1>Scientific Calculator</h1>

            <p>
                Perform basic and scientific mathematical
                calculations quickly and easily.
            </p>

        </div>
        """
    )

    # --------------------------------------------------------
    # Main Layout
    # --------------------------------------------------------

    with gr.Row():

        # ====================================================
        # Calculator Input
        # ====================================================

        with gr.Column(elem_classes="calc-card"):

            gr.Markdown("### Calculator")

            operation = gr.Dropdown(
                choices=OPERATIONS,
                value="Addition (+)",
                label="Select Operation"
            )

            num1 = gr.Number(
                label="First Number",
                placeholder="Enter first number"
            )

            num2 = gr.Number(
                label="Second Number",
                placeholder="Enter second number"
            )

            with gr.Row():

                calculate_button = gr.Button(
                    "Calculate",
                    variant="primary"
                )

                clear_button = gr.Button(
                    "Clear",
                    variant="secondary"
                )

        # ====================================================
        # Result
        # ====================================================

        with gr.Column(elem_classes="calc-card"):

            gr.Markdown("### Result")

            result = gr.Textbox(
                label="Answer",
                placeholder="Your result will appear here",
                interactive=False,
                elem_classes="result-box"
            )

            calculation = gr.Textbox(
                label="Calculation",
                placeholder="Calculation details will appear here",
                interactive=False,
                elem_classes="calculation-box"
            )


    # --------------------------------------------------------
    # Footer
    # --------------------------------------------------------

    gr.HTML(
        """
        <div class="footer">
            Scientific Calculator • Python + Gradio
        </div>
        """
    )

    # ========================================================
    # Events
    # ========================================================

    operation.change(
        fn=update_second_number,
        inputs=operation,
        outputs=num2
    )

    calculate_button.click(
        fn=calculate,
        inputs=[operation, num1, num2],
        outputs=[result, calculation]
    )

    clear_button.click(
        fn=clear_calculator,
        inputs=[],
        outputs=[
            num1,
            num2,
            operation,
            result,
            calculation
        ]
    )


# ============================================================
# Launch
# ============================================================

if __name__ == "__main__":

    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        ssr_mode=False,
        css=CUSTOM_CSS
    )