tharu22's picture
message
c102664
import pandas as pd
from fastapi import APIRouter, HTTPException
from models.continent import ContinentStats
from utils.logger import logger
import os
# Router instance
router = APIRouter()
# base_dir = os.path.dirname(os.path.abspath(__file__)) # Get current script directory
# file_path = os.path.join(base_dir, "data/world_population.csv")
# # Load the CSV data
file_path = "world_population.csv"
df = pd.read_csv(file_path)
@router.get("/{continent}", response_model=ContinentStats)
def get_continent_stats(continent: str):
try:
# The logic for calculating stats (same as your current code)
if continent not in df['Continent'].values:
raise HTTPException(status_code=404, detail=f"Continent '{continent}' not found")
max_population = df.groupby('Continent')['Population'].max()
min_population = df.groupby('Continent')['Population'].min()
max_country = df.groupby('Continent')['Country'].max()
min_country = df.groupby('Continent')['Country'].min()
average_population = df.groupby('Continent')['Population'].mean()
total_area = df.groupby('Continent')['Area'].sum()
total_population = df.groupby('Continent')['Population'].sum() # Prepare the response
response = {}
# Max population and country
max_pop = max_population[continent]
max_pop_country = max_country[continent]
response["Max"] = f"{continent}'s maximum population is {max_pop} in {max_pop_country}"
# Min population and country
min_pop = min_population[continent]
min_pop_country = min_country[continent]
response["Min"] = f"{continent}'s minimum population is {min_pop} in {min_pop_country}"
# Average population
avg_pop = average_population[continent]
response["Avgerage"] = f"{continent}'s average population is {avg_pop}"
# Area
area = total_area[continent]
response["Area"] = f"{continent}'s total area is {area}"
# Total population
total_pop = total_population[continent]
response["Sum"] = f"{continent}'s total population is {total_pop}"
# Population density
continent_density = total_population / total_area
response["density"] = f"{continent}'s population density is {continent_density[continent]}"
# Log the request and result
logger.info(f"Fetched stats for {continent}")
return response
except Exception as e:
logger.error(f"Error occurred while fetching stats for {continent}: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")