Skip to content
Snippets Groups Projects
restAPIServer.py 2.27 KiB
Newer Older
Benedikt's avatar
Benedikt committed
import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dsiUnits import dsiUnit
import re
import XMLUnitExtractor  # Import the newly created module
Benedikt's avatar
Benedikt committed
app = FastAPI()

class UnitRequest(BaseModel):
    unit_string: str

class UnitComparisonRequest(BaseModel):
    unit_string1: str
    unit_string2: str
    complete: bool = False

class XMLRequest(BaseModel):
    xml: str


Benedikt's avatar
Benedikt committed
@app.post("/convert/utf8/")
async def convert_to_utf8(request: UnitRequest):
    try:
        unit=dsiUnit(request.unit_string)
        if unit.valid:
            return {unit.toUTF8()}
        else:
            raise HTTPException(status_code=500, detail=str(unit.warnings))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/convert/latex/")
async def convert_to_latex(request: UnitRequest):
    try:
        unit = dsiUnit(request.unit_string)
        # Assuming you have a function to convert unit strings to LaTeX
        if unit.valid:
            return {unit.toLatex()}
        else:
            raise HTTPException(status_code=500, detail=str(unit.warnings))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/compare/units/")
async def compare_units(request: UnitComparisonRequest):
    try:
        unit1 = dsiUnit(request.unit_string1)
        unit2 = dsiUnit(request.unit_string2)
        complete = request.complete
        if unit1.valid and unit2.valid:
            scale_factor, base_unit = unit1.isScalablyEqualTo(unit2, complete=complete)
            if not np.isnan(scale_factor):
                return {"scale_factor": scale_factor, "base_unit": str(base_unit)}
            else:
                return {"error": "Units are not scalably equal try complete conversion instead. "}
        else:
            warnings = unit1.warnings if not unit1.valid else unit2.warnings
            raise HTTPException(status_code=400, detail=str(warnings))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/validateUnitsInXML/")
async def parse_xml(request: XMLRequest):
    try:
        result = XMLUnitExtractor.parse_and_process(request.xml)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))