unit-convertor / app.py
zeeshan4801's picture
Create app.py
71304a0 verified
# app.py
# Simple Unit Converter (Gradio) - ready for Hugging Face Spaces
import gradio as gr
# ----------------------------
# Conversion data / helpers
# ----------------------------
CONVERSIONS = {
"Length": {
"m": 1.0,
"cm": 0.01,
"mm": 0.001,
"km": 1000.0,
"in": 0.0254,
"ft": 0.3048,
"yd": 0.9144,
"mi": 1609.344
},
"Mass": {
"kg": 1.0,
"g": 0.001,
"mg": 1e-6,
"lb": 0.45359237,
"oz": 0.028349523125
},
"Volume": {
"L": 1.0,
"mL": 0.001,
"m^3": 1000.0,
"cup": 0.2365882365,
"pt": 0.473176473,
"gal": 3.785411784
},
"Temperature": ["C", "F", "K"]
}
def convert_linear(value: float, from_unit: str, to_unit: str, mapping: dict) -> float:
if from_unit not in mapping or to_unit not in mapping:
raise ValueError("Unknown unit for this category.")
value_in_base = value * mapping[from_unit]
return value_in_base / mapping[to_unit]
def temp_to_c(value: float, unit: str) -> float:
unit = unit.upper()
if unit == "C":
return value
if unit == "F":
return (value - 32.0) * 5.0 / 9.0
if unit == "K":
return value - 273.15
raise ValueError("Unsupported temperature unit")
def c_to_temp(celsius: float, unit: str) -> float:
unit = unit.upper()
if unit == "C":
return celsius
if unit == "F":
return celsius * 9.0 / 5.0 + 32.0
if unit == "K":
return celsius + 273.15
raise ValueError("Unsupported temperature unit")
def convert_temperature(value: float, from_unit: str, to_unit: str) -> float:
c = temp_to_c(value, from_unit)
return c_to_temp(c, to_unit)
# ----------------------------
# Gradio UI callbacks
# ----------------------------
def update_unit_dropdowns(category: str):
if category == "Temperature":
units = CONVERSIONS["Temperature"]
else:
units = list(CONVERSIONS[category].keys())
from_default = units[0]
to_default = units[1] if len(units) > 1 else units[0]
return gr.update(choices=units, value=from_default), gr.update(choices=units, value=to_default)
def perform_conversion(value, from_unit, to_unit, category):
try:
if value is None:
return "Please enter a numeric value."
if category == "Temperature":
result = convert_temperature(float(value), from_unit, to_unit)
return f"{result:.6g} {to_unit}"
else:
mapping = CONVERSIONS[category]
result = convert_linear(float(value), from_unit, to_unit, mapping)
return f"{result:.6g} {to_unit}"
except Exception as e:
return f"Error: {e}"
# ----------------------------
# Build Gradio Blocks UI
# ----------------------------
with gr.Blocks(title="Simple Unit Converter") as demo:
gr.Markdown("## Simple Unit Converter\nConvert between Length, Mass, Volume and Temperature units.")
category_dd = gr.Dropdown(choices=list(CONVERSIONS.keys()), label="Category", value="Length")
from_dd = gr.Dropdown(choices=list(CONVERSIONS["Length"].keys()), label="From unit")
to_dd = gr.Dropdown(choices=list(CONVERSIONS["Length"].keys()), label="To unit")
val_in = gr.Number(value=1.0, label="Value to convert")
convert_btn = gr.Button("Convert")
result_out = gr.Textbox(label="Result", interactive=False)
category_dd.change(fn=update_unit_dropdowns, inputs=category_dd, outputs=[from_dd, to_dd])
convert_btn.click(fn=perform_conversion, inputs=[val_in, from_dd, to_dd, category_dd], outputs=result_out)
# IMPORTANT for Spaces: do NOT use share=True (that's for Colab).
if __name__ == "__main__":
demo.launch()