| import gradio as gr |
|
|
| |
| def kg_to_g(value): return value * 1000 |
| def g_to_kg(value): return value / 1000 |
| def m_to_cm(value): return value * 100 |
| def cm_to_m(value): return value / 100 |
| def m_to_ft(value): return value * 3.28084 |
| def ft_to_m(value): return value / 3.28084 |
| def c_to_f(value): return (value * 9/5) + 32 |
| def f_to_c(value): return (value - 32) * 5/9 |
|
|
| |
| def convert_value(category, from_unit, to_unit, input_value): |
| try: |
| x = float(input_value) |
| except: |
| return "⚠️ Please enter a valid number." |
|
|
| if category == "Mass": |
| if from_unit == "kg" and to_unit == "g": result = kg_to_g(x) |
| elif from_unit == "g" and to_unit == "kg": result = g_to_kg(x) |
| elif from_unit == to_unit: result = x |
| else: return "Conversion not supported in Mass category." |
|
|
| elif category == "Length": |
| if from_unit == "m" and to_unit == "cm": result = m_to_cm(x) |
| elif from_unit == "cm" and to_unit == "m": result = cm_to_m(x) |
| elif from_unit == "m" and to_unit == "ft": result = m_to_ft(x) |
| elif from_unit == "ft" and to_unit == "m": result = ft_to_m(x) |
| elif from_unit == to_unit: result = x |
| else: return "Conversion not supported in Length category." |
|
|
| elif category == "Temperature": |
| if from_unit == "°C" and to_unit == "°F": result = c_to_f(x) |
| elif from_unit == "°F" and to_unit == "°C": result = f_to_c(x) |
| elif from_unit == to_unit: result = x |
| else: return "Conversion not supported in Temperature category." |
|
|
| else: |
| return "Unknown category." |
|
|
| return f"{x} {from_unit} = {round(result, 4)} {to_unit}" |
|
|
| |
| categories = ["Mass", "Length", "Temperature"] |
| units_map = { |
| "Mass": ["kg", "g"], |
| "Length": ["m", "cm", "ft"], |
| "Temperature": ["°C", "°F"] |
| } |
|
|
| def update_units(cat): |
| return ( |
| gr.update(choices=units_map[cat], value=units_map[cat][0]), |
| gr.update(choices=units_map[cat], value=units_map[cat][1]), |
| ) |
|
|
| with gr.Blocks() as demo: |
| gr.Markdown("# 🧮 Unit Converter App\nConvert mass, length, and temperature easily!") |
| with gr.Row(): |
| category = gr.Dropdown(label="Category", choices=categories, value="Mass") |
| from_unit = gr.Dropdown(label="From unit", choices=units_map["Mass"], value="kg") |
| to_unit = gr.Dropdown(label="To unit", choices=units_map["Mass"], value="g") |
| value = gr.Textbox(label="Value to convert", placeholder="e.g., 12.5") |
| convert_btn = gr.Button("Convert") |
| output = gr.Textbox(label="Result", interactive=False) |
| |
| category.change(fn=update_units, inputs=category, outputs=[from_unit, to_unit]) |
| convert_btn.click(fn=convert_value, inputs=[category, from_unit, to_unit, value], outputs=output) |
|
|
| demo.launch() |
|
|