Spaces:
Sleeping
Sleeping
OnlyBiggg
commited on
Commit
·
e2b74e4
0
Parent(s):
Initial commit
Browse files- .env +1 -0
- Dockerfile +11 -0
- __pycache__/app.cpython-39.pyc +0 -0
- __pycache__/main.cpython-39.pyc +0 -0
- app/api/__pycache__/routes.cpython-39.pyc +0 -0
- app/api/routes.py +264 -0
- app/busbooking-451909-aa92e337868d.json +13 -0
- app/core/__pycache__/config.cpython-39.pyc +0 -0
- app/core/config.py +9 -0
- app/services/__pycache__/api.cpython-39.pyc +0 -0
- app/services/__pycache__/external_api.cpython-39.pyc +0 -0
- app/services/api.py +61 -0
- app/templates/index.html +25 -0
- app/types/Respone.py +35 -0
- app/types/__pycache__/Respone.cpython-39.pyc +0 -0
- app/utils/__pycache__/constants.cpython-39.pyc +0 -0
- app/utils/code_province.json +68 -0
- app/utils/constants.py +5 -0
- main.py +10 -0
- requirements.txt +24 -0
.env
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
API_BASE_URL=https://api-dev.futabus.vn
|
Dockerfile
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
|
3 |
+
ENV API_BASE_URL https://api-dev.futabus.vn
|
4 |
+
|
5 |
+
COPY . .
|
6 |
+
|
7 |
+
WORKDIR /
|
8 |
+
|
9 |
+
RUN pip install --no-cache-dir --upgrade -r /requirements.txt
|
10 |
+
|
11 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
__pycache__/app.cpython-39.pyc
ADDED
Binary file (435 Bytes). View file
|
|
__pycache__/main.cpython-39.pyc
ADDED
Binary file (443 Bytes). View file
|
|
app/api/__pycache__/routes.cpython-39.pyc
ADDED
Binary file (7.63 kB). View file
|
|
app/api/routes.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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I, APIRouter, HTTPException, Request, Response # type: ignore
|
2 |
+
from fastapi.responses import JSONResponse, RedirectResponse, HTMLResponse # type: ignore
|
3 |
+
from datetime import datetime, timedelta
|
4 |
+
from fastapi.templating import Jinja2Templates
|
5 |
+
|
6 |
+
|
7 |
+
from app.services import api
|
8 |
+
from app.utils.constants import code_province
|
9 |
+
from app.types.Respone import DialogFlowResponseAPI
|
10 |
+
router = APIRouter()
|
11 |
+
|
12 |
+
templates = Jinja2Templates(directory="app/templates")
|
13 |
+
|
14 |
+
def to_datetime_from_Dialogflow(time: dict):
|
15 |
+
date_time = datetime(int(time["year"]), int(time["month"]), int(time["day"]))
|
16 |
+
return date_time
|
17 |
+
|
18 |
+
# Xử lý fromTime và toTime
|
19 |
+
def process_dates_to_timestamp(from_time: datetime = None, to_time: datetime = None):
|
20 |
+
print(from_time)
|
21 |
+
if to_time is None and from_time is not None:
|
22 |
+
to_time = from_time.replace(hour=23, minute=59, second=59)
|
23 |
+
|
24 |
+
if from_time is None:
|
25 |
+
today = datetime.today().date()
|
26 |
+
from_time = datetime.combine(today, datetime.min.time())
|
27 |
+
to_time = datetime.combine(today, datetime.max.time()) - timedelta(microseconds=1)
|
28 |
+
|
29 |
+
return int(from_time.timestamp()) * 1000 , int(to_time.timestamp()) * 1000
|
30 |
+
def get_param_from_dialogflow(body: any):
|
31 |
+
session_info = body.get("sessionInfo", {})
|
32 |
+
parameters = session_info.get("parameters")
|
33 |
+
raw_date = parameters.get("date")
|
34 |
+
if raw_date is not None:
|
35 |
+
raw_date = to_datetime_from_Dialogflow(raw_date)
|
36 |
+
raw_departure_city = parameters.get("departure_city")
|
37 |
+
raw_destination_city = parameters.get("destination_city")
|
38 |
+
raw_ticket_number = parameters.get("ticket_number")
|
39 |
+
raw_time_of_day = parameters.get("time_of_day")
|
40 |
+
return raw_departure_city, raw_destination_city, raw_ticket_number, raw_date, raw_time_of_day
|
41 |
+
|
42 |
+
async def search_route_ids_from_province(departure_code: str, destination_code: str):
|
43 |
+
response = await api.get(f'/metadata/office/routes?DestCode={destination_code}&OriginCode={departure_code}')
|
44 |
+
route_ids = []
|
45 |
+
if isinstance(response, list): # Kiểm tra nếu data là danh sách
|
46 |
+
route_ids = [route.get("routeId", -1) for route in response]
|
47 |
+
|
48 |
+
return route_ids
|
49 |
+
|
50 |
+
@router.post('/routes')
|
51 |
+
async def route(request: Request):
|
52 |
+
body = await request.json()
|
53 |
+
raw_departure_city, raw_destination_city, raw_ticket_number , raw_date, _ = get_param_from_dialogflow(body)
|
54 |
+
|
55 |
+
|
56 |
+
ticket_count = int(raw_ticket_number) if raw_ticket_number else 1
|
57 |
+
|
58 |
+
if raw_date is None:
|
59 |
+
from_time, to_time = process_dates_to_timestamp()
|
60 |
+
date = datetime.today().date().strftime('%m-%d-%Y')
|
61 |
+
else:
|
62 |
+
date = raw_date.strftime('%m-%d-%Y')
|
63 |
+
from_time, to_time = process_dates_to_timestamp(raw_date)
|
64 |
+
departure_code = code_province.get(raw_departure_city)
|
65 |
+
destination_code = code_province.get(raw_destination_city)
|
66 |
+
route_dep_to_des = await search_route_ids_from_province(departure_code,destination_code)
|
67 |
+
route_des_to_dep = await search_route_ids_from_province(destination_code,departure_code)
|
68 |
+
routes_ids = list(set(route_dep_to_des + route_des_to_dep))
|
69 |
+
payload = {
|
70 |
+
"from_time": from_time,
|
71 |
+
"to_time": to_time,
|
72 |
+
"route_ids": routes_ids,
|
73 |
+
"ticket_count": 1,
|
74 |
+
"sort_by": ["price", "departure_time"]
|
75 |
+
}
|
76 |
+
try:
|
77 |
+
respone = await api.post("/search/trips", payload=payload)
|
78 |
+
data = respone["data"]["items"]
|
79 |
+
total = respone["data"]["total"]
|
80 |
+
if total > 0:
|
81 |
+
price = data[0]["price"]
|
82 |
+
list_raw_departure_times = sorted(list(set([ trip["raw_departure_time"] for trip in data])))
|
83 |
+
schedule_time_trip = "**" + "** | **".join(map(str, list_raw_departure_times)) + "**"
|
84 |
+
link = f'https://stag.futabus.vn/dat-ve?from={departure_code}&fromTime={date}&isReturn=false&ticketCount={ticket_count}&to={destination_code}&toTime='
|
85 |
+
text = [f"Lộ trình **{raw_departure_city}** - **{raw_destination_city}**: **{total}** tuyến xe.\n \
|
86 |
+
Thời gian các tuyến xe khởi hành: {schedule_time_trip}\n \
|
87 |
+
Giá vé: **{price}** VND.\n \
|
88 |
+
Quý khách vui lòng truy cập vào [**tại đây**]({link}) để xem chi tiết lịch trình."]
|
89 |
+
payload = {
|
90 |
+
"richContent": [
|
91 |
+
[
|
92 |
+
{
|
93 |
+
"type": "chips",
|
94 |
+
"options": [
|
95 |
+
{"text": "Đặt vé"},
|
96 |
+
{"text": "Xem lịch trình khác"},
|
97 |
+
{"text": "Không, cảm ơn"}
|
98 |
+
]
|
99 |
+
}
|
100 |
+
]
|
101 |
+
]
|
102 |
+
}
|
103 |
+
|
104 |
+
return DialogFlowResponseAPI(text=text, payload=payload)
|
105 |
+
|
106 |
+
text = [f"Hệ thống không tìm thấy tuyến xe nào phù hợp với lộ trình **{raw_departure_city}** - **{raw_destination_city}** của quý khách.\n Quý khách vui lòng thử lại với lộ trình khác hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."]
|
107 |
+
payload = {
|
108 |
+
"richContent": [
|
109 |
+
[
|
110 |
+
{
|
111 |
+
"type": "chips",
|
112 |
+
"options": [
|
113 |
+
{"text": "Xem lịch trình khác"},
|
114 |
+
{"text": "Không, cảm ơn"}
|
115 |
+
]
|
116 |
+
}
|
117 |
+
]
|
118 |
+
]
|
119 |
+
}
|
120 |
+
return DialogFlowResponseAPI(text=text, payload=payload)
|
121 |
+
# return DialogFlowResponeAPI(text=['Hello'])
|
122 |
+
except Exception as e:
|
123 |
+
return DialogFlowResponseAPI(text=["Hệ thống xảy ra lỗi. Quý khách vui lòng thử lại sau hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."])
|
124 |
+
|
125 |
+
|
126 |
+
@router.post('/price')
|
127 |
+
async def price(request: Request):
|
128 |
+
body = await request.json()
|
129 |
+
raw_departure_city, raw_destination_city, _, raw_date, _ = get_param_from_dialogflow(body)
|
130 |
+
|
131 |
+
if raw_date is None:
|
132 |
+
from_time, to_time = process_dates_to_timestamp()
|
133 |
+
from_time, to_time = process_dates_to_timestamp(raw_date)
|
134 |
+
|
135 |
+
departure_code = code_province.get(raw_departure_city)
|
136 |
+
destination_code = code_province.get(raw_destination_city)
|
137 |
+
route_dep_to_des = await search_route_ids_from_province(departure_code,destination_code)
|
138 |
+
route_des_to_dep = await search_route_ids_from_province(destination_code,departure_code)
|
139 |
+
routes_ids = list(set(route_dep_to_des + route_des_to_dep))
|
140 |
+
payload = {
|
141 |
+
"from_time": from_time,
|
142 |
+
"to_time": to_time,
|
143 |
+
"route_ids": routes_ids,
|
144 |
+
"ticket_count": 1,
|
145 |
+
"sort_by": ["price", "departure_time"]
|
146 |
+
}
|
147 |
+
try:
|
148 |
+
respone = await api.post("/search/trips", payload=payload)
|
149 |
+
total = respone["data"]["total"]
|
150 |
+
if total > 0:
|
151 |
+
price = respone["data"]["items"][0]["price"]
|
152 |
+
text = [f"Lộ trình **{raw_departure_city}** - **{raw_destination_city}**\n"
|
153 |
+
f"Giá vé: **{price}** VND.\nBạn có muốn đặt vé không?"
|
154 |
+
]
|
155 |
+
payload = {
|
156 |
+
"richContent": [
|
157 |
+
[
|
158 |
+
{
|
159 |
+
"type": "chips",
|
160 |
+
"options": [
|
161 |
+
{"text": "Có, tôi muốn đặt vé"},
|
162 |
+
{"text": "Xem giá vé lịch trình khác"},
|
163 |
+
{"text": "Không, cảm ơn"}
|
164 |
+
]
|
165 |
+
}
|
166 |
+
]
|
167 |
+
]
|
168 |
+
}
|
169 |
+
return DialogFlowResponseAPI(text=text, payload=payload)
|
170 |
+
text = [f"Hệ thống không tìm thấy tuyến xe nào phù hợp với lộ trình **{raw_departure_city}** - **{raw_destination_city}** của quý khách.\n Quý khách vui lòng thử lại với lộ trình khác hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."]
|
171 |
+
payload={
|
172 |
+
"richContent": [
|
173 |
+
[
|
174 |
+
{
|
175 |
+
"type": "chips",
|
176 |
+
"options": [
|
177 |
+
{"text": "Xem giá vé lịch trình khác"},
|
178 |
+
{"text": "Không, cảm ơn"}
|
179 |
+
]
|
180 |
+
}
|
181 |
+
]
|
182 |
+
]
|
183 |
+
}
|
184 |
+
|
185 |
+
return DialogFlowResponseAPI(text=text, payload=payload)
|
186 |
+
except:
|
187 |
+
return DialogFlowResponseAPI(text=["Hệ thống xảy ra lỗi. Quý khách vui lòng thử lại sau hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."])
|
188 |
+
@router.post('/trip/booking')
|
189 |
+
async def booking_trip(request: Request) -> Response:
|
190 |
+
body = await request.json()
|
191 |
+
raw_departure_city, raw_destination_city, raw_ticket_number, raw_date, raw_time_of_day = get_param_from_dialogflow(body)
|
192 |
+
|
193 |
+
date = raw_date.strftime('%m-%d-%Y')
|
194 |
+
from_time, to_time = process_dates_to_timestamp(raw_date)
|
195 |
+
ticket_count = int(raw_ticket_number) if raw_ticket_number else 1
|
196 |
+
|
197 |
+
departure_code = code_province.get(raw_departure_city)
|
198 |
+
destination_code = code_province.get(raw_destination_city)
|
199 |
+
|
200 |
+
route_dep_to_des = await search_route_ids_from_province(departure_code,destination_code)
|
201 |
+
route_des_to_dep = await search_route_ids_from_province(destination_code,departure_code)
|
202 |
+
routes_ids = list(set(route_dep_to_des + route_des_to_dep))
|
203 |
+
payload = {
|
204 |
+
"from_time": from_time,
|
205 |
+
"to_time": to_time,
|
206 |
+
"route_ids": routes_ids,
|
207 |
+
"ticket_count": ticket_count,
|
208 |
+
"sort_by": ["price", "departure_time"]
|
209 |
+
}
|
210 |
+
try:
|
211 |
+
respone = await api.post("/search/trips", payload=payload)
|
212 |
+
if respone.get('status') == 200:
|
213 |
+
data = respone["data"]["items"]
|
214 |
+
total = respone["data"]["total"]
|
215 |
+
if total > 0:
|
216 |
+
price = respone["data"]["items"][0]["price"]
|
217 |
+
list_raw_departure_times = sorted(list(set([ trip["raw_departure_time"] for trip in data])))
|
218 |
+
schedule_time_trip = "**" + "** | **".join(map(str, list_raw_departure_times)) + "**"
|
219 |
+
link = f'https://stag.futabus.vn/dat-ve?from={departure_code}&fromTime={date}&isReturn=false&ticketCount={ticket_count}&to={destination_code}&toTime='
|
220 |
+
|
221 |
+
text= [f"Lộ trình **{raw_departure_city}** - **{raw_destination_city}**: **{total}** tuyến xe.\n"
|
222 |
+
f"Thời gian các tuyến xe khởi hành: {schedule_time_trip}\n"
|
223 |
+
f"Giá vé: **{price}** VND.\n"
|
224 |
+
f"Quý khách vui lòng truy cập vào [**tại đây**]({link}) để tiến hành đặt vé."]
|
225 |
+
return DialogFlowResponseAPI(text=text)
|
226 |
+
|
227 |
+
text = [f"Hệ thống không tìm thấy tuyến xe nào phù hợp với lộ trình **{raw_departure_city}** - **{raw_destination_city}** của quý khách.\n Quý khách vui lòng thử lại với lộ trình khác hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."]
|
228 |
+
payload={
|
229 |
+
"richContent": [
|
230 |
+
[
|
231 |
+
{
|
232 |
+
"type": "chips",
|
233 |
+
"options": [
|
234 |
+
{"text": "Xem lịch trình khác"},
|
235 |
+
{"text": "Không, cảm ơn"}
|
236 |
+
]
|
237 |
+
}
|
238 |
+
]
|
239 |
+
]
|
240 |
+
}
|
241 |
+
|
242 |
+
return DialogFlowResponseAPI(text=text, payload=payload)
|
243 |
+
except Exception as e:
|
244 |
+
print(e)
|
245 |
+
return JSONResponse(
|
246 |
+
{
|
247 |
+
"fulfillment_response": {
|
248 |
+
"messages": [
|
249 |
+
{
|
250 |
+
"text": {
|
251 |
+
"text": ["Hệ thống xảy ra lỗi. Quý khách vui lòng thử lại sau hoặc liên hệ Trung tâm tổng đài 1900 6067 để được hỗ trợ."]
|
252 |
+
}
|
253 |
+
}
|
254 |
+
]
|
255 |
+
},
|
256 |
+
}
|
257 |
+
)
|
258 |
+
@router.get("/")
|
259 |
+
def home():
|
260 |
+
return "Hello World!"
|
261 |
+
|
262 |
+
@router.get('/chatbot', response_class=HTMLResponse)
|
263 |
+
async def index(request: Request):
|
264 |
+
return templates.TemplateResponse("index.html", {"request": request, "title": "Dawi Chatbot"})
|
app/busbooking-451909-aa92e337868d.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"type": "service_account",
|
3 |
+
"project_id": "busbooking-451909",
|
4 |
+
"private_key_id": "aa92e337868d77340f1e1bc3d0119738f48b8a49",
|
5 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDwozPFZx+v2DH+\nXFMLaft+4tnaWKPDGEgQ0IGwmXUtgVzd7iuH/fI9tXFiRw1ecFGAzundf1qiJJis\npMgfMxXm5fWpaKa4AM5LKxootKYPLZeJ3/N+BhJkCSmDXZmk6TuBff3WBRUkDj9n\nQTnpRSCBsCxArvm2zw6PSUqHwPiW/g05q6escmHXZUO3wpLgFz41u1Xy7M2Rc/bO\n3j6OYogYxZkp5aY5EpWhUKO2+qNVaVQqDweJhQ7/M+UpX5Va9VdMAM7dm3BUIy1Y\n3c8NDgUvL5uXKljoHrPpGXm+1QZTnrT18y3Jmo5PxkIF0u/SXDnFTYl9CL876ewq\nYaN55d9fAgMBAAECggEAArpm8Nr9cfnqfy6+xkdaUZLy01Xj7WdOEdq7Taw/ttdb\nnSyBE9aeM3LmKS4TCboOQn6WCivSdDoj/PkVR71Fh0ueIGCOW1GvBQ0lC8cYht2G\ndUqzsP8SoE22ScX64vK9+PbbtNxz4+fBckM8C9f7yVyc89LIA/mO+bLkBGv8pYGQ\nNg2Po8Oi8wjA06XMEaFVfrURnyQoUVVeIXBn/L0TViL/vSo0wshYQw9hoXI6RrUW\n1SDjfRmzOIt63R7x4Bn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client_id": "111019976759266480456",
|
8 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
9 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
10 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
11 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/chatbot%40busbooking-451909.iam.gserviceaccount.com",
|
12 |
+
"universe_domain": "googleapis.com"
|
13 |
+
}
|
app/core/__pycache__/config.cpython-39.pyc
ADDED
Binary file (441 Bytes). View file
|
|
app/core/config.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
|
4 |
+
load_dotenv() # Load biến môi trường từ file .env
|
5 |
+
|
6 |
+
class Settings:
|
7 |
+
API_BASE_URL = os.getenv("API_BASE_URL") # API gốc (backend dev)
|
8 |
+
|
9 |
+
settings = Settings()
|
app/services/__pycache__/api.cpython-39.pyc
ADDED
Binary file (2.86 kB). View file
|
|
app/services/__pycache__/external_api.cpython-39.pyc
ADDED
Binary file (2.86 kB). View file
|
|
app/services/api.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import httpx
|
2 |
+
from app.core.config import settings
|
3 |
+
from typing import Optional, Dict, Any
|
4 |
+
|
5 |
+
API_BASE_URL = settings.API_BASE_URL # Lấy base URL từ config
|
6 |
+
|
7 |
+
async def get(endpoint: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None):
|
8 |
+
"""Gọi API GET"""
|
9 |
+
url = f"{API_BASE_URL}{endpoint}"
|
10 |
+
headers = headers or {}
|
11 |
+
async with httpx.AsyncClient() as client:
|
12 |
+
try:
|
13 |
+
response = await client.get(url, headers=headers, params=params)
|
14 |
+
response.raise_for_status()
|
15 |
+
return response.json()
|
16 |
+
except httpx.HTTPStatusError as http_err:
|
17 |
+
return {"error": f"HTTP {http_err.response.status_code}: {http_err.response.text}"}
|
18 |
+
except Exception as err:
|
19 |
+
return {"error": f"Request failed: {str(err)}"}
|
20 |
+
|
21 |
+
async def post(endpoint: str , payload: Dict[str, Any] = None,headers: Optional[Dict[str, str]] = None):
|
22 |
+
"""Gọi API POST"""
|
23 |
+
url = f"{API_BASE_URL}{endpoint}"
|
24 |
+
headers = headers or {"Content-Type": "application/json"}
|
25 |
+
async with httpx.AsyncClient() as client:
|
26 |
+
try:
|
27 |
+
response = await client.post(url, json=payload, headers=headers)
|
28 |
+
response.raise_for_status()
|
29 |
+
return response.json()
|
30 |
+
except httpx.HTTPStatusError as http_err:
|
31 |
+
return {"error": f"HTTP {http_err.response.status_code}: {http_err.response.text}"}
|
32 |
+
except Exception as err:
|
33 |
+
return {"error": f"Request failed: {str(err)}"}
|
34 |
+
|
35 |
+
async def put_api(endpoint: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None):
|
36 |
+
"""Gọi API PUT"""
|
37 |
+
url = f"{API_BASE_URL}{endpoint}"
|
38 |
+
headers = headers or {"Content-Type": "application/json"}
|
39 |
+
async with httpx.AsyncClient() as client:
|
40 |
+
try:
|
41 |
+
response = await client.put(url, json=payload, headers=headers)
|
42 |
+
response.raise_for_status()
|
43 |
+
return response.json()
|
44 |
+
except httpx.HTTPStatusError as http_err:
|
45 |
+
return {"error": f"HTTP {http_err.response.status_code}: {http_err.response.text}"}
|
46 |
+
except Exception as err:
|
47 |
+
return {"error": f"Request failed: {str(err)}"}
|
48 |
+
|
49 |
+
async def delete_api(endpoint: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None):
|
50 |
+
"""Gọi API DELETE"""
|
51 |
+
url = f"{API_BASE_URL}{endpoint}"
|
52 |
+
headers = headers or {}
|
53 |
+
async with httpx.AsyncClient() as client:
|
54 |
+
try:
|
55 |
+
response = await client.delete(url, headers=headers, params=params)
|
56 |
+
response.raise_for_status()
|
57 |
+
return response.json()
|
58 |
+
except httpx.HTTPStatusError as http_err:
|
59 |
+
return {"error": f"HTTP {http_err.response.status_code}: {http_err.response.text}"}
|
60 |
+
except Exception as err:
|
61 |
+
return {"error": f"Request failed: {str(err)}"}
|
app/templates/index.html
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<link rel="stylesheet" href="https://www.gstatic.com/dialogflow-console/fast/df-messenger/prod/v1/themes/df-messenger-default.css">
|
2 |
+
<script src="https://www.gstatic.com/dialogflow-console/fast/df-messenger/prod/v1/df-messenger.js"></script>
|
3 |
+
<df-messenger
|
4 |
+
location="us-central1"
|
5 |
+
project-id="busbooking-451909"
|
6 |
+
agent-id="76716506-e80a-413a-931b-6b61ef715d31"
|
7 |
+
language-code="vi"
|
8 |
+
max-query-length="-1">
|
9 |
+
<df-messenger-chat-bubble
|
10 |
+
chat-title="Bus Booking">
|
11 |
+
</df-messenger-chat-bubble>
|
12 |
+
</df-messenger>
|
13 |
+
<style>
|
14 |
+
df-messenger {
|
15 |
+
z-index: 999;
|
16 |
+
position: fixed;
|
17 |
+
--df-messenger-font-color: #000;
|
18 |
+
--df-messenger-font-family: Google Sans;
|
19 |
+
--df-messenger-chat-background: #f3f6fc;
|
20 |
+
--df-messenger-message-user-background: #d3e3fd;
|
21 |
+
--df-messenger-message-bot-background: #fff;
|
22 |
+
bottom: 16px;
|
23 |
+
right: 16px;
|
24 |
+
}
|
25 |
+
</style>
|
app/types/Respone.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi.responses import JSONResponse
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from typing import List, Dict, Any, Optional
|
4 |
+
|
5 |
+
class MessageText(BaseModel):
|
6 |
+
text: List[str]
|
7 |
+
|
8 |
+
class Message(BaseModel):
|
9 |
+
text: MessageText = None
|
10 |
+
payload: Optional[Dict[str, Any]] = None # Thêm trường payload tùy chọn
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
class FulfillmentResponse(BaseModel):
|
15 |
+
messages: List[Message]
|
16 |
+
|
17 |
+
class DialogflowResponse(BaseModel):
|
18 |
+
fulfillment_response: FulfillmentResponse
|
19 |
+
|
20 |
+
def DialogFlowResponseAPI(text: List[str], payload: Optional[Dict[str, Any]] = None):
|
21 |
+
"""
|
22 |
+
Hàm tạo JSON response cho Dialogflow CX, hỗ trợ payload tùy chỉnh.
|
23 |
+
"""
|
24 |
+
|
25 |
+
messages = []
|
26 |
+
messages.append(Message(text=MessageText(text=text)))
|
27 |
+
|
28 |
+
if payload:
|
29 |
+
messages.append(Message(payload=payload))
|
30 |
+
|
31 |
+
response_data = DialogflowResponse(
|
32 |
+
fulfillment_response=FulfillmentResponse(messages=messages)
|
33 |
+
)
|
34 |
+
|
35 |
+
return JSONResponse(content=response_data.model_dump())
|
app/types/__pycache__/Respone.cpython-39.pyc
ADDED
Binary file (1.6 kB). View file
|
|
app/utils/__pycache__/constants.cpython-39.pyc
ADDED
Binary file (320 Bytes). View file
|
|
app/utils/code_province.json
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"Hà Nội": "HANOI",
|
3 |
+
"Hà Giang": "HAGIANG",
|
4 |
+
"Cao Bằng": "CAOBANG",
|
5 |
+
"Bắc Kạn": "BACKAN",
|
6 |
+
"Tuyên Quang": "TUYENQUANG",
|
7 |
+
"Lào Cai": "LAOCAI",
|
8 |
+
"Điện Biên": "DIENBIEN",
|
9 |
+
"Lai Châu": "LAICHAU",
|
10 |
+
"Sơn La": "SONLA",
|
11 |
+
"Yên Bái": "YENBAI",
|
12 |
+
"Hoà Bình": "HOABINH",
|
13 |
+
"Thái Nguyên": "THAINGUYEN",
|
14 |
+
"Lạng Sơn": "LANGSON",
|
15 |
+
"Quảng Ninh": "QUANGNINH",
|
16 |
+
"Bắc Giang": "BACGIANG",
|
17 |
+
"Phú Thọ": "PHUTHO",
|
18 |
+
"Vĩnh Phúc": "VINHPHUC",
|
19 |
+
"Bắc Ninh": "BACNINH",
|
20 |
+
"Hải Dương": "HAIDUONG",
|
21 |
+
"Hải Phòng": "HAIPHONG",
|
22 |
+
"Hưng Yên": "HUNGYEN",
|
23 |
+
"Thái Bình": "THAIBINH",
|
24 |
+
"Hà Nam": "HANAM",
|
25 |
+
"Nam Định": "NAMDINH",
|
26 |
+
"Ninh Bình": "NINHBINH",
|
27 |
+
"Thanh Hóa": "THANHHOA",
|
28 |
+
"Nghệ An": "NGHEAN",
|
29 |
+
"Hà Tĩnh": "HATINH",
|
30 |
+
"Quảng Bình": "QUANGBINH",
|
31 |
+
"Quảng Trị": "QUANGTRI",
|
32 |
+
"Huế": "HUE",
|
33 |
+
"Đà Nẵng": "DANANG",
|
34 |
+
"Quảng Nam": "QUANGNAM",
|
35 |
+
"Quảng Ngãi": "QUANGNGAI",
|
36 |
+
"Bình Định": "BINHDINH",
|
37 |
+
"Phú Yên": "PHUYEN",
|
38 |
+
"Khánh Hòa": "KHANHHOA",
|
39 |
+
"Ninh Thuận": "NINHTHUAN",
|
40 |
+
"Bình Thuận": "BINHTHUAN",
|
41 |
+
"Kon Tum": "KONTUM",
|
42 |
+
"Gia Lai": "GIALAI",
|
43 |
+
"Đắk Lắk": "DAKLAK",
|
44 |
+
"Đắk Nông": "DAKNONG",
|
45 |
+
"Đà Lạt": "DALAT",
|
46 |
+
"Thành phố Đà Lạt": "DALAT",
|
47 |
+
"Lâm Đồng": "LAMDONG",
|
48 |
+
"Bình Phước": "BINHPHUOC",
|
49 |
+
"Tây Ninh": "TAYNINH",
|
50 |
+
"Bình Dương": "BINHDUONG",
|
51 |
+
"Đồng Nai": "DONGNAI",
|
52 |
+
"Bà Rịa - Vũng Tàu": "VUNGTAU",
|
53 |
+
"Hồ Chí Minh": "TPHCM",
|
54 |
+
"Thành phố Hồ Chí Minh": "TPHCM",
|
55 |
+
"Long An": "LONGAN",
|
56 |
+
"Tiền Giang": "TIENGIANG",
|
57 |
+
"Bến Tre": "BENTRE",
|
58 |
+
"Trà Vinh": "TRAVINH",
|
59 |
+
"Vĩnh Long": "VINHLONG",
|
60 |
+
"Đồng Tháp": "DONGTHAP",
|
61 |
+
"An Giang": "ANGIANG",
|
62 |
+
"Kiên Giang": "KIENGIANG",
|
63 |
+
"Cần Thơ": "CANTHO",
|
64 |
+
"Hậu Giang": "HAUGIANG",
|
65 |
+
"Sóc Trăng": "SOCTRANG",
|
66 |
+
"Bạc Liêu": "BACLIEU",
|
67 |
+
"Cà Mau": "CAMAU"
|
68 |
+
}
|
app/utils/constants.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
|
3 |
+
# Đọc dữ liệu từ file JSON
|
4 |
+
with open("app/utils/code_province.json", "r", encoding="utf-8") as file:
|
5 |
+
code_province = json.load(file)
|
main.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from app.api.routes import router
|
3 |
+
|
4 |
+
app = FastAPI(title="FastAPI Proxy Service")
|
5 |
+
|
6 |
+
app.include_router(router, prefix="/api")
|
7 |
+
|
8 |
+
if __name__ == "__main__":
|
9 |
+
import uvicorn
|
10 |
+
uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
|
requirements.txt
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
annotated-types==0.7.0
|
2 |
+
anyio==4.8.0
|
3 |
+
certifi==2025.1.31
|
4 |
+
click==8.1.8
|
5 |
+
colorama==0.4.6
|
6 |
+
exceptiongroup==1.2.2
|
7 |
+
fastapi==0.115.11
|
8 |
+
h11==0.14.0
|
9 |
+
httpcore==1.0.7
|
10 |
+
httptools==0.6.4
|
11 |
+
httpx==0.28.1
|
12 |
+
idna==3.10
|
13 |
+
Jinja2==3.1.6
|
14 |
+
MarkupSafe==3.0.2
|
15 |
+
pydantic==2.10.6
|
16 |
+
pydantic_core==2.27.2
|
17 |
+
python-dotenv==1.0.1
|
18 |
+
PyYAML==6.0.2
|
19 |
+
sniffio==1.3.1
|
20 |
+
starlette==0.46.0
|
21 |
+
typing_extensions==4.12.2
|
22 |
+
uvicorn==0.34.0
|
23 |
+
watchfiles==1.0.4
|
24 |
+
websockets==15.0.1
|