Spaces:
Running
Running
File size: 2,274 Bytes
616000a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
from fastapi import FastAPI, HTTPException
app = FastAPI()
# Conversion functions
def convert_length(value: float, from_unit: str, to_unit: str) -> float:
length_units = {"meters": 1, "kilometers": 0.001, "miles": 0.000621371, "feet": 3.28084}
if from_unit not in length_units or to_unit not in length_units:
raise ValueError("Invalid length units")
return value * (length_units[to_unit] / length_units[from_unit])
def convert_weight(value: float, from_unit: str, to_unit: str) -> float:
weight_units = {"grams": 1, "kilograms": 0.001, "pounds": 0.00220462, "ounces": 0.035274}
if from_unit not in weight_units or to_unit not in weight_units:
raise ValueError("Invalid weight units")
return value * (weight_units[to_unit] / weight_units[from_unit])
def convert_temperature(value: float, from_unit: str, to_unit: str) -> float:
if from_unit == "celsius" and to_unit == "fahrenheit":
return value * 9/5 + 32
elif from_unit == "fahrenheit" and to_unit == "celsius":
return (value - 32) * 5/9
elif from_unit == "celsius" and to_unit == "kelvin":
return value + 273.15
elif from_unit == "kelvin" and to_unit == "celsius":
return value - 273.15
elif from_unit == "fahrenheit" and to_unit == "kelvin":
return (value - 32) * 5/9 + 273.15
elif from_unit == "kelvin" and to_unit == "fahrenheit":
return (value - 273.15) * 9/5 + 32
elif from_unit == to_unit:
return value
else:
raise ValueError("Invalid temperature conversion")
# API endpoints
@app.get("/convert/{category}")
async def convert_units(category: str, value: float, from_unit: str, to_unit: str):
try:
if category == "length":
result = convert_length(value, from_unit, to_unit)
elif category == "weight":
result = convert_weight(value, from_unit, to_unit)
elif category == "temperature":
result = convert_temperature(value, from_unit, to_unit)
else:
raise HTTPException(status_code=400, detail="Invalid category")
return {"value": value, "from_unit": from_unit, "to_unit": to_unit, "result": result}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
|