Improve : from datetime import datetime from fastapi import FastAPI, Depends,…
Jump to turn (6)
- User
Improve : from datetime import datetime
from fastapi import FastAPI, Depends, HTTPException from pydantic import BaseModel from typing import Optional, List
from sqlalchemy import func from sqlalchemy.orm import Session from database import SessionLocal, engine, Base from models import Mosquito as MosquitoReportModel, Traitement, Maladie
Base.metadata.create_all(bind=engine)
app = FastAPI()
class MosquitoReport(BaseModel): id: int location: str species: str date: datetime contamination_rate: Optional[float] observations: str = None disease: str number_contamination: int
class Config:
orm_mode = True
class ContaminationRate(BaseModel): species: str total_tested: int total_contaminated: int contamination_rate: float
class Config:
orm_mode = True
class TraitementSchema(BaseModel): id: int description: str maladie_id: int
class Config:
orm_mode = True
class MaladieSchema(BaseModel): id: int nom: str traitements: List[TraitementSchema]
class Config:
orm_mode = True
def get_db(): db = SessionLocal() try: yield db finally: db.close()
@app.get("/") def read_root(): return {"message": "Welcome to the Mosquito API"}
@app.post("/mosquito/", response_model=MosquitoReport) def create_mosquito_report(mosquito: MosquitoReport, db: Session = Depends(get_db)): db_mosquito = MosquitoReportModel(**mosquito.dict()) db.add(db_mosquito) db.commit() db.refresh(db_mosquito) return db_mosquito
@app.get("/mosquito/{mosquito_id}", response_model=MosquitoReport) def read_mosquito_report(mosquito_id: int, db: Session = Depends(get_db)): db_mosquito = db.query(MosquitoReportModel).filter(MosquitoReportModel.id == mosquito_id).first() if db_mosquito is None: raise HTTPException(status_code=404, detail="Mosquito not found") return db_mosquito
@app.put("/mosquito/{mosquito_id}", response_model=MosquitoReport) def update_mosquito_report(mosquito_id: int, mosquito: MosquitoReport, db: Session = Depends(get_db)): db_mosquito = db.query(MosquitoReportModel).filter(MosquitoReportModel.id == mosquito_id).first() if db_mosquito is None: raise HTTPException(status_code=404, detail="Mosquito not found") for key, value in mosquito.dict().items(): setattr(db_mosquito, key, value) db.commit() db.refresh(db_mosquito) return db_mosquito
@app.delete("/mosquito/{mosquito_id}", response_model=MosquitoReport) def delete_mosquito_report(mosquito_id: int, db: Session = Depends(get_db)): db_mosquito = db.query(MosquitoReportModel).filter(MosquitoReportModel.id == mosquito_id).first() if db_mosquito is None: raise HTTPException(status_code=404, detail="Mosquito not found") db.delete(db_mosquito) db.commit() return db_mosquito
@app.get("/mosquito/count", response_model=int) def count_number_mosquito_reports(db: Session = Depends(get_db)): return db.query(MosquitoReportModel).count()
@app.get("/mosquito/last", response_model=MosquitoReport) def read_last_mosquito_report(db: Session = Depends(get_db)): return db.query(MosquitoReportModel).order_by(MosquitoReportModel.date.desc()).first()
@app.get("/contamination/", response_model=List[ContaminationRate])
def read_contamination_rates(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
return db.query(MosquitoReportModel.species, func.count(MosquitoReportModel.species).label('total_tested'),
func.sum(MosquitoReportModel.contamination_rate).label('total_contaminated'),
func.avg(MosquitoReportModel.contamination_rate).label('contamination_rate'))
.group_by(MosquitoReportModel.species).offset(skip).limit(limit).all()
@app.get("/contamination/{species}", response_model=ContaminationRate)
def read_contamination_rate(species: str, db: Session = Depends(get_db)):
return db.query(MosquitoReportModel.species, func.count(MosquitoReportModel.species).label('total_tested'),
func.sum(MosquitoReportModel.contamination_rate).label('total_contaminated'),
func.avg(MosquitoReportModel.contamination_rate).label('contamination_rate'))
.filter(MosquitoReportModel.species == species).group_by(MosquitoReportModel.species).first()
@app.get("/mosquito/", response_model=List[MosquitoReport]) def read_mosquito_reports(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): return db.query(MosquitoReportModel).offset(skip).limit(limit).all()
@app.post("/traitement/", response_model=TraitementSchema) def create_traitement(traitement: TraitementSchema, db: Session = Depends(get_db)): db_traitement = Traitement(**traitement.dict()) db.add(db_traitement) db.commit() db.refresh(db_traitement) return db_traitement
@app.get("/traitement/{traitement_id}", response_model=TraitementSchema) def read_traitement(traitement_id: int, db: Session = Depends(get_db)): db_traitement = db.query(Traitement).filter(Traitement.id == traitement_id).first() if db_traitement is None: raise HTTPException(status_code=404, detail="Traitement not found") return db_traitement
@app.get("/traitement/", response_model=List[TraitementSchema]) def read_traitements(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): return db.query(Traitement).offset(skip).limit(limit).all()
@app.post("/maladie/", response_model=MaladieSchema) def create_maladie(maladie: MaladieSchema, db: Session = Depends(get_db)): db_maladie = Maladie(**maladie.dict()) db.add(db_maladie) db.commit() db.refresh(db_maladie) return db_maladie
@app.get("/maladie/{maladie_id}", response_model=MaladieSchema) def read_maladie(maladie_id: int, db: Session = Depends(get_db)): db_maladie = db.query(Maladie).filter(Maladie.id == maladie_id).first() if db_maladie is None: raise HTTPException(status_code=404, detail="Maladie not found") return db_maladie
@app.get("/maladie/", response_model=List[MaladieSchema]) def read_maladies(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): return db.query(Maladie).offset(skip).limit(limit).all()
Your FastAPI application seems well-organized and functional, covering key CRUD operations for mosquito reports, treatments, and diseases. However, there are some areas where improvements can be made to enhance code clarity, efficiency, and maintainability. Below are some recommendations for these improvements:
async and await where possible:FastAPI supports asynchronous programming, which can benefit the performance when dealing with I/O-bound tasks such as database operations.
Consider structuring your project into separate modules for models, schemas, and operations. This not only makes the code cleaner but also easier to manage and test.
Enhance error handling by centralizing the error responses or using exception handlers to keep the endpoint functions clean.
Adding descriptive docstrings to your functions can improve the understandability of the code, helping future maintainers and users of the API.
You've already started using it for database sessions. Continue this approach for any similar pattern that repeats.
For better data validation and error handling, ensure all input schemas utilize Pydantic's capabilities fully, including more complex validations if needed.
Ensure that SQL queries are efficient and consider indexing database columns that are commonly used in queries like id and species.
Your skip and limit functionality could be abstracted into a dependency that you can inject into your route functions, making it more reusable and concise.
Here's a refactor of your application considering some of the enhancements mentioned (focusing on database session handling and adding async):
database.py:from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite+aiosqlite:///./fastapi.db"
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)
Find species easier for each mosquito
If your goal is to make it easier for users of your FastAPI application to find and interact with data based on mosquito species, you can enhance your API with specific endpoints or features that support these interactions. Here are a few suggestions:
You can create a search endpoint that allows users to filter mosquito reports and related data by species, leveraging case-insensitive and partial matching.
from sqlalchemy import or_
@app.get("/mosquito/search/", response_model=List[MosquitoReport])
async def search_mosquito_reports(species: Optional[str] = None, db: Session = Depends(get_db)):
query = db.query(MosquitoReportModel)
if species:
query = query.filter(MosquitoReportModel.species.ilike(f"%{species}%"))
return await query.all()
Implement an endpoint that returns potentially matching species as the user types, enhancing the user interface with auto-complete functionality.
@app.get("/species/suggest/", response_model=List[str])
async def suggest_species(query: str, db: Session = Depends(get_db), limit: int = 5):
species_list = await db.query(MosquitoReportModel.species).filter(
MosquitoReportModel.species.ilike(f"%{query}%")
).distinct().limit(limit).all()
return [species[0] for species in species_list]
Provide an endpoint that gives a summary of data related to each species, such as the number of reports, average contamination rate, etc.
Add other endpoints api
To enhance the functionality of your FastAPI application, you can add a variety of endpoints that cater to different needs and improve user interaction. Here are some additional API endpoints that could be useful based on your existing project setup:
This endpoint would allow users to retrieve detailed reports of mosquitos based on location, which can be useful in epidemiological studies or regional health planning.
@app.get("/mosquito/location/{location}", response_model=List[MosquitoReport])
async def read_mosquito_reports_by_location(location: str, db: Session = Depends(get_db)):
reports = await db.query(MosquitoReportModel).filter(MosquitoReportModel.location.ilike(f"%{location}%")).all()
return reports
An endpoint to get aggregated information about diseases, such as the number of associated treatments, or the regions most affected could provide valuable insights.
@app.get("/disease/summary", response_model=List[DiseaseSummary])
async def disease_summary(db: Session = Depends(get_db)):
summary = await db.query(
Maladie.nom,
func.count(Traitement.id).label('number_of_treatments'),
func.count(distinct(MosquitoReportModel.location)).label('affected_locations')
).join(Traitement).join(MosquitoReportModel).group_by(Maladie.nom).all()
return summary
Creating a simpler endpoint to just update the observations for a mosquito report can be a useful feature, without needing to send a full payload for updates.
Add Ml for predictive analysis endpoints api
Integrating machine learning (ML) predictive analysis into your FastAPI application can provide valuable foresight based on historical data. In this case, you might want to predict future contamination rates or the potential spread of diseases based on mosquito data.
Before setting up an endpoint for predictive analysis, you need to prepare the following:
Here’s a step-by-step guide to adding an ML-powered endpoint to predict contamination rates:
You'll need to extract historical mosquito data from your database, optionally enrich it with external data sources (weather conditions, geographic info, etc.), and then preprocess it for ML training.
For simplicity in this example, assume you have a dataset ready for training.
Choose a model based on your requirements. For regression tasks like predicting rates, you might consider using linear regression, decision trees, or more complex models like Gradient Boosting or Neural Networks.
Here's a simple example with Scikit-Learn:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston # Placeholder: replace with your own data loading mechanism
# Load and split the data
data = load_boston() # Placeholder
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# Train the model
model = LinearRegression()
model.fit(X_train, y_train)
After training, save your model using joblib or pickle, and then load it in your API:
import joblib
# Save the model
joblib.dump(model, 'mosquito_model.pkl')
# Load the model in your API setup
model = joblib.load('mosquito_model.pkl')
Add other models for exemple
To expand the predictive capabilities of your FastAPI application further, you can integrate additional machine learning models tailored to different aspects of your dataset or to improve the predictions you're already planning to make. Below are examples of several machine learning models you can utilize, each serving different purposes within your application.
RandomForest is a versatile machine learning model that can be used for both classification and regression tasks. For predicting whether a particular area is likely to have a disease outbreak based on mosquito data, a classifier model can be very useful.
Training the RandomForest Classifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Suppose you have labeled training data in 'X' as features and 'y' as labels (0: no outbreak, 1: outbreak)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
classifier = RandomForestClassifier(n_estimators=100, random_state=0)
classifier.fit(X_train, y_train)
# Save and load model like discussed previously
joblib.dump(classifier, 'disease_outbreak_classifier.pkl')
API Endpoint for Outbreak Prediction
@app.post("/predict/outbreak/")
async def predict_disease_outbreak(input_data: PredictionInput):
try:
model = joblib.load('disease_outbreak_classifier.pkl')
data = np.array([input_data.features])
prediction = model.predict(data)
return {"outbreak_prediction": int(prediction[0])} # Returns 0 or 1
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
Gradient Boosting is an ensemble learning method that works well for regression problems. It can predict the contamination rate more accurately by combining multiple weak learning models sequentially.
I speak models pydantic for m'y api
If you are referring to enhancing your FastAPI application by defining and utilizing more comprehensive Pydantic models for better structured data interactions, here’s how you can design and integrate these models into your API to enable more robust and clear data handling procedures. Pydantic models help in validation keys and data types, ensuring that data meets the expected format and content.
Enhanced Mosquito Report Model:
Extending the MosquitoReport model to include related data such as regional weather conditions, which could affect mosquito populations and disease spread.
from pydantic import BaseModel, validator
from datetime import datetime
from typing import Optional, List
class WeatherInfo(BaseModel):
temperature: float
humidity: float
rainfall: float # in mm
class MosquitoReport(BaseModel):
id: int
location: str
species: str
date: datetime
contamination_rate: Optional[float] = None
observations: Optional[str] = None
disease: str
number_contamination: int
weather: Optional[WeatherInfo] = None
@validator('date')
def date_must_be_past(cls, v):
if v > datetime.now():
raise ValueError('Date must be in the past')
return v
class Config:
orm_mode = True
Disease Impact Model: A model that describes the impact and statistics of a particular disease related to mosquito vectors.
class DiseaseImpact(BaseModel):
disease_name: str
total_cases: int
total_fatalities: int
regions_affected: List[str]
class Config:
orm_mode = True
Mosquito Population Model: A model that could help in understanding the distribution and population density of mosquitoes in different areas.
Not yet included in a published release.
dependencies.py:from .database import AsyncSessionLocal
async def get_db():
async with AsyncSessionLocal() as session:
yield session
main.py updates for async/await in route functions:@app.post("/mosquito/", response_model=MosquitoReport)
async def create_mosquito_report(mosquito: MosquitoReport, db: Session = Depends(get_db)):
db_mosquito = MosquitoReportModel(**mosquito.dict())
db.add(db_mosquito)
await db.commit()
await db.refresh(db_mosquito)
return db_mosquito
With these changes, your API will make better use of FastAPI's async capabilities, improve code modularity, and enhance maintainability. Consider systematically applying these patterns across your project.
@app.get("/species/summary/", response_model=List[SpeciesSummary])
async def get_species_summary(db: Session = Depends(get_db)):
summary = await db.query(
MosquitoReportModel.species,
func.count().label("total_reports"),
func.avg(MosquitoReportModel.contamination_rate).label("average_contamination")
).group_by(MosquitoReportModel.species).all()
return summary
Improve your API documentation by adding more descriptive titles and descriptions for endpoints, especially those related to species.
@app.get("/species/suggest/", response_model=List[str], summary="Suggest species names",
description="Provides suggested species names based on the partial input for auto-complete functionality.")
async def suggest_species( ... ):
...
Consider developing or integrating a front-end element that utilizes these endpoints, providing users a seamless and interactive experience when searching for and filtering data based on mosquito species.
For each of these changes, make sure your database queries are optimized to handle potentially large datasets and frequent requests, possibly using indexes on the species column and ensuring queries are appropriately cached if necessary.
@app.patch("/mosquito/{mosquito_id}/update-observations", response_model=MosquitoReport)
async def update_mosquito_observations(mosquito_id: int, observations: str, db: Session = Depends(get_db)):
mosquito = await db.query(MosquitoReportModel).filter(MosquitoReportModel.id == mosquito_id).first()
if mosquito is None:
raise HTTPException(status_code=404, detail="Mosquito report not found")
mosquito.observations = observations
db.commit()
await db.refresh(mosquito)
return mosquito
Introducing endpoints that offer predictive analysis based on the data can be a high-value addition. For instance, predicting future contamination rates from historical data.
@app.get("/predict/contamination/{species}", response_model=float)
async def predict_contamination(species: str, db: Session = Depends(get_db)):
# Placeholder for predictive functionality, normally you would integrate a ML model here.
recent_data = await db.query(func.avg(MosquitoReportModel.contamination_rate))\
.filter(MosquitoReportModel.species == species)\
.limit(100).all()
prediction = sum([d[0] for d in recent_data])/len(recent_data)
return prediction
Based on mosquito data and disease incidence, issue health advisories for different locations.
@app.get("/advisory/{location}", response_model=str)
async def health_advisory(location: str, db: Session = Depends(get_db)):
disease_risk = await db.query(func.sum(MosquitoReportModel.number_contamination))\
.filter(MosquitoReportModel.location == location)\
.scalar()
advice = "Low Risk" if disease_risk < 10 else "High Risk"
return f"Current health advisory for {location}: {advice}"
These endpoints offer broader functionality to the users of your API, ranging from more detailed and specialized fetch requests to actionable insights and predictions based on the data. By developing these endpoints, you can greatly increase the applicability and usefulness of your API.
Here’s how you can set up a FastAPI endpoint to use the trained model:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import numpy as np
app = FastAPI()
class PredictionInput(BaseModel):
features: list # This will depend on the features your model was trained on
@app.post("/predict/contamination/")
async def predict_contamination(input_data: PredictionInput):
try:
# Ensure incoming features match the model's expected input shape
data = np.array([input_data.features])
prediction = model.predict(data)
return {"predicted_contamination_rate": prediction[0]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
By following these steps, you integrate a basic ML prediction feature into your FastAPI application, enhancing it to provide predictive insights based on historical data. As you expand, consider more complex models and features to improve accuracy and utility.
Training the Gradient Boosting Regressor
from sklearn.ensemble import GradientBoostingRegressor
# Data preparation remains similar to previous examples
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
regressor = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=0)
regressor.fit(X_train, y_train)
joblib.dump(regressor, 'contamination_rate_regressor.pkl')
API Endpoint for Contamination Rate Prediction
@app.post("/predict/contamination-rate/")
async def predict_contamination_rate(input_data: PredictionInput):
try {
model = joblib.load('contamination_rate_regressor.pkl')
data = np.array([input_data.features])
prediction = model.predict(data)
return {"predicted_contamination_rate": float(prediction[0])}
} except Exception as e {
raise HTTPException(status_code=400, detail=str(e))
}
K-Means can be used to find clusters of mosquito data points, helping to understand which areas might be more prone to having higher mosquito populations.
Training the K-Means Model
from sklearn.cluster import KMeans
# Data might only be locations or combine with other data like vegetation indexes, etc.
kmeans = KMeans(n_clusters=5, random_state=0).fit(X)
joblib.dump(kmeans, 'mosquito_distribution_kmeans.pkl')
API Endpoint for Mosquito Data Analysis
@app.get("/analyze/mosquito_distribution/")
async def analyze_mosquito_distribution():
try {
model = joblib.load('mosquito_distribution_kmeans.pkl')
labels = model.labels_
return {"cluster_labels": labels.tolist()}
} except Exception as e {
raise HTTPException(status_code=400, detail=str(e))
}
Adding multiple models to your FastAPI can provide diverse insights across different aspects of your data, making your application a powerful tool for decision-making.
class MosquitoPopulation(BaseModel):
location: str
species: str
estimated_population: int
last_surveyed: datetime
class Config:
orm_mode = True
Here’s how you can utilize these models in your FastAPI endpoints for creating and retrieving data:
@app.post("/mosquito/", response_model=MosquitoReport)
async def create_mosquito_report(mosquito: MosquitoReport, db: Session = Depends(get_db)):
db_mosquito = MosquitoReportModel(**mosquito.dict())
db.add(db_mosquito)
db.commit()
db.refresh(db_mosquito)
return db_mosquito
@app.get("/disease/impact/{disease_name}", response_model=DiseaseImpact)
async def get_disease_impact(disease_name: str, db: Session = Depends(get_db)):
impact_data = db.query(DiseaseModel).filter(DiseaseModel.name == disease_name).first()
if impact_data is None:
raise HTTPException(status_code=404, detail="Disease not found")
return DiseaseImpact(**impact_data)
@app.get("/mosquito/population/{location}", response_model=List[MosquitoPopulation])
async def get_mosquito_population_by_location(location: str, db: Session = Depends(get_db)):
populations = db.query(MosquitoModel).filter(MosquitoModel.location.ilike(f"%{location}%")).all()
return [MosquitoPopulation(**pop.dict()) for pop in populations]
These enhanced Pydantic models and example usages demonstrate how leveraging detailed, structured, and validated models can deeply enrich the functionality and reliability of your API. This approach ensures that all data interactions are clear, predictable, and helpful in building robust applications with FastAPI.