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