File size: 3,786 Bytes
e52201b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
app.py - Simple Unit Converter Web App using Gradio
---------------------------------------------------
Supports: Mass, Length, Volume, Temperature.
Beginner-friendly code with inline comments.

How to run in Google Colab:
1. !pip install -r requirements.txt
2. !python app.py
3. Click the "share" link generated by Gradio.
"""

import gradio as gr

# --- STEP 1: Define available units and conversion logic ---

# Conversion factors relative to a base unit for each category
UNIT_MAP = {
    "Mass": {       # base = grams
        "kg": 1000.0,
        "g": 1.0,
        "mg": 0.001,
        "lb": 453.592,
        "oz": 28.3495,
    },
    "Length": {     # base = meters
        "mm": 0.001,
        "cm": 0.01,
        "m": 1.0,
        "km": 1000.0,
        "in": 0.0254,
        "ft": 0.3048,
        "yd": 0.9144,
        "mi": 1609.34,
    },
    "Volume": {     # base = liters
        "mL": 0.001,
        "L": 1.0,
        "m³": 1000.0,
        "cup": 0.24,
        "pint": 0.47,
        "gallon": 3.785,
    },
}

# Special case: Temperature uses formulas (not multipliers)
TEMP_UNITS = ["C", "F", "K"]

# --- STEP 2: Conversion functions ---

def convert_temperature(value, from_u, to_u):
    """Convert temperature between Celsius, Fahrenheit, Kelvin."""
    # convert input to Celsius
    if from_u == "C":
        c = value
    elif from_u == "F":
        c = (value - 32) * 5/9
    elif from_u == "K":
        c = value - 273.15
    else:
        return "Unknown unit"

    # convert Celsius to target
    if to_u == "C":
        return c
    elif to_u == "F":
        return c * 9/5 + 32
    elif to_u == "K":
        return c + 273.15

def convert_linear(value, from_u, to_u, category):
    """Convert Mass, Length, Volume using base-unit multipliers."""
    mapping = UNIT_MAP[category]
    base_value = value * mapping[from_u]       # step 1: to base
    return base_value / mapping[to_u]          # step 2: to target

def convert(value, from_unit, to_unit, category):
    """Main function used by Gradio."""
    # --- Input validation ---
    try:
        val = float(value)
    except:
        return "❌ Please enter a numeric value."

    try:
        if category == "Temperature":
            result = convert_temperature(val, from_unit, to_unit)
        else:
            result = convert_linear(val, from_unit, to_unit, category)
    except Exception as e:
        return f"⚠️ Error: {e}"

    return f"{val} {from_unit} = {result:.4g} {to_unit}"

# --- STEP 3: Define unit lists for dropdown menus ---
UNITS_BY_CATEGORY = {
    "Mass": list(UNIT_MAP["Mass"].keys()),
    "Length": list(UNIT_MAP["Length"].keys()),
    "Volume": list(UNIT_MAP["Volume"].keys()),
    "Temperature": TEMP_UNITS,
}

# --- STEP 4: Build Gradio UI ---
with gr.Blocks() as demo:
    gr.Markdown("## 🔄 Simple Unit Converter")

    # Row: category + unit dropdowns
    with gr.Row():
        category = gr.Dropdown(list(UNITS_BY_CATEGORY.keys()), value="Mass", label="Category")
        from_unit = gr.Dropdown(UNITS_BY_CATEGORY["Mass"], label="From Unit")
        to_unit = gr.Dropdown(UNITS_BY_CATEGORY["Mass"], label="To Unit")

    # Input + button + output
    value_input = gr.Number(value=1, label="Value")
    convert_btn = gr.Button("Convert")
    output = gr.Textbox(label="Result")

    # --- Update dropdowns when category changes ---
    def update_units(cat):
        units = UNITS_BY_CATEGORY[cat]
        return gr.update(choices=units, value=units[0]), gr.update(choices=units, value=units[1])

    category.change(update_units, category, [from_unit, to_unit])
    convert_btn.click(convert, [value_input, from_unit, to_unit, category], output)

# Run app (share=True gives a public link in Colab)
if __name__ == "__main__":
    demo.launch(share=True)