Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
BielStela committed Feb 19, 2025
1 parent 1640265 commit 30066f6
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 26 deletions.
7 changes: 6 additions & 1 deletion api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.uv]
dev-dependencies = ["app", "mypy>=1.15.0", "pytest>=8.3.4", "ruff>=0.9.6"]
dev-dependencies = [
"app",
"mypy>=1.15.0",
"pytest>=8.3.4",
"ruff>=0.9.6",
]

[tool.uv.sources]
app = { workspace = true }
Expand Down
3 changes: 2 additions & 1 deletion api/src/app/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Settings(BaseSettings):
"""Global configuration for the application."""

model_config = SettingsConfigDict(env_file=".env")

auth_token: str
tiff_path: str
grid_tiles_path: str
Expand All @@ -21,4 +22,4 @@ class Settings(BaseSettings):
@lru_cache
def get_settings() -> Settings:
"""Return the global configuration."""
return Settings()
return Settings() # type: ignore
6 changes: 4 additions & 2 deletions api/src/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ def path_params(raster_filename: Annotated[str, Query(description="Raster filena

# Use ORJSONResponse to handle serialization of NaN values. Normal Json fails to serialize NaN values.
app = FastAPI(title="Amazonia360 API", default_response_class=ORJSONResponse)

app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

tiler_routes = ZonalTilerFactory(path_dependency=path_params)

app.include_router(tiler_routes.router, tags=["Raster"], dependencies=[Depends(verify_token)])
app.include_router(grid_router, prefix="/grid", tags=["Grid"], dependencies=[Depends(verify_token)])
app.include_router(ai_router, prefix="/ai", tags=["LLMs"], dependencies=[Depends(verify_token)])

app.include_router(ai_router, prefix="/ai", tags=["Text Generation"], dependencies=[Depends(verify_token)])
add_exception_handlers(app, DEFAULT_STATUS_CODES)

_ = get_settings() # load settings at startup to check for issues


@app.get("/tifs", tags=["Raster"], dependencies=[Depends(verify_token)])
async def list_files():
Expand Down
Empty file.
28 changes: 10 additions & 18 deletions api/src/app/openai_service.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import json

from openai import OpenAI
from openai import OpenAI, OpenAIError

from app.config.config import get_settings


def generate_description(context_data: dict, description_type: str, language: str) -> dict[str, str] | str:
def generate_description(context_data: dict, description_type: str, language: str) -> str:
"""
Generate a description using OpenAI's Chat Completions API based on context data, a
description type, and the desired language.
Expand Down Expand Up @@ -50,24 +50,16 @@ def generate_description(context_data: dict, description_type: str, language: st
# Initialize the OpenAI client
client = OpenAI(api_key=get_settings().openai_token.get_secret_value())

try:
# Make the API call
completion = client.chat.completions.create(
model="gpt-4o",
messages=[system_message, user_message],
max_tokens=1024,
temperature=0.7,
)
except Exception as e:
# Handle API errors
return {"error": f"API request failed: {str(e)}"}
# Make the API call
completion = client.chat.completions.create(
model="gpt-4o",
messages=[system_message, user_message], # type: ignore
max_tokens=1024,
temperature=0.7,
)

# Extract and validate the response content
if not completion or not completion.choices[0] or not completion.choices[0].message.content:
return {"error": "API response was empty or invalid."}

raise OpenAIError("OpenAI API response was empty or invalid")
description = completion.choices[0].message.content.strip()
if not description:
return {"error": "Description generation failed."}

return description
8 changes: 6 additions & 2 deletions api/src/app/routers/text_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ class Context(BaseModel):
description_type: Literal["Short", "Normal", "Long"] = "Normal"


class DescritionResponse(BaseModel):
description: str


@router.post("/")
def generate_description_text(
context: Context,
):
) -> DescritionResponse:
"""Generate a description based on context data and audience profile."""
description = generate_description(context.data, context.description_type, context.language)
return {"description": description}
return DescritionResponse(description=description)
5 changes: 3 additions & 2 deletions api/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import os
from collections.abc import Generator
from pathlib import Path

import numpy as np
Expand Down Expand Up @@ -81,7 +82,7 @@ def geojson() -> str:


@pytest.fixture()
def grid_dataset(setup_data_folder) -> str:
def grid_dataset(setup_data_folder) -> Generator[str]:
"""Create an empty binary file to be used as grid dataset stub
for a level 0 tile. like:
data
Expand Down Expand Up @@ -146,7 +147,7 @@ def tif_file(setup_data_folder):
The bbox is BoundingBox(left=0.0, bottom=7.0, right=3.0, top=10.0)
"""
data = np.array([[0, 1, 0], [1, 9, 1], [0, 1, 0]])
transform = rasterio.transform.from_origin(0, 10, 1, 1)
transform = rasterio.transform.from_origin(0, 10, 1, 1) # pyright: ignore
with rasterio.open(
f"{get_settings().tiff_path}/raster.tif",
"w",
Expand Down

0 comments on commit 30066f6

Please sign in to comment.