IBM Abdulsalam commited on
Commit
ba86161
1 Parent(s): b58ddbb
__pycache__/app.cpython-310.pyc DELETED
Binary file (3.21 kB)
 
__pycache__/crud.cpython-310.pyc DELETED
Binary file (1.54 kB)
 
__pycache__/database.cpython-310.pyc DELETED
Binary file (490 Bytes)
 
__pycache__/main.cpython-310.pyc DELETED
Binary file (2.24 kB)
 
__pycache__/models.cpython-310.pyc DELETED
Binary file (1.06 kB)
 
__pycache__/schemas.cpython-310.pyc DELETED
Binary file (1.56 kB)
 
app/.app.py.swp ADDED
Binary file (1.02 kB). View file
 
app/.db.py.swp ADDED
Binary file (1.02 kB). View file
 
app/__init__.py ADDED
File without changes
app/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (127 Bytes). View file
 
app/__pycache__/app.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
app/__pycache__/db.cpython-310.pyc ADDED
Binary file (1.72 kB). View file
 
app/__pycache__/schemas.cpython-310.pyc ADDED
Binary file (617 Bytes). View file
 
app/__pycache__/users.cpython-310.pyc ADDED
Binary file (2.16 kB). View file
 
app/app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import asynccontextmanager
2
+
3
+ from fastapi import Depends, FastAPI
4
+
5
+ from .db import User, create_db_and_tables
6
+ from .schemas import UserCreate, UserRead, UserUpdate
7
+ from .users import auth_backend, current_active_user, fastapi_users
8
+ from .llm import *
9
+
10
+ @asynccontextmanager
11
+ async def lifespan(app: FastAPI):
12
+ # Not needed if you setup a migration system like Alembic
13
+ await create_db_and_tables()
14
+ yield
15
+
16
+
17
+ app = FastAPI(lifespan=lifespan)
18
+
19
+ app.include_router(
20
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
21
+ )
22
+ app.include_router(
23
+ llm_router,
24
+ tags=["llm"]
25
+ )
26
+ app.include_router(
27
+ fastapi_users.get_register_router(UserRead, UserCreate),
28
+ prefix="/auth",
29
+ tags=["auth"],
30
+ )
31
+ app.include_router(
32
+ fastapi_users.get_reset_password_router(),
33
+ prefix="/auth",
34
+ tags=["auth"],
35
+ )
36
+ app.include_router(
37
+ fastapi_users.get_verify_router(UserRead),
38
+ prefix="/auth",
39
+ tags=["auth"],
40
+ )
41
+ app.include_router(
42
+ fastapi_users.get_users_router(UserRead, UserUpdate),
43
+ prefix="/users",
44
+ tags=["users"],
45
+ )
46
+
47
+
48
+ @app.get("/authenticated-route")
49
+ async def authenticated_route(user: User = Depends(current_active_user)):
50
+ return {"message": f"Hello {user.email}!"}
app/db.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import AsyncGenerator
2
+ from app import app
3
+ from fastapi import Depends
4
+ from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
5
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
6
+ from sqlalchemy.orm import DeclarativeBase
7
+
8
+ from sqlalchemy import URL
9
+
10
+ db_url = URL.create(
11
+ "postgresql",
12
+ username="avnadmin",
13
+ password="AVNS_u12fHxoNLBbzD8TGpqN", # plain (unescaped) text
14
+ host="pg-opengenai-opengenai.b.aivencloud.com",
15
+ database="defaultdb",
16
+ port=14535,
17
+ )
18
+
19
+
20
+ DATABASE_URL = db_url
21
+ #DATABASE_URL = "sqlite+aiosqlite:///./test.db"
22
+
23
+
24
+ class Base(DeclarativeBase):
25
+ pass
26
+
27
+
28
+ class User(SQLAlchemyBaseUserTableUUID, Base):
29
+ pass
30
+
31
+
32
+ engine = create_async_engine(DATABASE_URL)
33
+ async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
34
+
35
+
36
+ async def create_db_and_tables():
37
+ async with engine.begin() as conn:
38
+ await conn.run_sync(Base.metadata.create_all)
39
+
40
+
41
+ async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
42
+ async with async_session_maker() as session:
43
+ yield session
44
+
45
+
46
+ async def get_user_db(session: AsyncSession = Depends(get_async_session)):
47
+ yield SQLAlchemyUserDatabase(session, User)
48
+
49
+
app.py → app/llm.py RENAMED
File without changes
app/schemas.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+ from fastapi_users import schemas
4
+
5
+
6
+ class UserRead(schemas.BaseUser[uuid.UUID]):
7
+ pass
8
+
9
+
10
+ class UserCreate(schemas.BaseUserCreate):
11
+ pass
12
+
13
+
14
+ class UserUpdate(schemas.BaseUserUpdate):
15
+ pass
app/users.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from typing import Optional
3
+
4
+ from fastapi import Depends, Request
5
+ from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
6
+ from fastapi_users.authentication import (
7
+ AuthenticationBackend,
8
+ BearerTransport,
9
+ JWTStrategy,
10
+ )
11
+ from fastapi_users.db import SQLAlchemyUserDatabase
12
+
13
+ from app.db import User, get_user_db
14
+
15
+ SECRET = "SECRET"
16
+
17
+
18
+ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
19
+ reset_password_token_secret = SECRET
20
+ verification_token_secret = SECRET
21
+
22
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
23
+ print(f"User {user.id} has registered.")
24
+
25
+ async def on_after_forgot_password(
26
+ self, user: User, token: str, request: Optional[Request] = None
27
+ ):
28
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
29
+
30
+ async def on_after_request_verify(
31
+ self, user: User, token: str, request: Optional[Request] = None
32
+ ):
33
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
34
+
35
+
36
+ async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
37
+ yield UserManager(user_db)
38
+
39
+
40
+ bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
41
+
42
+
43
+ def get_jwt_strategy() -> JWTStrategy:
44
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
45
+
46
+
47
+ auth_backend = AuthenticationBackend(
48
+ name="jwt",
49
+ transport=bearer_transport,
50
+ get_strategy=get_jwt_strategy,
51
+ )
52
+
53
+ fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
54
+
55
+ current_active_user = fastapi_users.current_user(active=True)
56
+
config.py DELETED
@@ -1,8 +0,0 @@
1
- import os
2
- #from pydantic import BaseSettings, Field
3
- from pydantic_settings import BaseSettings
4
- from pydantic import Field
5
- class Settings(BaseSettings):
6
- db_url: str = Field(..., env='DATABASE_URL')
7
-
8
- settings = Settings()
 
 
 
 
 
 
 
 
 
