Spaces:
Sleeping
Sleeping
File size: 2,996 Bytes
687f8d1 |
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 |
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()
|