# app.py import gradio as gr # Conversion function def convert_units(value, conversion_type, from_unit, to_unit): try: value = float(value) except ValueError: return "Please enter a numeric value" # Weight conversions weight_units = {"kg": 1, "gram": 1000, "lb": 2.20462} if conversion_type == "Weight": return round(value * weight_units[to_unit] / weight_units[from_unit], 4) # Length conversions length_units = {"meter": 1, "cm": 100, "feet": 3.28084, "inch": 39.3701} if conversion_type == "Length": return round(value * length_units[to_unit] / length_units[from_unit], 4) # Temperature conversions if conversion_type == "Temperature": if from_unit == "Celsius" and to_unit == "Fahrenheit": return round((value * 9/5) + 32, 2) elif from_unit == "Fahrenheit" and to_unit == "Celsius": return round((value - 32) * 5/9, 2) elif from_unit == to_unit: return value return "Conversion not supported" # Dropdown options conversion_types = ["Weight", "Length", "Temperature"] weight_units = ["kg", "gram", "lb"] length_units = ["meter", "cm", "feet", "inch"] temperature_units = ["Celsius", "Fahrenheit"] # Function to get units based on type def get_units(conversion_type): if conversion_type == "Weight": return gr.update(choices=weight_units, value="kg"), gr.update(choices=weight_units, value="gram") elif conversion_type == "Length": return gr.update(choices=length_units, value="meter"), gr.update(choices=length_units, value="cm") elif conversion_type == "Temperature": return gr.update(choices=temperature_units, value="Celsius"), gr.update(choices=temperature_units, value="Fahrenheit") # Gradio Interface with gr.Blocks() as demo: gr.Markdown("# 🌐 Unit Conversion App") conversion_type = gr.Dropdown(conversion_types, label="Conversion Type", value="Weight") from_unit = gr.Dropdown(weight_units, label="From Unit", value="kg") to_unit = gr.Dropdown(weight_units, label="To Unit", value="gram") value_input = gr.Textbox(label="Value to Convert", value="1") result_output = gr.Textbox(label="Converted Value") convert_button = gr.Button("Convert") # Update unit dropdowns dynamically conversion_type.change(fn=get_units, inputs=conversion_type, outputs=[from_unit, to_unit]) # Convert on button click convert_button.click(fn=convert_units, inputs=[value_input, conversion_type, from_unit, to_unit], outputs=result_output) demo.launch()