Skip to content

Commit

Permalink
feat: resturing backend
Browse files Browse the repository at this point in the history
  • Loading branch information
arunavabasucom committed Aug 12, 2023
1 parent 4b26e67 commit 2b8f7a1
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 194 deletions.
196 changes: 2 additions & 194 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import os
import radis
import numpy as np
import astropy.units as u
from astropy.units import cds
from typing import List, Optional
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from pydantic.typing import Literal
from fastapi.responses import FileResponse




# for high resolution
Expand All @@ -22,190 +17,3 @@
allow_methods=["*"],
allow_headers=["*"],
)
# structure of the request


# class Species(BaseModel):
# molecule: str
# mole_fraction: float


# class Payload(BaseModel):
# min_wavenumber_range: float
# max_wavenumber_range: float
# species: List[Species]
# pressure: float
# tgas: float
# tvib: Optional[float] = None
# trot: Optional[float] = None
# path_length: float
# simulate_slit: Optional[int] = None
# use_simulate_slit: bool
# mode: Literal[
# "absorbance",
# "transmittance_noslit",
# "radiance_noslit",
# "transmittance",
# "radiance",
# ]
# database: Literal["hitran", "geisa", "hitemp"]
# wavelength_units: Literal["1/u.cm", "u.nm"]
# pressure_units: Literal["u.bar", "u.mbar", "cds.atm", "u.torr", "u.mTorr", "u.Pa"]
# path_length_units: Literal["u.cm", "u.m", "u.km"]


# calculating the spectrum return back the spectrum
# def calculate_spectrum(payload):
# print(">> Payload : ")
# print(payload)
# spectrum = radis.calc_spectrum(
# payload.min_wavenumber_range * eval(payload.wavelength_units),
# payload.max_wavenumber_range * eval(payload.wavelength_units),
# molecule=[species.molecule for species in payload.species],
# mole_fraction={
# species.molecule: species.mole_fraction for species in payload.species
# },
# # TODO: Hard-coding "1,2,3" as the isotopologue for the time-being
# isotope={species.molecule: "1,2,3" for species in payload.species},
# pressure=payload.pressure * eval(payload.pressure_units),
# Tgas=payload.tgas,
# Tvib=payload.tvib,
# Trot=payload.trot,
# path_length=payload.path_length * eval(payload. path_length_units),
# export_lines=False,
# wstep="auto",
# databank=payload.database,
# use_cached=True,
# )
# return spectrum


# # create the folder in server for better organization
# DOWNLOADED_SPECFILES_DIRECTORY = "DOWNLOADED_SPECFILES"
# DOWNLOADED_TXT_DIRECTORY = "DOWNLOADED_TXT"


# def create_download_directory(FILE_NAME):

# if os.path.exists(FILE_NAME):
# print(" >> Folder already exists ")
# else:
# print(">> creating DOWNLOADED_SPECFILES folder")
# os.mkdir(FILE_NAME)


# # delete the file after giving the file response back to the user
# def delete_spec(file_path: str):

# if os.path.exists(file_path):
# print(" >> Removing file......")
# os.remove(file_path)
# print(" >> File removed")
# else:
# print(" >> File is not found ")


# "/calculate-spectrum " --> to calculate the spectrum and return back the x and y coordinates
# @app.post("/calculate-spectrum")
# async def calc_spectrum(payload: Payload):
# print(payload)

# try:
# spectrum = calculate_spectrum(payload)
# if payload.use_simulate_slit is True:
# if(payload.wavelength_units=="1/u.cm"):
# slit_unit="cm-1"
# else:
# slit_unit="nm"
# print("Applying simulate slit")
# spectrum.apply_slit(payload.simulate_slit, slit_unit)

# except radis.misc.warning.EmptyDatabaseError:
# return {"error": "No line in the specified wavenumber range"}
# except Exception as exc:
# print("Error", exc)
# return {"error": str(exc)}
# else:

# wunit = spectrum.get_waveunit()
# iunit = "default"
# xNan, yNan = spectrum.get(payload.mode, wunit=wunit, Iunit=iunit)
# # to remove the nan values from x and y
# x = xNan[~np.isnan(xNan)]
# y = yNan[~np.isnan(yNan)]
# # Reduce payload size
# threshold = 5e7
# if len(spectrum) * 8 * 2 > threshold:
# print("Reducing the payload size")
# # Setting return payload size limit of 50 MB
# # one float is about 8 bytes
# # we return 2 arrays (w, I)
# # (note: we could avoid returning the full w-range, and recompute it on the client
# # from the x min, max and step --> less data transfer. TODO )
# resample = int(len(spectrum) * 8 * 2 // threshold)
# x, y = x[::resample], y[::resample]

