Spaces:
Running
Running
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 | |
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)) | |