docker update
Browse files- Dockerfile +13 -0
- README.md +8 -8
- app.py +113 -0
Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
|
| 3 |
+
WORKDIR /code
|
| 4 |
+
|
| 5 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 6 |
+
|
| 7 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
COPY ./app.py /code/
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
CMD ["fastapi", "run", "app.py", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: docker
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
-
|
| 10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Hello World App # Replace with your app's title
|
| 3 |
+
emoji: π # Replace with an emoji that represents your app
|
| 4 |
+
colorFrom: green # Background gradient start color
|
| 5 |
+
colorTo: blue # Background gradient end color
|
| 6 |
+
sdk: docker # Specify 'docker' since you're using a Dockerfile
|
| 7 |
+
sdk_version: "1.0" # Specify the version (leave it as is if unsure)
|
| 8 |
+
app_file: main.py # Replace with the file name where your app starts
|
| 9 |
+
pinned: false # Set to true if you want to pin this Space
|
| 10 |
---
|
|
|
|
|
|
app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel,Field
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
# Configure logging
|
| 7 |
+
logging.basicConfig(
|
| 8 |
+
level=logging.INFO, # Set the logging level to INFO
|
| 9 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 10 |
+
handlers=[
|
| 11 |
+
logging.FileHandler("app.log"), # Log to a file named app.log
|
| 12 |
+
logging.StreamHandler() # Log to the console
|
| 13 |
+
]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Create logger instance
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
app = FastAPI()
|
| 20 |
+
|
| 21 |
+
file_path = "D:/pandas/world_population (1).csv"
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
countries_df = pd.read_csv(file_path)
|
| 25 |
+
# Convert Population and Area to numeric values with error handling
|
| 26 |
+
countries_df["Population"] = pd.to_numeric(countries_df["Population"])
|
| 27 |
+
countries_df["Area"] = pd.to_numeric(countries_df["Area"])
|
| 28 |
+
logger.info("CSV file loaded and processed successfully.")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Failed to load or process CSV file: {e}")
|
| 31 |
+
raise
|
| 32 |
+
|
| 33 |
+
# Pydantic models for API response
|
| 34 |
+
class CountryPopulation(BaseModel):
|
| 35 |
+
country: str
|
| 36 |
+
population: int
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ContinentPopulationResponse(BaseModel):
|
| 40 |
+
continent: str=Field(description="continent of country")
|
| 41 |
+
total_population: int
|
| 42 |
+
total_area: int
|
| 43 |
+
continent_population_density: float
|
| 44 |
+
max_population: CountryPopulation
|
| 45 |
+
min_population: CountryPopulation
|
| 46 |
+
avg_population: int
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@app.get("/")
|
| 50 |
+
def home():
|
| 51 |
+
logger.info("Accessed home endpoint.")
|
| 52 |
+
return {"message": "Welcome to the World Population API"}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@app.get("/continent/{continent_name}", response_model=ContinentPopulationResponse)
|
| 56 |
+
def get_continent_population(continent_name: str):
|
| 57 |
+
try:
|
| 58 |
+
logger.info(f"Received request for continent: {continent_name}")
|
| 59 |
+
|
| 60 |
+
# Filter data for the given continent
|
| 61 |
+
continent_group = countries_df[countries_df["Continent"] == continent_name]
|
| 62 |
+
continent_group = continent_group.dropna(subset=["Population", "Area"])
|
| 63 |
+
|
| 64 |
+
if continent_group.empty:
|
| 65 |
+
logger.warning(f"No data found for continent: {continent_name}")
|
| 66 |
+
raise HTTPException(status_code=404, detail=f"No data found for continent: {continent_name}")
|
| 67 |
+
|
| 68 |
+
# Calculate total population and total area
|
| 69 |
+
total_population = int(continent_group["Population"].sum())
|
| 70 |
+
total_area = int(continent_group["Area"].sum())
|
| 71 |
+
|
| 72 |
+
# Handle case where total_area is zero to avoid division by zero
|
| 73 |
+
if total_area == 0:
|
| 74 |
+
logger.error(f"Total area is zero for continent: {continent_name}. Cannot calculate population density.")
|
| 75 |
+
raise HTTPException(status_code=400, detail="Total area is zero. Cannot calculate population density.")
|
| 76 |
+
|
| 77 |
+
# Calculate population density
|
| 78 |
+
continent_density = total_population / total_area
|
| 79 |
+
|
| 80 |
+
# Find max and min population countries
|
| 81 |
+
max_row = continent_group.loc[continent_group["Population"].idxmax()]
|
| 82 |
+
min_row = continent_group.loc[continent_group["Population"].idxmin()]
|
| 83 |
+
avg_population = int(continent_group["Population"].mean())
|
| 84 |
+
|
| 85 |
+
logger.info(
|
| 86 |
+
f"Processed data for continent: {continent_name} | "
|
| 87 |
+
f"Total Population: {total_population}, Total Area: {total_area}, "
|
| 88 |
+
f"Population Density: {continent_density:.2f}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return ContinentPopulationResponse(
|
| 92 |
+
continent=continent_name,
|
| 93 |
+
total_population=total_population,
|
| 94 |
+
total_area=total_area,
|
| 95 |
+
continent_population_density=continent_density,
|
| 96 |
+
max_population=CountryPopulation(
|
| 97 |
+
country=max_row["Country"],
|
| 98 |
+
population=int(max_row["Population"])
|
| 99 |
+
),
|
| 100 |
+
min_population=CountryPopulation(
|
| 101 |
+
country=min_row["Country"],
|
| 102 |
+
population=int(min_row["Population"])
|
| 103 |
+
),
|
| 104 |
+
avg_population=avg_population
|
| 105 |
+
)
|
| 106 |
+
except HTTPException as http_err:
|
| 107 |
+
# Log and re-raise HTTP-specific exceptions
|
| 108 |
+
logger.error(f"HTTP exception occurred: {http_err.detail}")
|
| 109 |
+
raise http_err
|
| 110 |
+
except Exception as e:
|
| 111 |
+
# Handle unexpected errors
|
| 112 |
+
logger.error(f"Unexpected error occurred while processing continent: {continent_name} | Error: {e}")
|
| 113 |
+
raise HTTPException(status_code=500, detail="An unexpected error occurred while processing your request.")
|