Spaces:
Sleeping
Sleeping
| """ | |
| app.py - Simple Unit Converter Web App using Gradio | |
| --------------------------------------------------- | |
| Supports: Mass, Length, Volume, Temperature. | |
| Beginner-friendly code with inline comments. | |
| How to run in Google Colab: | |
| 1. !pip install -r requirements.txt | |
| 2. !python app.py | |
| 3. Click the "share" link generated by Gradio. | |
| """ | |
| import gradio as gr | |
| # --- STEP 1: Define available units and conversion logic --- | |
| # Conversion factors relative to a base unit for each category | |
| UNIT_MAP = { | |
| "Mass": { # base = grams | |
| "kg": 1000.0, | |
| "g": 1.0, | |
| "mg": 0.001, | |
| "lb": 453.592, | |
| "oz": 28.3495, | |
| }, | |
| "Length": { # base = meters | |
| "mm": 0.001, | |
| "cm": 0.01, | |
| "m": 1.0, | |
| "km": 1000.0, | |
| "in": 0.0254, | |
| "ft": 0.3048, | |
| "yd": 0.9144, | |
| "mi": 1609.34, | |
| }, | |
| "Volume": { # base = liters | |
| "mL": 0.001, | |
| "L": 1.0, | |
| "m³": 1000.0, | |
| "cup": 0.24, | |
| "pint": 0.47, | |
| "gallon": 3.785, | |
| }, | |
| } | |
| # Special case: Temperature uses formulas (not multipliers) | |
| TEMP_UNITS = ["C", "F", "K"] | |
| # --- STEP 2: Conversion functions --- | |
| def convert_temperature(value, from_u, to_u): | |
| """Convert temperature between Celsius, Fahrenheit, Kelvin.""" | |
| # convert input to Celsius | |
| if from_u == "C": | |
| c = value | |
| elif from_u == "F": | |
| c = (value - 32) * 5/9 | |
| elif from_u == "K": | |
| c = value - 273.15 | |
| else: | |
| return "Unknown unit" | |
| # convert Celsius to target | |
| if to_u == "C": | |
| return c | |
| elif to_u == "F": | |
| return c * 9/5 + 32 | |
| elif to_u == "K": | |
| return c + 273.15 | |
| def convert_linear(value, from_u, to_u, category): | |
| """Convert Mass, Length, Volume using base-unit multipliers.""" | |
| mapping = UNIT_MAP[category] | |
| base_value = value * mapping[from_u] # step 1: to base | |
| return base_value / mapping[to_u] # step 2: to target | |
| def convert(value, from_unit, to_unit, category): | |
| """Main function used by Gradio.""" | |
| # --- Input validation --- | |
| try: | |
| val = float(value) | |
| except: | |
| return "❌ Please enter a numeric value." | |
| try: | |
| if category == "Temperature": | |
| result = convert_temperature(val, from_unit, to_unit) | |
| else: | |
| result = convert_linear(val, from_unit, to_unit, category) | |
| except Exception as e: | |
| return f"⚠️ Error: {e}" | |
| return f"{val} {from_unit} = {result:.4g} {to_unit}" | |
| # --- STEP 3: Define unit lists for dropdown menus --- | |
| UNITS_BY_CATEGORY = { | |
| "Mass": list(UNIT_MAP["Mass"].keys()), | |
| "Length": list(UNIT_MAP["Length"].keys()), | |
| "Volume": list(UNIT_MAP["Volume"].keys()), | |
| "Temperature": TEMP_UNITS, | |
| } | |
| # --- STEP 4: Build Gradio UI --- | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 🔄 Simple Unit Converter") | |
| # Row: category + unit dropdowns | |
| with gr.Row(): | |
| category = gr.Dropdown(list(UNITS_BY_CATEGORY.keys()), value="Mass", label="Category") | |
| from_unit = gr.Dropdown(UNITS_BY_CATEGORY["Mass"], label="From Unit") | |
| to_unit = gr.Dropdown(UNITS_BY_CATEGORY["Mass"], label="To Unit") | |
| # Input + button + output | |
| value_input = gr.Number(value=1, label="Value") | |
| convert_btn = gr.Button("Convert") | |
| output = gr.Textbox(label="Result") | |
| # --- Update dropdowns when category changes --- | |
| def update_units(cat): | |
| units = UNITS_BY_CATEGORY[cat] | |
| return gr.update(choices=units, value=units[0]), gr.update(choices=units, value=units[1]) | |
| category.change(update_units, category, [from_unit, to_unit]) | |
| convert_btn.click(convert, [value_input, from_unit, to_unit, category], output) | |
| # Run app (share=True gives a public link in Colab) | |
| if __name__ == "__main__": | |
| demo.launch(share=True) | |