imfakhar/Unit-Converter
0
1import gradio as gr2 3# Define conversion functions4def convert_units(category, from_unit, to_unit, value, precision):5 try:6 value = float(value)7 except:8 return "Please enter a valid number"9 10 # Length conversions (base unit: meters)11 if category == "Length":12 length_factors = {13 "Meters": 1,14 "Kilometers": 1000,15 "Centimeters": 0.01,16 "Millimeters": 0.001,17 "Miles": 1609.34,18 "Yards": 0.9144,19 "Feet": 0.3048,20 "Inches": 0.0254,21 "Nautical Miles": 185222 }23 result = value * length_factors[from_unit] / length_factors[to_unit]24 25 # Mass conversions (base unit: kilograms)26 elif category == "Mass":27 mass_factors = {28 "Kilograms": 1,29 "Grams": 0.001,30 "Milligrams": 0.000001,31 "Pounds": 0.453592,32 "Ounces": 0.0283495,33 "Tons": 907.185,34 "Metric Tons": 1000,35 "Stones": 6.3502936 }37 result = value * mass_factors[from_unit] / mass_factors[to_unit]38 39 # Temperature conversions (special handling)40 elif category == "Temperature":41 if from_unit == "Celsius":42 if to_unit == "Fahrenheit":43 result = (value * 9/5) + 3244 elif to_unit == "Kelvin":45 result = value + 273.1546 else:47 result = value48 elif from_unit == "Fahrenheit":49 if to_unit == "Celsius":50 result = (value - 32) * 5/951 elif to_unit == "Kelvin":52 result = (value - 32) * 5/9 + 273.1553 else:54 result = value55 elif from_unit == "Kelvin":56 if to_unit == "Celsius":57 result = value - 273.1558 elif to_unit == "Fahrenheit":59 result = (value - 273.15) * 9/5 + 3260 else:61 result = value62 63 # Volume conversions (base unit: liters)64 elif category == "Volume":65 volume_factors = {66 "Liters": 1,67 "Milliliters": 0.001,68 "Gallons": 3.78541,69 "Quarts": 0.946353,70 "Pints": 0.473176,71 "Cups": 0.24,72 "Fluid Ounces": 0.0295735,73 "Cubic Meters": 1000,74 "Cubic Feet": 28.3168,75 "Cubic Inches": 0.016387176 }77 result = value * volume_factors[from_unit] / volume_factors[to_unit]78 79 # Time conversions (base unit: seconds)80 elif category == "Time":81 time_factors = {82 "Seconds": 1,83 "Milliseconds": 0.001,84 "Minutes": 60,85 "Hours": 3600,86 "Days": 86400,87 "Weeks": 604800,88 "Years": 31536000, # 365 days89 "Months": 2628000, # 30.44 days90 "Decades": 31536000091 }92 result = value * time_factors[from_unit] / time_factors[to_unit]93 94 # Area conversions (base unit: square meters)95 elif category == "Area":96 area_factors = {97 "Square Meters": 1,98 "Square Kilometers": 1000000,99 "Square Centimeters": 0.0001,100 "Square Miles": 2589990,101 "Square Yards": 0.836127,102 "Square Feet": 0.092903,103 "Square Inches": 0.00064516,104 "Acres": 4046.86,105 "Hectares": 10000106 }107 result = value * area_factors[from_unit] / area_factors[to_unit]108 109 # Digital Storage conversions (base unit: bytes)110 elif category == "Digital Storage":111 digital_factors = {112 "Bits": 0.125,113 "Bytes": 1,114 "Kilobytes": 1024,115 "Megabytes": 1048576,116 "Gigabytes": 1073741824,117 "Terabytes": 1099511627776118 }119 result = value * digital_factors[from_unit] / digital_factors[to_unit]120 121 else:122 return "Conversion category not supported"123 124 # Format the result with the specified precision125 return f"{result:.{precision}f}"126 127# Function to swap units128def swap_units(from_unit, to_unit):129 return to_unit, from_unit130 131# Function to set example132def set_example(example_num):133 examples = [134 {"category": "Length", "from_unit": "Miles", "to_unit": "Kilometers", "value": "10", "precision": 2},135 {"category": "Temperature", "from_unit": "Celsius", "to_unit": "Fahrenheit", "value": "25", "precision": 1},136 {"category": "Mass", "from_unit": "Pounds", "to_unit": "Kilograms", "value": "150", "precision": 2},137 {"category": "Volume", "from_unit": "Gallons", "to_unit": "Liters", "value": "5", "precision": 2},138 {"category": "Time", "from_unit": "Hours", "to_unit": "Minutes", "value": "2.5", "precision": 1},139 {"category": "Area", "from_unit": "Acres", "to_unit": "Square Meters", "value": "2", "precision": 2},140 {"category": "Digital Storage", "from_unit": "Megabytes", "to_unit": "Gigabytes", "value": "5120", "precision": 3}141 ]142 return examples[example_num]["category"], examples[example_num]["from_unit"], examples[example_num]["to_unit"], examples[example_num]["value"], examples[example_num]["precision"]143 144# Update unit options when category changes145def update_units(category):146 if category == "Length":147 return gr.Dropdown(choices=["Meters", "Kilometers", "Centimeters", "Millimeters", "Miles", "Yards", "Feet", "Inches", "Nautical Miles"], value="Meters"), gr.Dropdown(choices=["Meters", "Kilometers", "Centimeters", "Millimeters", "Miles", "Yards", "Feet", "Inches", "Nautical Miles"], value="Kilometers")148 elif category == "Mass":149 return gr.Dropdown(choices=["Kilograms", "Grams", "Milligrams", "Pounds", "Ounces", "Tons", "Metric Tons", "Stones"], value="Pounds"), gr.Dropdown(choices=["Kilograms", "Grams", "Milligrams", "Pounds", "Ounces", "Tons", "Metric Tons", "Stones"], value="Kilograms")150 elif category == "Temperature":151 return gr.Dropdown(choices=["Celsius", "Fahrenheit", "Kelvin"], value="Celsius"), gr.Dropdown(choices=["Celsius", "Fahrenheit", "Kelvin"], value="Fahrenheit")152 elif category == "Volume":153 return gr.Dropdown(choices=["Liters", "Milliliters", "Gallons", "Quarts", "Pints", "Cups", "Fluid Ounces", "Cubic Meters", "Cubic Feet", "Cubic Inches"], value="Gallons"), gr.Dropdown(choices=["Liters", "Milliliters", "Gallons", "Quarts", "Pints", "Cups", "Fluid Ounces", "Cubic Meters", "Cubic Feet", "Cubic Inches"], value="Liters")154 elif category == "Time":155 return gr.Dropdown(choices=["Seconds", "Milliseconds", "Minutes", "Hours", "Days", "Weeks", "Months", "Years", "Decades"], value="Hours"), gr.Dropdown(choices=["Seconds", "Milliseconds", "Minutes", "Hours", "Days", "Weeks", "Months", "Years", "Decades"], value="Minutes")156 elif category == "Area":157 return gr.Dropdown(choices=["Square Meters", "Square Kilometers", "Square Centimeters", "Square Miles", "Square Yards", "Square Feet", "Square Inches", "Acres", "Hectares"], value="Acres"), gr.Dropdown(choices=["Square Meters", "Square Kilometers", "Square Centimeters", "Square Miles", "Square Yards", "Square Feet", "Square Inches", "Acres", "Hectares"], value="Square Meters")158 elif category == "Digital Storage":159 return gr.Dropdown(choices=["Bits", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"], value="Megabytes"), gr.Dropdown(choices=["Bits", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"], value="Gigabytes")160 else:161 return gr.Dropdown(choices=[]), gr.Dropdown(choices=[])162 163# Create the Gradio interface164with gr.Blocks(title="Unit Converter", theme=gr.themes.Soft()) as demo:165 gr.Markdown("# 🔄 Unit Converter")166 gr.Markdown("Convert between different units of measurement")167 168 with gr.Row():169 with gr.Column(scale=1):170 category = gr.Dropdown(171 choices=["Length", "Mass", "Temperature", "Volume", "Time", "Area", "Digital Storage"],172 value="Length",173 label="Category"174 )175 176 with gr.Row():177 from_unit = gr.Dropdown(label="From Unit")178 to_unit = gr.Dropdown(label="To Unit")179 180 swap_btn = gr.Button("↔ Swap Units", size="sm")181 182 value = gr.Number(value=1, label="Value")183 precision = gr.Slider(0, 8, value=2, step=1, label="Decimal Precision")184 185 with gr.Row():186 convert_btn = gr.Button("Convert", variant="primary")187 clear_btn = gr.Button("Clear")188 189 with gr.Column(scale=1):190 output = gr.Textbox(label="Result", interactive=False)191 192 gr.Markdown("### Examples")193 with gr.Row():194 ex1 = gr.Button("10 Miles to KM")195 ex2 = gr.Button("25°C to °F")196 ex3 = gr.Button("150 lbs to kg")197 with gr.Row():198 ex4 = gr.Button("5 Gal to L")199 ex5 = gr.Button("2.5 hrs to min")200 with gr.Row():201 ex6 = gr.Button("2 Acres to m²")202 ex7 = gr.Button("5120 MB to GB")203 204 # Set up event handlers205 category.change(update_units, inputs=category, outputs=[from_unit, to_unit])206 swap_btn.click(swap_units, inputs=[from_unit, to_unit], outputs=[from_unit, to_unit])207 convert_btn.click(convert_units, inputs=[category, from_unit, to_unit, value, precision], outputs=output)208 clear_btn.click(lambda: ["Length", "Meters", "Kilometers", 1, 2, ""], outputs=[category, from_unit, to_unit, value, precision, output])209 210 # Example handlers211 ex1.click(lambda: set_example(0), outputs=[category, from_unit, to_unit, value, precision])212 ex2.click(lambda: set_example(1), outputs=[category, from_unit, to_unit, value, precision])213 ex3.click(lambda: set_example(2), outputs=[category, from_unit, to_unit, value, precision])214 ex4.click(lambda: set_example(3), outputs=[category, from_unit, to_unit, value, precision])215 ex5.click(lambda: set_example(4), outputs=[category, from_unit, to_unit, value, precision])216 ex6.click(lambda: set_example(5), outputs=[category, from_unit, to_unit, value, precision])217 ex7.click(lambda: set_example(6), outputs=[category, from_unit, to_unit, value, precision])218 219 # Initialize the units220 demo.load(update_units, inputs=category, outputs=[from_unit, to_unit])221 222# Launch the app223if __name__ == "__main__":224 demo.launch()