# return {
# "data": {
# "x": list(x),
# "y": list(y),
# "units": spectrum.units[payload.mode],
# },
# }


# "/download-spectrum"--> to return back the .spec file and delete that file after giving the fileresponse back
# @app.post("/download-spectrum")
# async def download_spec(payload: Payload, background_tasks: BackgroundTasks):

# try:
# create_download_directory(DOWNLOADED_SPECFILES_DIRECTORY)
# spectrum = calculate_spectrum(payload)
# file_name_spec = spectrum.get_name()
# file_name = f"{file_name_spec}.spec"
# file_path = f"{DOWNLOADED_SPECFILES_DIRECTORY}/{file_name}"
# if payload.use_simulate_slit is True:
# print(" >> Applying simulate slit")
# spectrum.apply_slit(payload.simulate_slit, "nm")
# # returning the error response
# except radis.misc.warning.EmptyDatabaseError:
# return {"error": "No line in the specified wavenumber range"}
# except Exception as exc:
# print("Error", exc)
# return {"error": str(exc)}
# else:
# spectrum.store(file_path, compress=True, if_exists_then="replace")
# # running as a background task to delete the .spec file after giving the file response back
# background_tasks.add_task(delete_spec, file_path)
# return FileResponse(
# file_path, media_type="application/octet-stream", filename=file_name
# )

#to return back the csv response to the frontend
@app.post("/download-txt")
async def download_txt(payload: Payload, background_tasks: BackgroundTasks):
try:
create_download_directory(DOWNLOADED_TXT_DIRECTORY)
spectrum = calculate_spectrum(payload)
file_name_txt = spectrum.get_name()
file_name = f"{file_name_txt}.csv"
file_path = f"{DOWNLOADED_TXT_DIRECTORY}/{file_name}"
if payload.use_simulate_slit is True:
print(" >> Applying simulate slit")
spectrum.apply_slit(payload.simulate_slit, "nm")
# returning the error response
except radis.misc.warning.EmptyDatabaseError:
return {"error": "No line in the specified wavenumber range"}
except Exception as exc:
print("Error", exc)
return {"error": str(exc)}
else:

wunit = spectrum.get_waveunit()
iunit = "default"
spectrum.savetxt(file_path,payload.mode,wunit=wunit,Iunit=iunit)
# running as a background task to delete the .spec file after giving the file response back
background_tasks.add_task(delete_spec, file_path)
return FileResponse(
file_path, media_type="application/octet-stream", filename=file_name
)
7 changes: 7 additions & 0 deletions backend/src/models/payload.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import astropy.units as u
from astropy.units import cds
from pydantic import BaseModel
from typing import List, Optional
from models.species import Species
from pydantic.typing import Literal

class Payload(BaseModel):
min_wavenumber_range: float
max_wavenumber_range: float
Expand Down
2 changes: 2 additions & 0 deletions backend/src/models/species.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pydantic import BaseModel

class Species(BaseModel):
molecule: str
mole_fraction: float
4 changes: 4 additions & 0 deletions backend/src/routes/calculateSpectrum.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import radis
import numpy as np
from fastapi import APIRouter
from models.payload import Payload
from helpers.calculateSpectrum import calculate_spectrum

router = APIRouter()
@router.post("/calculate-spectrum")
Expand Down
8 changes: 8 additions & 0 deletions backend/src/routes/downloadSpectrum.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import radis
from fastapi import APIRouter
from models.payload import Payload
from fastapi import BackgroundTasks
from fastapi.responses import FileResponse
from helpers.deleteDownloadDirectory import delete_spec
from helpers.calculateSpectrum import calculate_spectrum
from constants.constants import DOWNLOADED_SPECFILES_DIRECTORY
from helpers.createDownloadDirectory import create_download_directory
router = APIRouter()
@router.post("/download-spectrum")
async def download_spec(payload: Payload, background_tasks: BackgroundTasks):
Expand Down
8 changes: 8 additions & 0 deletions backend/src/routes/downloadTxt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import radis
from fastapi import APIRouter
from models.payload import Payload
from fastapi import BackgroundTasks
from fastapi.responses import FileResponse
from helpers.deleteDownloadDirectory import delete_spec
from helpers.calculateSpectrum import calculate_spectrum
from constants.constants import DOWNLOADED_TXT_DIRECTORY
from helpers.createDownloadDirectory import create_download_directory

router = APIRouter()

Expand Down

0 comments on commit 2b8f7a1

Please sign in to comment.