Skip to content
Snippets Groups Projects
Commit 11e92319 authored by Aymeric Chaumont's avatar Aymeric Chaumont
Browse files

Merge branch 'docker_config' into 'main'

add volume in docker-compose and update README.md

See merge request !4
parents bf0880bf 9266c27b
Branches
No related tags found
1 merge request!4add volume in docker-compose and update README.md
1. Run the server-side FastAPI app in one terminal window: **README**
==========
# Run the server-side FastAPI app
## In development mode
You can start a virtual environment with the following instructions.
```sh ```sh
$ cd backend $ cd backend
$ python3.9 -m venv env $ python3.9 -m venv env
$ source env/bin/activate $ source env/bin/activate
(env)$ pip install -r requirements.txt
(env)$ python main.py
``` ```
Navigate to [http://localhost:8000](http://localhost:8000) Then you need to install the dependencies by executing `pip install -r requirements.txt`
Comment the app service in the docker-compose.yml then build and run the file.
Start the development server running `python -m uvicorn main:app --reload --port=3001 --host 0.0.0.0`
1. Run the client-side React app in a different terminal window: Navigate to [http://localhost:3001](http://localhost:3001)
<br/>
## In production mode
Build the docker image : `docker-compose build`
Run the server, `docker-compose up -d`
<br/>
# Run the client-side React app in a different terminal window:
```sh ```sh
$ cd frontend $ cd frontend
......
.dockerignore
.env.template
.gitignore
docker-compose.yml
Dockerfile
README.md
__pycache__
env
\ No newline at end of file
...@@ -20,4 +20,4 @@ COPY --from=build /venv /venv ...@@ -20,4 +20,4 @@ COPY --from=build /venv /venv
WORKDIR /backend WORKDIR /backend
COPY . . COPY . .
ENTRYPOINT ["python3", "main.py"] CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
\ No newline at end of file \ No newline at end of file
from typing import List
from fastapi import Body, Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from dotenv import load_dotenv
import os
from db import crud, schemas, database
# load environment variables
load_dotenv()
app = FastAPI(docs_url="/api/docs", openapi_url="/api/openapi.json")
origins = [
os.getenv('WEB_ROOT'),
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
def get_db():
"""Create a database session."""
db = database.SessionLocal()
try:
yield db
finally:
db.close()
@app.get('/api/{place}', response_model=List[schemas.Record])
async def eatfast(place: str, db: Session = Depends(get_db)):
return crud.get_records(place, db)
@app.post('/api/create', response_model=schemas.Record)
async def post(record: schemas.RecordBase = Body(...), db: Session = Depends(get_db)):
return crud.create_record(record, db)
"""
import cv2
import numpy as np
import keras
from utils.preprocessing import fix_singular_shape, norm_by_imagenet
model = keras.models.load_model('model')
# contours of the zone of a picture that should be analyzed by the model
contours = {
'eiffel': [[70, 370], [420, 720], [1280, 720], [1280, 250], [930, 215], [450, 550], [130, 350]]
}
masks = {}
for key, polygon in contours.items():
mask = np.zeros((1280, 720, 3), dtype=np.unit8)
cv2.fillPoly(mask, [polygon], (255, 255, 255))
masks[key] = mask
@app.get("/estimate/{id}")
async def estimate_(id: str) -> float:
# img = fetch(...)
img = np.zeros((1280, 720, 3))
resized_img = cv2.cvtColor(cv2.resize(img, (1280, 720)), cv2.COLOR_BGR2RGB).astype(np.float32)
masked_img = cv2.bitwise_and(resized_img, mask[id])
treated_img = fix_singular_shape(masked_img, 16)
input_image = np.expand_dims(np.squeeze(norm_by_imagenet([treated_img])), axis=0)
pred_map = np.squeeze(model.predict(input_image))
count_prediction = np.sum(pred_map)
return count_prediction
"""
\ No newline at end of file
...@@ -9,17 +9,22 @@ services: ...@@ -9,17 +9,22 @@ services:
command: ["mysqld", "--authentication-policy=mysql_native_password"] command: ["mysqld", "--authentication-policy=mysql_native_password"]
ports: ports:
- "3306:3306" - "3306:3306"
volumes:
- mysql-db:/var/lib/mysql
# app: app:
# container_name: "app" container_name: "app"
# build: . build: .
# depends_on: depends_on:
# - db - db
# restart: always restart: always
# ports: ports:
# - 3000:3000 - 8000:80
# env_file: .env env_file: .env
# environment: environment:
# DB_HOST: db DB_HOST: db
# links: links:
# - db - db
\ No newline at end of file
volumes:
mysql-db:
\ No newline at end of file
import uvicorn from typing import List
from db import models, database from fastapi import Body, Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from dotenv import load_dotenv
import os
from db import crud, schemas, database, models
# load environment variables
load_dotenv()
app = FastAPI(docs_url="/api/docs", openapi_url="/api/openapi.json")
origins = [
os.getenv('WEB_ROOT'),
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
def get_db():
"""Create a database session."""
db = database.SessionLocal()
try:
yield db
finally:
db.close()
@app.on_event("startup")
def on_startup():
# Database creation # Database creation
models.Base.metadata.create_all(bind=database.engine) models.Base.metadata.create_all(bind=database.engine)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=3000, reload=True) @app.get('/api/{place}', response_model=List[schemas.Record])
async def eatfast(place: str, db: Session = Depends(get_db)):
return crud.get_records(place, db)
@app.post('/api/create', response_model=schemas.Record)
async def post(record: schemas.RecordBase = Body(...), db: Session = Depends(get_db)):
return crud.create_record(record, db)
"""
import cv2
import numpy as np
import keras
from utils.preprocessing import fix_singular_shape, norm_by_imagenet
model = keras.models.load_model('model')
# contours of the zone of a picture that should be analyzed by the model
contours = {
'eiffel': [[70, 370], [420, 720], [1280, 720], [1280, 250], [930, 215], [450, 550], [130, 350]]
}
masks = {}
for key, polygon in contours.items():
mask = np.zeros((1280, 720, 3), dtype=np.unit8)
cv2.fillPoly(mask, [polygon], (255, 255, 255))
masks[key] = mask
@app.get("/estimate/{id}")
async def estimate_(id: str) -> float:
# img = fetch(...)
img = np.zeros((1280, 720, 3))
resized_img = cv2.cvtColor(cv2.resize(img, (1280, 720)), cv2.COLOR_BGR2RGB).astype(np.float32)
masked_img = cv2.bitwise_and(resized_img, mask[id])
treated_img = fix_singular_shape(masked_img, 16)
input_image = np.expand_dims(np.squeeze(norm_by_imagenet([treated_img])), axis=0)
pred_map = np.squeeze(model.predict(input_image))
count_prediction = np.sum(pred_map)
return count_prediction
"""
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment