Spaces:
Sleeping
Sleeping
| # app.py | |
| import gradio as gr | |
| MASS_FACTORS = { | |
| "kg": 1000.0, | |
| "g": 1.0, | |
| "lb": 453.59237, | |
| "oz": 28.349523125 | |
| } | |
| UNITS = [ | |
| "Mass: kg", "Mass: g", "Mass: lb", "Mass: oz", | |
| "Temp: C", "Temp: F", "Temp: K" | |
| ] | |
| def convert(value, from_label, to_label): | |
| try: | |
| x = float(value) | |
| except: | |
| return "Error: enter a numeric value." | |
| fcat, funit = from_label.split(": ") | |
| tcat, tunit = to_label.split(": ") | |
| if fcat != tcat: | |
| return f"Error: can't convert between categories ({fcat} vs {tcat})." | |
| if fcat == "Mass": | |
| grams = x * MASS_FACTORS[funit] | |
| out = grams / MASS_FACTORS[tunit] | |
| return f"{out:.6f} {tunit}" | |
| else: | |
| if funit == tunit: | |
| return f"{x:.6f} {tunit}" | |
| # to Celsius | |
| if funit == "C": | |
| c = x | |
| elif funit == "F": | |
| c = (x - 32.0) * 5.0/9.0 | |
| elif funit == "K": | |
| c = x - 273.15 | |
| else: | |
| return "Error: unknown temperature unit." | |
| # Celsius -> target | |
| if tunit == "C": | |
| out = c | |
| elif tunit == "F": | |
| out = c * 9.0/5.0 + 32.0 | |
| elif tunit == "K": | |
| out = c + 273.15 | |
| else: | |
| return "Error: unknown temperature unit." | |
| return f"{out:.6f} {tunit}" | |
| iface = gr.Interface( | |
| fn=convert, | |
| inputs=[ | |
| gr.Number(label="Value", value=1), | |
| gr.Dropdown(UNITS, label="From"), | |
| gr.Dropdown(UNITS, label="To"), | |
| ], | |
| outputs=gr.Textbox(label="Result"), | |
| title="Simple Unit Converter", | |
| description="Converts Mass (kg, g, lb, oz) and Temperature (C, F, K)." | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |