Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • raptornythorink/eatfast-website
1 result
Select Git revision
Show changes
Commits on Source (4)
Showing
with 186 additions and 16 deletions
......@@ -2,4 +2,5 @@
node_modules/
build/
env/
.env
__pycache__
\ No newline at end of file
MYSQL_DATABASE=eatfast
MYSQL_USER=user
MYSQL_PASSWORD=password
MYSQL_ROOT_PASSWORD=rootpassword
DB_HOST=localhost
DB_PORT=3306
WEB_ROOT=http://localhost:8000
\ No newline at end of file
FROM python:3.9 AS build
## virtualenv
RUN python3 -m venv /venv
ENV PATH="/venv/bin:$PATH"
## add and install requirements
RUN pip install --upgrade pip && pip install pip-tools
COPY ./requirements.txt ./
RUN pip install -r requirements.txt
FROM python:3.9 AS runtime
EXPOSE 80
ENV PATH="/venv/bin:$PATH"
COPY --from=build /venv /venv
WORKDIR /backend
COPY . .
ENTRYPOINT ["python3", "main.py"]
\ No newline at end of file
import cv2
import numpy as np
import keras
from fastapi import FastAPI
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 utils.preprocessing import fix_singular_shape, norm_by_imagenet
from db import crud, schemas, database
app = FastAPI()
# load environment variables
load_dotenv()
app = FastAPI(docs_url="/api/docs", openapi_url="/api/openapi.json")
origins = [
"http://localhost:3000",
"localhost:3000"
os.getenv('WEB_ROOT'),
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
......@@ -24,6 +25,33 @@ app.add_middleware(
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
......@@ -49,3 +77,4 @@ async def estimate_(id: str) -> float:
pred_map = np.squeeze(model.predict(input_image))
count_prediction = np.sum(pred_map)
return count_prediction
"""
\ No newline at end of file
File moved
"""
Module to interact with the database
"""
from sqlalchemy.orm import Session
from db import models, schemas
def get_records(place: str, db: Session):
""" Get all the records for the given place """
records = db.query(models.Records).filter(models.Records.place == place).order_by(models.Records.date.desc()).all()
return records
def create_record(new_record: schemas.RecordBase, db: Session):
""" Add a new record to the database """
db_record = models.Records(**new_record.dict())
db.add(db_record)
db.commit()
db.refresh(db_record)
return db_record
\ No newline at end of file
"""
Database connection
"""
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
# load environment variables
load_dotenv()
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}@{os.getenv('DB_HOST')}:{os.getenv('DB_PORT')}/{os.getenv('MYSQL_DATABASE')}?charset=utf8"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
"""
Models of the database for magasin app
"""
from sqlalchemy import Column, Integer, DateTime, Float, Interval, String
from db.database import Base
class Records(Base):
"""Records sql table model"""
__tablename__ = "records"
id = Column(Integer, primary_key=True, index=True)
place = Column(String(10))
date = Column(DateTime)
density = Column(Float)
waiting_time = Column(Interval)
\ No newline at end of file
"""
Pydantic schemas for the magasin app
"""
from typing import Optional
from datetime import datetime, timedelta
from pydantic import BaseModel, Field
class RecordBase(BaseModel):
"""Records base schema"""
place: str = Field(..., title="Name of the RU corresponding the given record")
date: datetime = Field(..., title="Date of the record")
density: float = Field(..., title="Estimated density of people")
waiting_time: Optional[timedelta] = Field(title="Estimated waiting time for people coming at this date")
class Record(RecordBase):
"""Database records schema"""
id: int
class Config:
orm_mode = True
\ No newline at end of file
version: "3.3"
services:
db:
image: mysql
container_name: "db"
restart: always
env_file: .env
command: ["mysqld", "--authentication-policy=mysql_native_password"]
ports:
- "3306:3306"
# app:
# container_name: "app"
# build: .
# depends_on:
# - db
# restart: always
# ports:
# - 3000:3000
# env_file: .env
# environment:
# DB_HOST: db
# links:
# - db
\ No newline at end of file
import uvicorn
from db import models, database
# Database creation
models.Base.metadata.create_all(bind=database.engine)
if __name__ == "__main__":
uvicorn.run("app.api:app", host="0.0.0.0", port=8000, reload=True)
uvicorn.run("app:app", host="0.0.0.0", port=3000, reload=True)
......@@ -12,3 +12,6 @@ sniffio==1.2.0
starlette==0.19.1
typing-extensions==4.2.0
uvicorn==0.17.6
SQLAlchemy==1.4.19
python-dotenv==0.18.0
PyMySQL==1.0.2
\ No newline at end of file