Unit-Converter / app.py
SabaAnver's picture
Create app.py
4168d77 verified
# app.py
# Simple Unit Converter for Hugging Face Spaces (Gradio)
# No models or APIs required — pure Python
import gradio as gr
# Base units: Length -> meter, Mass -> kilogram, Volume -> liter
UNITS = {
"Length": {
"m": 1.0,
"cm": 0.01,
"km": 1000.0,
"in": 0.0254,
"ft": 0.3048,
"yd": 0.9144,
"mi": 1609.344,
},
"Mass": {
"kg": 1.0,
"g": 0.001,
"lb": 0.45359237,
"oz": 0.028349523125,
},
"Volume": {
"L": 1.0,
"mL": 0.001,
"gal": 3.785411784, # US liquid gallon
"qt": 0.946352946, # US liquid quart
"cup": 0.2365882365, # US cup
}
}
TEMP_UNITS = ["C", "F", "K"]
CATEGORIES = ["Length", "Mass", "Temperature", "Volume"]
def convert_temperature(value: float, from_u: str, to_u: str) -> float:
if from_u == "K" and value < 0:
raise ValueError("Kelvin cannot be negative.")
# to Celsius
if from_u == "C":
c = value
elif from_u == "F":
c = (value - 32.0) * 5.0 / 9.0
elif from_u == "K":
c = value - 273.15
else:
raise ValueError("Unknown temperature unit.")
# from Celsius to target
if to_u == "C":
return c
elif to_u == "F":
return c * 9.0 / 5.0 + 32.0
elif to_u == "K":
return c + 273.15
else:
raise ValueError("Unknown temperature unit.")
def convert_via_base(value: float, category: str, from_u: str, to_u: str) -> float:
factors = UNITS[category]
if from_u not in factors or to_u not in factors:
raise ValueError("Unsupported unit for this category.")
base_val = value * factors[from_u] # to base (meter/kg/liter)
return base_val / factors[to_u]
def convert(category: str, value, from_unit: str, to_unit: str, decimals: int):
if value is None or str(value).strip() == "":
return "Please enter a number."
try:
value = float(value)
except:
return "Please enter a valid number (e.g., 12.5)."
try:
if category == "Temperature":
result = convert_temperature(value, from_unit, to_unit)
else:
result = convert_via_base(value, category, from_unit, to_unit)
fmt = f"{{:.{int(decimals)}f}}"
return f"{value} {from_unit} = {fmt.format(result)} {to_unit}"
except Exception as e:
return f"Error: {e}"
def units_for_category(category: str):
if category == "Temperature":
choices = TEMP_UNITS
else:
choices = list(UNITS[category].keys())
default_from = choices[0]
default_to = choices[1] if len(choices) > 1 else choices[0]
return (
gr.update(choices=choices, value=default_from),
gr.update(choices=choices, value=default_to),
)
with gr.Blocks(title="Simple Unit Converter") as demo:
gr.Markdown(
"""
# Simple Unit Converter
A tiny web app to convert units (Length, Mass, Volume, Temperature).
No models or APIs — pure Python.
"""
)
with gr.Row():
category = gr.Dropdown(CATEGORIES, value="Length", label="Category")
decimals = gr.Slider(minimum=0, maximum=10, step=1, value=3, label="Decimal places")
value_in = gr.Number(label="Input value", value=1.0)
with gr.Row():
from_unit = gr.Dropdown(list(UNITS["Length"].keys()), value="m", label="From unit")
to_unit = gr.Dropdown(list(UNITS["Length"].keys()), value="ft", label="To unit")
convert_btn = gr.Button("Convert")
output = gr.Textbox(label="Result", lines=1)
category.change(fn=units_for_category, inputs=category, outputs=[from_unit, to_unit])
convert_btn.click(fn=convert, inputs=[category, value_in, from_unit, to_unit, decimals], outputs=output)
gr.Examples(
examples=[
["Length", 1, "m", "ft", 3],
["Length", 12, "in", "cm", 2],
["Mass", 2.5, "kg", "lb", 3],
["Volume", 3, "L", "gal", 4],
["Temperature", 100, "C", "F", 1],
["Temperature", 300, "K", "C", 2],
],
inputs=[category, value_in, from_unit, to_unit, decimals],
label="Examples (click to fill the form)"
)
if __name__ == "__main__":
# Spaces runs your script and will serve the Gradio app automatically.
demo.launch()