crud.py DELETED
@@ -1,37 +0,0 @@
1
- from sqlalchemy.orm import Session
2
-
3
- import models
4
- import schemas
5
-
6
-
7
- def get_user(db: Session, user_id: int):
8
- return db.query(models.User).filter(models.User.id == user_id).first()
9
-
10
-
11
- def get_user_by_email(db: Session, email: str):
12
- return db.query(models.User).filter(models.User.email == email).first()
13
-
14
-
15
- def get_users(db: Session, skip: int = 0, limit: int = 100):
16
- return db.query(models.User).offset(skip).limit(limit).all()
17
-
18
-
19
- def create_user(db: Session, user: schemas.UserCreate):
20
- fake_hashed_password = user.password + "notreallyhashed"
21
- db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
22
- db.add(db_user)
23
- db.commit()
24
- db.refresh(db_user)
25
- return db_user
26
-
27
-
28
- def get_items(db: Session, skip: int = 0, limit: int = 100):
29
- return db.query(models.Item).offset(skip).limit(limit).all()
30
-
31
-
32
- def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
33
- db_item = models.Item(**item.model_dump(), owner_id=user_id)
34
- db.add(db_item)
35
- db.commit()
36
- db.refresh(db_item)
37
- return db_item
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
database.py DELETED
@@ -1,28 +0,0 @@
1
- from sqlalchemy import create_engine
2
- from sqlalchemy.ext.declarative import declarative_base
3
- from sqlalchemy.orm import sessionmaker
4
- #from config import settings
5
-
6
- import os
7
- #db_url = os.environ.get("DATABASE_URL", "")
8
-
9
- from sqlalchemy import URL
10
-
11
- db_url = URL.create(
12
- "postgresql",
13
- username="avnadmin",
14
- password="AVNS_u12fHxoNLBbzD8TGpqN", # plain (unescaped) text
15
- host="pg-opengenai-opengenai.b.aivencloud.com",
16
- database="defaultdb",
17
- port=14535,
18
- )
19
- #database = databases.Database(settings.db_url)
20
- SQLALCHEMY_DATABASE_URL = db_url # "ibmabdulsalam.mysql.pythonanywhere-services.com" #"sqlite:///./sql_app.db"
21
- #SQLALCHEMY_DATABASE_URL = db_url #"postgresql://user:password@postgresserver/db"
22
-
23
- engine = create_engine(
24
- SQLALCHEMY_DATABASE_URL, pool_size=10
25
- )#, connect_args={"check_same_thread": False}
26
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
27
-
28
- Base = declarative_base()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docker-compose.yml DELETED
@@ -1,39 +0,0 @@
1
- version: "3"
2
-
3
- services:
4
- backend:
5
- build: ./app/Dockerfile
6
- command: uvicorn main:app --host 0.0.0.0
7
- networks:
8
- - caw
9
- ports:
10
- - "7860:7860"
11
- volumes:
12
- - ./config.yaml:/app/config.yaml
13
- environment:
14
- DATABASE_URL: postgresql://postgres:postgres@postgres:5432/postgres
15
- database:
16
- image: postgres:latest
17
- networks:
18
- - caw
19
- environment:
20
- POSTGRES_DB: postgres
21
- POSTGRES_USER: postgres
22
- POSTGRES_PASSWORD: postgres
23
- volumes:
24
- - database:/var/lib/postgresql/data
25
- ports:
26
- - "5432:5432"
27
- cache:
28
- image: redis:latest
29
- networks:
30
- - caw
31
- ports:
32
- - "6379:6379"
33
-
34
- volumes:
35
- database:
36
-
37
-
38
- networks:
39
- caw:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py CHANGED
@@ -1,62 +1,5 @@
1
- from fastapi import Depends, FastAPI, HTTPException
2
- from sqlalchemy.orm import Session
3
- import crud
4
- import models
5
- import schemas
6
- from database import SessionLocal, engine
7
- from app import llm_router
8
- from fastapi import APIRouter, FastAPI
9
- models.Base.metadata.create_all(bind=engine)
10
 
