File size: 1,692 Bytes
5a89251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import gradio as gr

MASS_FACTORS = {
    "kg": 1000.0,
    "g": 1.0,
    "lb": 453.59237,
    "oz": 28.349523125
}

UNITS = [
    "Mass: kg", "Mass: g", "Mass: lb", "Mass: oz",
    "Temp: C", "Temp: F", "Temp: K"
]

def convert(value, from_label, to_label):
    try:
        x = float(value)
    except:
        return "Error: enter a numeric value."

    fcat, funit = from_label.split(": ")
    tcat, tunit = to_label.split(": ")

    if fcat != tcat:
        return f"Error: can't convert between categories ({fcat} vs {tcat})."

    if fcat == "Mass":
        grams = x * MASS_FACTORS[funit]
        out = grams / MASS_FACTORS[tunit]
        return f"{out:.6f} {tunit}"
    else:
        if funit == tunit:
            return f"{x:.6f} {tunit}"

        # to Celsius
        if funit == "C":
            c = x
        elif funit == "F":
            c = (x - 32.0) * 5.0/9.0
        elif funit == "K":
            c = x - 273.15
        else:
            return "Error: unknown temperature unit."

        # Celsius -> target
        if tunit == "C":
            out = c
        elif tunit == "F":
            out = c * 9.0/5.0 + 32.0
        elif tunit == "K":
            out = c + 273.15
        else:
            return "Error: unknown temperature unit."

        return f"{out:.6f} {tunit}"

iface = gr.Interface(
    fn=convert,
    inputs=[
        gr.Number(label="Value", value=1),
        gr.Dropdown(UNITS, label="From"),
        gr.Dropdown(UNITS, label="To"),
    ],
    outputs=gr.Textbox(label="Result"),
    title="Simple Unit Converter",
    description="Converts Mass (kg, g, lb, oz) and Temperature (C, F, K)."
)

if __name__ == "__main__":
    iface.launch()