import gradio as gr # Conversion logic def convert_units(value, from_unit, to_unit, category): conversions = { "Length": { "Meter": 1, "Kilometer": 1000, "Centimeter": 0.01, "Millimeter": 0.001, "Mile": 1609.34, "Yard": 0.9144, "Foot": 0.3048, "Inch": 0.0254, }, "Weight": { "Kilogram": 1, "Gram": 0.001, "Milligram": 0.000001, "Pound": 0.453592, "Ounce": 0.0283495, }, "Temperature": None # handled separately } if category == "Temperature": if from_unit == to_unit: return value elif from_unit == "Celsius" and to_unit == "Fahrenheit": return (value * 9/5) + 32 elif from_unit == "Fahrenheit" and to_unit == "Celsius": return (value - 32) * 5/9 elif from_unit == "Celsius" and to_unit == "Kelvin": return value + 273.15 elif from_unit == "Kelvin" and to_unit == "Celsius": return value - 273.15 elif from_unit == "Fahrenheit" and to_unit == "Kelvin": return (value - 32) * 5/9 + 273.15 elif from_unit == "Kelvin" and to_unit == "Fahrenheit": return (value - 273.15) * 9/5 + 32 else: base_value = value * conversions[category][from_unit] result = base_value / conversions[category][to_unit] return result def update_units(category): if category == "Length": units = ["Meter", "Kilometer", "Centimeter", "Millimeter", "Mile", "Yard", "Foot", "Inch"] elif category == "Weight": units = ["Kilogram", "Gram", "Milligram", "Pound", "Ounce"] elif category == "Temperature": units = ["Celsius", "Fahrenheit", "Kelvin"] return gr.update(choices=units, value=units[0]), gr.update(choices=units, value=units[1]) with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("## 🌡️ Universal Unit Converter\nConvert between different unit categories easily!") with gr.Row(): category = gr.Dropdown(["Length", "Weight", "Temperature"], label="Select Category", value="Length") with gr.Row(): value = gr.Number(label="Enter Value", value=1) with gr.Row(): from_unit = gr.Dropdown([], label="From Unit") to_unit = gr.Dropdown([], label="To Unit") category.change(fn=update_units, inputs=category, outputs=[from_unit, to_unit]) convert_btn = gr.Button("Convert") output = gr.Textbox(label="Converted Value") convert_btn.click(fn=convert_units, inputs=[value, from_unit, to_unit, category], outputs=output) demo.launch()