Spaces:
Sleeping
Sleeping
theekshana
commited on
Commit
•
4a0d2c6
1
Parent(s):
995dee5
Update app.py
Browse files
app.py
CHANGED
@@ -1,173 +1,179 @@
|
|
1 |
-
"""
|
2 |
-
/*************************************************************************
|
3 |
-
*
|
4 |
-
* CONFIDENTIAL
|
5 |
-
* __________________
|
6 |
-
*
|
7 |
-
* Copyright (2023-2025) AI Labs, IronOne Technologies, LLC
|
8 |
-
* All Rights Reserved
|
9 |
-
*
|
10 |
-
* Author : Theekshana Samaradiwakara
|
11 |
-
* Description :Python Backend API to chat with private data
|
12 |
-
* CreatedDate : 14/11/2023
|
13 |
-
* LastModifiedDate : 15/10/2024
|
14 |
-
*************************************************************************/
|
15 |
-
"""
|
16 |
-
|
17 |
-
import os
|
18 |
-
import time
|
19 |
-
import sys
|
20 |
-
import logging
|
21 |
-
import datetime
|
22 |
-
import uvicorn
|
23 |
-
from dotenv import load_dotenv
|
24 |
-
|
25 |
-
from fastapi import FastAPI, APIRouter, HTTPException, status
|
26 |
-
from fastapi import HTTPException, status
|
27 |
-
from fastapi.middleware.cors import CORSMiddleware
|
28 |
-
|
29 |
-
from schema import UserQuery, ResponseModel, Document, LoginRequest, UserModel
|
30 |
-
from controller import get_QA_Answers, get_avaliable_models
|
31 |
-
|
32 |
-
|
33 |
-
def filer():
|
34 |
-
return "logs/log"
|
35 |
-
# today = datetime.datetime.today()
|
36 |
-
# log_filename = f"logs/{today.year}-{today.month:02d}-{today.day:02d}.log"
|
37 |
-
# return log_filename
|
38 |
-
|
39 |
-
|
40 |
-
file_handler = logging.FileHandler(filer())
|
41 |
-
# file_handler = logging.handlers.TimedRotatingFileHandler(filer(),when="D")
|
42 |
-
file_handler.setLevel(logging.INFO)
|
43 |
-
|
44 |
-
logging.basicConfig(
|
45 |
-
level=logging.DEBUG,
|
46 |
-
format="%(asctime)s %(levelname)s (%(name)s) : %(message)s",
|
47 |
-
datefmt="%Y-%m-%d %H:%M:%S",
|
48 |
-
handlers=[file_handler],
|
49 |
-
force=True,
|
50 |
-
)
|
51 |
-
|
52 |
-
logger = logging.getLogger(__name__)
|
53 |
-
|
54 |
-
load_dotenv()
|
55 |
-
host = os.environ.get("APP_HOST")
|
56 |
-
port = int(os.environ.get("APP_PORT"))
|
57 |
-
|
58 |
-
|
59 |
-
class ChatAPI:
|
60 |
-
|
61 |
-
def __init__(self):
|
62 |
-
self.router = APIRouter()
|
63 |
-
self.router.add_api_route("/api/v1/health", self.hello, methods=["GET"])
|
64 |
-
self.router.add_api_route("/api/v1/models", self.avaliable_models, methods=["GET"])
|
65 |
-
self.router.add_api_route(
|
66 |
-
"/api/v1/login", self.login, methods=["POST"], response_model=UserModel
|
67 |
-
)
|
68 |
-
self.router.add_api_route("/api/v1/chat", self.chat, methods=["POST"])
|
69 |
-
|
70 |
-
async def hello(self):
|
71 |
-
return "Hello there!"
|
72 |
-
|
73 |
-
async def avaliable_models(self):
|
74 |
-
logger.info("getting avaliable models")
|
75 |
-
models = get_avaliable_models()
|
76 |
-
|
77 |
-
if not models:
|
78 |
-
logger.exception("models not found")
|
79 |
-
raise HTTPException(
|
80 |
-
status_code=status.HTTP_404_NOT_FOUND, detail="models not found"
|
81 |
-
)
|
82 |
-
|
83 |
-
return models
|
84 |
-
|
85 |
-
async def login(self, login_request: LoginRequest):
|
86 |
-
logger.info(f"username password: {login_request} ")
|
87 |
-
# Dummy user data for demonstration (normally, you'd use a database)
|
88 |
-
dummy_users_db = {
|
89 |
-
"john_doe": {
|
90 |
-
"userId": 1,
|
91 |
-
"firstName": "John",
|
92 |
-
"lastName": "Doe",
|
93 |
-
"userName": "john_doe",
|
94 |
-
"password": "password", # Normally, passwords would be hashed and stored securely
|
95 |
-
"token": "dummy_token_123", # In a real scenario, this would be a JWT or another kind of token
|
96 |
-
}
|
97 |
-
}
|
98 |
-
# Fetch user by username
|
99 |
-
# user = dummy_users_db.get(login_request.username)
|
100 |
-
user = dummy_users_db.get("john_doe")
|
101 |
-
# Validate user credentials
|
102 |
-
if not user or user["password"] != login_request.password:
|
103 |
-
raise HTTPException(status_code=401, detail="Invalid username or password")
|
104 |
-
|
105 |
-
# Return the user model without the password
|
106 |
-
return UserModel(
|
107 |
-
userId=user["userId"],
|
108 |
-
firstName=user["firstName"],
|
109 |
-
lastName=user["lastName"],
|
110 |
-
userName=user["userName"],
|
111 |
-
token=user["token"],
|
112 |
-
)
|
113 |
-
|
114 |
-
async def chat(
|
115 |
-
self, userQuery: UserQuery
|
116 |
-
): #:UserQuery):# -> ResponseModel: #chat: QueryModel): # -> ResponseModel:
|
117 |
-
"""Makes query to doc store via Langchain pipeline.
|
118 |
-
|
119 |
-
:param chat.: question, model, dataset location, history of the chat.
|
120 |
-
:type chat: QueryModel
|
121 |
-
"""
|
122 |
-
logger.info(f"userQuery: {userQuery} ")
|
123 |
-
|
124 |
-
try:
|
125 |
-
start = time.time()
|
126 |
-
res = get_QA_Answers(userQuery)
|
127 |
-
logger.info(
|
128 |
-
f"-------------------------- answer: {res} -------------------------- "
|
129 |
-
)
|
130 |
-
# return res
|
131 |
-
end = time.time()
|
132 |
-
logger.info(
|
133 |
-
f"-------------------------- Server process (took {round(end - start, 2)} s.) \n: {res}"
|
134 |
-
)
|
135 |
-
print(
|
136 |
-
f" \n -------------------------- Server process (took {round(end - start, 2)} s.) ------------------------- \n"
|
137 |
-
)
|
138 |
-
return res
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
app
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
/*************************************************************************
|
3 |
+
*
|
4 |
+
* CONFIDENTIAL
|
5 |
+
* __________________
|
6 |
+
*
|
7 |
+
* Copyright (2023-2025) AI Labs, IronOne Technologies, LLC
|
8 |
+
* All Rights Reserved
|
9 |
+
*
|
10 |
+
* Author : Theekshana Samaradiwakara
|
11 |
+
* Description :Python Backend API to chat with private data
|
12 |
+
* CreatedDate : 14/11/2023
|
13 |
+
* LastModifiedDate : 15/10/2024
|
14 |
+
*************************************************************************/
|
15 |
+
"""
|
16 |
+
|
17 |
+
import os
|
18 |
+
import time
|
19 |
+
import sys
|
20 |
+
import logging
|
21 |
+
import datetime
|
22 |
+
import uvicorn
|
23 |
+
from dotenv import load_dotenv
|
24 |
+
|
25 |
+
from fastapi import FastAPI, APIRouter, HTTPException, status
|
26 |
+
from fastapi import HTTPException, status
|
27 |
+
from fastapi.middleware.cors import CORSMiddleware
|
28 |
+
|
29 |
+
from schema import UserQuery, ResponseModel, Document, LoginRequest, UserModel
|
30 |
+
from controller import get_QA_Answers, get_avaliable_models
|
31 |
+
|
32 |
+
|
33 |
+
def filer():
|
34 |
+
return "logs/log"
|
35 |
+
# today = datetime.datetime.today()
|
36 |
+
# log_filename = f"logs/{today.year}-{today.month:02d}-{today.day:02d}.log"
|
37 |
+
# return log_filename
|
38 |
+
|
39 |
+
|
40 |
+
file_handler = logging.FileHandler(filer())
|
41 |
+
# file_handler = logging.handlers.TimedRotatingFileHandler(filer(),when="D")
|
42 |
+
file_handler.setLevel(logging.INFO)
|
43 |
+
|
44 |
+
logging.basicConfig(
|
45 |
+
level=logging.DEBUG,
|
46 |
+
format="%(asctime)s %(levelname)s (%(name)s) : %(message)s",
|
47 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
48 |
+
handlers=[file_handler],
|
49 |
+
force=True,
|
50 |
+
)
|
51 |
+
|
52 |
+
logger = logging.getLogger(__name__)
|
53 |
+
|
54 |
+
load_dotenv()
|
55 |
+
host = os.environ.get("APP_HOST")
|
56 |
+
port = int(os.environ.get("APP_PORT"))
|
57 |
+
|
58 |
+
|
59 |
+
class ChatAPI:
|
60 |
+
|
61 |
+
def __init__(self):
|
62 |
+
self.router = APIRouter()
|
63 |
+
self.router.add_api_route("/api/v1/health", self.hello, methods=["GET"])
|
64 |
+
self.router.add_api_route("/api/v1/models", self.avaliable_models, methods=["GET"])
|
65 |
+
self.router.add_api_route(
|
66 |
+
"/api/v1/login", self.login, methods=["POST"], response_model=UserModel
|
67 |
+
)
|
68 |
+
self.router.add_api_route("/api/v1/chat", self.chat, methods=["POST"])
|
69 |
+
|
70 |
+
async def hello(self):
|
71 |
+
return "Hello there!"
|
72 |
+
|
73 |
+
async def avaliable_models(self):
|
74 |
+
logger.info("getting avaliable models")
|
75 |
+
models = get_avaliable_models()
|
76 |
+
|
77 |
+
if not models:
|
78 |
+
logger.exception("models not found")
|
79 |
+
raise HTTPException(
|
80 |
+
status_code=status.HTTP_404_NOT_FOUND, detail="models not found"
|
81 |
+
)
|
82 |
+
|
83 |
+
return models
|
84 |
+
|
85 |
+
async def login(self, login_request: LoginRequest):
|
86 |
+
logger.info(f"username password: {login_request} ")
|
87 |
+
# Dummy user data for demonstration (normally, you'd use a database)
|
88 |
+
dummy_users_db = {
|
89 |
+
"john_doe": {
|
90 |
+
"userId": 1,
|
91 |
+
"firstName": "John",
|
92 |
+
"lastName": "Doe",
|
93 |
+
"userName": "john_doe",
|
94 |
+
"password": "password", # Normally, passwords would be hashed and stored securely
|
95 |
+
"token": "dummy_token_123", # In a real scenario, this would be a JWT or another kind of token
|
96 |
+
}
|
97 |
+
}
|
98 |
+
# Fetch user by username
|
99 |
+
# user = dummy_users_db.get(login_request.username)
|
100 |
+
user = dummy_users_db.get("john_doe")
|
101 |
+
# Validate user credentials
|
102 |
+
if not user or user["password"] != login_request.password:
|
103 |
+
raise HTTPException(status_code=401, detail="Invalid username or password")
|
104 |
+
|
105 |
+
# Return the user model without the password
|
106 |
+
return UserModel(
|
107 |
+
userId=user["userId"],
|
108 |
+
firstName=user["firstName"],
|
109 |
+
lastName=user["lastName"],
|
110 |
+
userName=user["userName"],
|
111 |
+
token=user["token"],
|
112 |
+
)
|
113 |
+
|
114 |
+
async def chat(
|
115 |
+
self, userQuery: UserQuery
|
116 |
+
): #:UserQuery):# -> ResponseModel: #chat: QueryModel): # -> ResponseModel:
|
117 |
+
"""Makes query to doc store via Langchain pipeline.
|
118 |
+
|
119 |
+
:param chat.: question, model, dataset location, history of the chat.
|
120 |
+
:type chat: QueryModel
|
121 |
+
"""
|
122 |
+
logger.info(f"userQuery: {userQuery} ")
|
123 |
+
|
124 |
+
try:
|
125 |
+
start = time.time()
|
126 |
+
res = get_QA_Answers(userQuery)
|
127 |
+
logger.info(
|
128 |
+
f"-------------------------- answer: {res} -------------------------- "
|
129 |
+
)
|
130 |
+
# return res
|
131 |
+
end = time.time()
|
132 |
+
logger.info(
|
133 |
+
f"-------------------------- Server process (took {round(end - start, 2)} s.) \n: {res}"
|
134 |
+
)
|
135 |
+
print(
|
136 |
+
f" \n -------------------------- Server process (took {round(end - start, 2)} s.) ------------------------- \n"
|
137 |
+
)
|
138 |
+
# return res
|
139 |
+
return {
|
140 |
+
"user_input": userQuery.user_question,
|
141 |
+
"bot_response": res["bot_response"],
|
142 |
+
"format_data": res["format_data"],
|
143 |
+
}
|
144 |
+
|
145 |
+
|
146 |
+
except HTTPException as e:
|
147 |
+
logger.exception(e)
|
148 |
+
raise e
|
149 |
+
|
150 |
+
except Exception as e:
|
151 |
+
logger.exception(e)
|
152 |
+
raise HTTPException(status_code=400, detail=f"Error : {e}")
|
153 |
+
|
154 |
+
|
155 |
+
# initialize API
|
156 |
+
app = FastAPI(title="Boardpac chatbot API")
|
157 |
+
api = ChatAPI()
|
158 |
+
app.include_router(api.router)
|
159 |
+
|
160 |
+
# origins = ['http://localhost:8000','http://192.168.10.100:8000']
|
161 |
+
|
162 |
+
app.add_middleware(
|
163 |
+
CORSMiddleware,
|
164 |
+
allow_origins=["*"], # origins,
|
165 |
+
allow_credentials=True,
|
166 |
+
allow_methods=["*"],
|
167 |
+
allow_headers=["*"],
|
168 |
+
)
|
169 |
+
|
170 |
+
if __name__ == "__main__":
|
171 |
+
|
172 |
+
host = "0.0.0.0"
|
173 |
+
port = 8000
|
174 |
+
|
175 |
+
# config = uvicorn.Config("server:app",host=host, port=port, log_config= logging.basicConfig())
|
176 |
+
config = uvicorn.Config("server:app", host=host, port=port)
|
177 |
+
server = uvicorn.Server(config)
|
178 |
+
server.run()
|
179 |
+
# uvicorn.run(app)
|