Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| # Conversion logic | |
| def convert_units(category, from_unit, to_unit, value): | |
| try: | |
| value = float(value) | |
| except: | |
| return "Invalid input value" | |
| conversions = { | |
| "Length": { | |
| "units": ["Meters", "Kilometers", "Feet", "Miles"], | |
| "factors": { | |
| "Meters": 1, | |
| "Kilometers": 1000, | |
| "Feet": 0.3048, | |
| "Miles": 1609.34 | |
| } | |
| }, | |
| "Weight": { | |
| "units": ["Grams", "Kilograms", "Pounds", "Ounces"], | |
| "factors": { | |
| "Grams": 1, | |
| "Kilograms": 1000, | |
| "Pounds": 453.592, | |
| "Ounces": 28.3495 | |
| } | |
| }, | |
| "Temperature": { | |
| "units": ["Celsius", "Fahrenheit", "Kelvin"] | |
| } | |
| } | |
| if category == "Temperature": | |
| if from_unit == to_unit: | |
| return value | |
| if from_unit == "Celsius": | |
| if to_unit == "Fahrenheit": | |
| return (value * 9/5) + 32 | |
| elif to_unit == "Kelvin": | |
| return value + 273.15 | |
| elif from_unit == "Fahrenheit": | |
| if to_unit == "Celsius": | |
| return (value - 32) * 5/9 | |
| elif to_unit == "Kelvin": | |
| return (value - 32) * 5/9 + 273.15 | |
| elif from_unit == "Kelvin": | |
| if to_unit == "Celsius": | |
| return value - 273.15 | |
| elif to_unit == "Fahrenheit": | |
| return (value - 273.15) * 9/5 + 32 | |
| else: | |
| base_value = value * conversions[category]["factors"][from_unit] | |
| return base_value / conversions[category]["factors"][to_unit] | |
| # UI layout | |
| categories = ["Length", "Weight", "Temperature"] | |
| units = { | |
| "Length": ["Meters", "Kilometers", "Feet", "Miles"], | |
| "Weight": ["Grams", "Kilograms", "Pounds", "Ounces"], | |
| "Temperature": ["Celsius", "Fahrenheit", "Kelvin"] | |
| } | |
| def unit_converter_app(category, from_unit, to_unit, value): | |
| result = convert_units(category, from_unit, to_unit, value) | |
| return f"{value} {from_unit} = {result:.4f} {to_unit}" | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# ๐ Unit Converter App") | |
| category_input = gr.Dropdown(choices=categories, label="Category", value="Length") | |
| from_unit_input = gr.Dropdown(choices=units["Length"], label="From Unit") | |
| to_unit_input = gr.Dropdown(choices=units["Length"], label="To Unit") | |
| value_input = gr.Textbox(label="Enter value") | |
| output = gr.Textbox(label="Result") | |
| def update_units(category): | |
| return gr.update(choices=units[category], value=units[category][0]), gr.update(choices=units[category], value=units[category][1]) | |
| category_input.change(fn=update_units, inputs=category_input, outputs=[from_unit_input, to_unit_input]) | |
| convert_button = gr.Button("Convert") | |
| convert_button.click(fn=unit_converter_app, inputs=[category_input, from_unit_input, to_unit_input, value_input], outputs=output) | |
| demo.launch() | |