11
- # Dependency
12
- def get_db():
13
- db = SessionLocal()
14
- try:
15
- yield db
16
- finally:
17
- db.close()
18
-
19
- user_router = APIRouter(prefix="/user")
20
-
21
- @user_router.post("/users/", response_model=schemas.User, tags=["users"])
22
- def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
23
- db_user = crud.get_user_by_email(db, email=user.email)
24
- if db_user:
25
- raise HTTPException(status_code=400, detail="Email already registered")
26
- return crud.create_user(db=db, user=user)
27
-
28
-
29
- @user_router.get("/users/", response_model=list[schemas.User], tags=["users"])
30
- def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
31
- users = crud.get_users(db, skip=skip, limit=limit)
32
- return users
33
-
34
-
35
- @user_router.get("/users/{user_id}", response_model=schemas.User, tags=["users"] )
36
- def read_user(user_id: int, db: Session = Depends(get_db)):
37
- db_user = crud.get_user(db, user_id=user_id)
38
- if db_user is None:
39
- raise HTTPException(status_code=404, detail="User not found")
40
- return db_user
41
-
42
-
43
- @user_router.post("/users/{user_id}/items/", response_model=schemas.Item, tags=["users"] )
44
- def create_item_for_user(
45
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
46
- ):
47
- return crud.create_user_item(db=db, item=item, user_id=user_id)
48
-
49
-
50
- @user_router.get("/items/", response_model=list[schemas.Item], tags=["users"] )
51
- def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
52
- items = crud.get_items(db, skip=skip, limit=limit)
53
- return items
54
-
55
-
56
- app = FastAPI(
57
- docs_url="/",
58
- title="OpenGenAI",
59
- description="Your Excellect AI Physician")
60
-
61
- app.include_router(user_router)
62
- app.include_router(llm_router)
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import uvicorn
3
+ #from app.app import app
4
+ if __name__ == "__main__":
5
+ uvicorn.run("app.app:app", host="0.0.0.0", log_level="info")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.py DELETED
@@ -1,26 +0,0 @@
1
- from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
2
- from sqlalchemy.orm import relationship
3
-
4
- from database import Base
5
-
6
-
7
- class User(Base):
8
- __tablename__ = "users"
9
-
10
- id = Column(Integer, primary_key=True, index=True)
11
- email = Column(String, unique=True, index=True)
12
- hashed_password = Column(String)
13
- is_active = Column(Boolean, default=True)
14
-
15
- items = relationship("Item", back_populates="owner")
16
-
17
-
18
- class Item(Base):
19
- __tablename__ = "items"
20
-
21
- id = Column(Integer, primary_key=True, index=True)
22
- title = Column(String, index=True)
23
- description = Column(String, index=True)
24
- owner_id = Column(Integer, ForeignKey("users.id"))
25
-
26
- owner = relationship("User", back_populates="items")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -5,4 +5,4 @@ pymysql
5
  mysqlclient==1.3.12
6
  tensorflow
7
  transformers
8
- psycopg2-binary
 
5
  mysqlclient==1.3.12
6
  tensorflow
7
  transformers
8
+ psycopg2-binary
schemas.py DELETED
@@ -1,36 +0,0 @@
1
- from typing import Union
2
- from pydantic import BaseModel
3
-
4
-
5
- class ItemBase(BaseModel):
6
- title: str
7
- description: Union[str, None] = None
8
-
9
-
10
- class ItemCreate(ItemBase):
11
- pass
12
-
13
-
14
- class Item(ItemBase):
15
- id: int
16
- owner_id: int
17
-
18
- class Config:
19
- from_attributes = True
20
-
21
-
22
- class UserBase(BaseModel):
23
- email: str
24
-
25
-
26
- class UserCreate(UserBase):
27
- password: str
28
-
29
-
30
- class User(UserBase):
31
- id: int
32
- is_active: bool
33
- items: list[Item] = []
34
-
35
- class Config:
36
- from_attributes = True