kltn20133118 commited on
Commit
63d1495
·
verified ·
1 Parent(s): 014e418

Upload 186 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env +23 -0
  2. .gitattributes +3 -0
  3. Dockerfile +24 -0
  4. auth/__pycache__/authentication.cpython-310.pyc +0 -0
  5. auth/__pycache__/authentication.cpython-311.pyc +0 -0
  6. auth/authentication.py +134 -0
  7. cert.pem +31 -0
  8. certificate/firebae_certificate.json +14 -0
  9. controller/ChatController.py +36 -0
  10. controller/DefaultController.py +62 -0
  11. controller/FileController.py +64 -0
  12. controller/LoginController.py +144 -0
  13. controller/MySQLController.py +70 -0
  14. controller/OTPController.py +37 -0
  15. controller/__pycache__/ChatController.cpython-310.pyc +0 -0
  16. controller/__pycache__/ChatController.cpython-311.pyc +0 -0
  17. controller/__pycache__/ChatController.py +35 -0
  18. controller/__pycache__/DefaultController.cpython-310.pyc +0 -0
  19. controller/__pycache__/DefaultController.cpython-311.pyc +0 -0
  20. controller/__pycache__/FileController.cpython-310.pyc +0 -0
  21. controller/__pycache__/FileController.cpython-311.pyc +0 -0
  22. controller/__pycache__/LoginController.cpython-310.pyc +0 -0
  23. controller/__pycache__/LoginController.cpython-311.pyc +0 -0
  24. controller/__pycache__/MySQLController.cpython-310.pyc +0 -0
  25. controller/__pycache__/MySQLController.cpython-311.pyc +0 -0
  26. controller/__pycache__/OTPController.cpython-310.pyc +0 -0
  27. controller/__pycache__/OTPController.cpython-311.pyc +0 -0
  28. entity/Database_Entity.py +68 -0
  29. entity/__pycache__/Database_Entity.cpython-310.pyc +0 -0
  30. entity/__pycache__/Database_Entity.cpython-311.pyc +0 -0
  31. entity/__pycache__/__init__.cpython-310.pyc +0 -0
  32. firebase_certificate.json +14 -0
  33. function/__pycache__/chatbot.cpython-310.pyc +0 -0
  34. function/__pycache__/chatbot.cpython-311.pyc +0 -0
  35. function/__pycache__/dropbox.cpython-310.pyc +0 -0
  36. function/__pycache__/dropbox.cpython-311.pyc +0 -0
  37. function/__pycache__/support_function.cpython-310.pyc +0 -0
  38. function/__pycache__/support_function.cpython-311.pyc +0 -0
  39. function/chatbot.py +680 -0
  40. function/dropbox.py +155 -0
  41. function/support_function.py +129 -0
  42. main.py +336 -0
  43. repository/ChatHistoryRepository.py +231 -0
  44. repository/ConfigDatabase.py +42 -0
  45. repository/DetailChatRepository.py +113 -0
  46. repository/OTPRepository.py +78 -0
  47. repository/UserInfoRepository.py +130 -0
  48. repository/UserLoginRepository.py +132 -0
  49. repository/UserRepository.py +319 -0
  50. repository/__pycache__/ChatHistoryRepository.cpython-310.pyc +0 -0
.env ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NGROK_STATIC_DOMAIN=rightly-poetic-amoeba.ngrok-free.app
2
+ NGROK_TOKEN=2fEEmIGqKqV2EoE6n5lBRgObtov_4KmEfqwPJLdMi2G7GKnXU
3
+ GROQ_API_KEY=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
4
+ COHERE_API_KEY=6H7ZPI4aDoGFcELYJ0KLdVYTqcbzN4wvvUcIBSLl
5
+ GOOGLE_API_KEY_1=AIzaSyB3j7vAOJBL4MnWPk8VJJM1Yg33YTZEBv0
6
+ GOOGLE_API_KEY=AIzaSyBfb8OiYQJCSnhV6aWdQlY6cSvDd_lmGhc
7
+ OPENAI_API_KEY=sk-proj-1hrUAZ8bf6x96BsYWNgqT3BlbkFJDAbZNrsgXxz2NCpYczLf
8
+ COHERE_API_KEY_1=TzXaHQJrHVzd7HaWjEm42y7996XqR73WpGMzXvZR
9
+ COHERE_API_KEY_2=RWIrMiF184xBmOAAvodxCxExefwEAYSn7yEOmbk1
10
+ CLIENT_ID=717779638552-1255g855qidok44bpev8glpp5q10bs5u.apps.googleusercontent.com
11
+ API_SIGN_UP_FIREBASE=AIzaSyDk579sNTudOnmAEHq4iOfTNIfqVzjFXYw
12
+ DROPBOX_APP_KEY=m79mo7gg7mh8pez
13
+ DROPBOX_APP_SECRET=by93yed7as4qlmo
14
+ DROPBOX_REFRESH_TOKEN=VG4SP0Ugo4EAAAAAAAAAAbHf7esmak_gieNGvLHxiiAXGfSeKPVXbX1lm28DMz_o
15
+ MYSQL_USER_NAME=root
16
+ MYSQL_PASSWOR=Yahana0509@
17
+ MYSQL_PORT=4000
18
+ MYSQL_DATABASE=pychatbot
19
+ MYSQL_HOST=localhost
20
+ #IF USE DOCKER MYSQL_HOST = host.docker.internal
21
+ CLOUDINARY_CLOUD_NAME=dgxozfb1f
22
+ CLOUDINARY_API_KEY=934177576436386
23
+ CLOUDINARY_API_SECRET=OdCUlhWxMUWG_nhexadAN-R6jEs
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tests/test_controller/user_file/quangphuc@gmail.com/demo1.pdf filter=lfs diff=lfs merge=lfs -text
37
+ tests/test_service/user_file/quangphuc@gmail.com/demo1.pdf filter=lfs diff=lfs merge=lfs -text
38
+ tests/user_file/quangphuc@gmail.com/demo1.pdf filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11
2
+
3
+ WORKDIR /code
4
+ WORKDIR /code/temp
5
+ WORKDIR /nltk_data
6
+
7
+ RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
8
+ RUN mkdir -p /code
9
+ RUN mkdir -p /code/temp
10
+ RUN mkdir -p /nltk_data
11
+
12
+ USER root
13
+
14
+ RUN chmod -R 777 /nltk_data
15
+ RUN chmod -R 777 /code
16
+ RUN chmod -R 777 /code/temp
17
+
18
+ COPY ./requirements.txt /code/requirements.txt
19
+ COPY ./firebase_certificate.json /code/firebase_certificate.json
20
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
21
+
22
+ COPY . .
23
+
24
+
auth/__pycache__/authentication.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
auth/__pycache__/authentication.cpython-311.pyc ADDED
Binary file (8.37 kB). View file
 
auth/authentication.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from typing import Dict
3
+ import jwt
4
+ import secrets
5
+ import logging
6
+ from fastapi import Depends, HTTPException
7
+ import base64
8
+ from datetime import datetime, timedelta
9
+ from repository import UserRepository, UserLoginRepository
10
+ import string, random
11
+
12
+ def check_token_is_valid(token):
13
+ check = UserRepository.getEmailUserByAccessToken(token)
14
+ if check is None:
15
+ return False
16
+ return True
17
+
18
+ def unique_string(byte: int = 8) -> str:
19
+ return secrets.token_urlsafe(byte)
20
+ JWT_SECRET = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
21
+ JWT_ALGORITHM = "HS512"
22
+ SECRET_KEY="8deadce9449770680910741063cd0a3fe0acb62a8978661f421bbcbb66dc41f1"
23
+
24
+ def token_response(token: str):
25
+ return {
26
+ "access_token": token
27
+ }
28
+ def str_encode(string: str) -> str:
29
+ return base64.b85encode(string.encode('ascii')).decode('ascii')
30
+
31
+ def get_token_payload(token: str, secret: str, algo: str):
32
+ try:
33
+ payload = jwt.decode(token, secret, algorithms=algo)
34
+ except Exception as jwt_exec:
35
+ logging.debug(f"JWT Error: {str(jwt_exec)}")
36
+ payload = None
37
+ return payload
38
+
39
+ from datetime import datetime
40
+ def generate_token(payload: dict, secret: str, algo: str, expiry: timedelta):
41
+ expire = datetime.now() + expiry
42
+ payload.update({"exp": expire})
43
+ return jwt.encode(payload, secret, algorithm=algo)
44
+
45
+ def str_decode(string: str) -> str:
46
+ return base64.b85decode(string.encode('ascii')).decode('ascii')
47
+
48
+ def generate_random_string(length=12):
49
+ characters = string.ascii_letters + string.digits
50
+ random_string = ''.join(random.choice(characters) for i in range(length))
51
+ return random_string
52
+
53
+ import pytz
54
+ from datetime import datetime
55
+ def signJWT(user_email: str) -> Dict[str, str]:
56
+ rt_expires = timedelta(days=7)
57
+ refresh_key = unique_string(100)
58
+ access_key = unique_string(50)
59
+ at_expires = timedelta(minutes=180)
60
+ at_payload = {
61
+ "sub": str_encode(str(user_email)),
62
+ 'a': access_key,
63
+ }
64
+ access_token = generate_token(at_payload, JWT_SECRET, JWT_ALGORITHM, at_expires)
65
+ rt_payload = {"sub": str_encode(str(user_email)), "t": refresh_key, 'a': access_key}
66
+ refresh_token = generate_token(rt_payload, SECRET_KEY,JWT_ALGORITHM, rt_expires)
67
+ expires_in = at_expires.seconds
68
+ vn_timezone = pytz.timezone('Asia/Ho_Chi_Minh')
69
+ current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(vn_timezone) + timedelta(seconds=expires_in)
70
+ formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S ')
71
+ existing_user = UserRepository.getUserByEmail(user_email)
72
+ if existing_user is None:
73
+ UserRepository.addUser(user_email, access_token, refresh_token, formatted_time)
74
+ else:
75
+ UserRepository.updateUserLogin(user_email, access_token, refresh_token, formatted_time)
76
+ user_record = UserRepository.getUserByEmail(user_email)
77
+ session_id = ""
78
+ if user_record:
79
+ session_id = generate_random_string()
80
+ existing_userlogin = UserLoginRepository.getUserLogin(user_email)
81
+ if existing_userlogin is None:
82
+ UserLoginRepository.addUserLogin(user_email,session_id=session_id)
83
+ else:
84
+ UserLoginRepository.updateUserLogin(user_email, session_id)
85
+ return {
86
+ "access_token": access_token,
87
+ "refresh_token": refresh_token,
88
+ "expires_in": at_expires.seconds,
89
+ "session_id": session_id
90
+ }
91
+
92
+ def returnAccessToken(user_email: str, refresh_token: str) -> Dict[str, str]:
93
+ access_key = unique_string(50)
94
+ at_expires = timedelta(minutes=180)
95
+ at_payload = {
96
+ "sub": str_encode(str(user_email)),
97
+ 'a': access_key,
98
+ }
99
+ access_token = generate_token(at_payload, JWT_SECRET, JWT_ALGORITHM, at_expires)
100
+ user_record = UserRepository.getUserByEmail(user_email)
101
+ session_id = ""
102
+ if user_record:
103
+ email1 = user_record.email
104
+ if email1:
105
+ session_id = generate_random_string()
106
+ existing_userlogin = UserLoginRepository.getUserLogin(user_email)
107
+ if existing_userlogin is None:
108
+ UserLoginRepository.addUserLogin(user_email,session_id=session_id)
109
+ else:
110
+ user_id = UserRepository.getUserIdByEmail(user_email)
111
+ UserLoginRepository.updateUserLogin(user_id,user_email,session_id)
112
+ return {
113
+ "access_token": access_token,
114
+ "refresh_token": refresh_token,
115
+ "expires_in": at_expires.seconds,
116
+ "session_id": session_id
117
+ }
118
+
119
+ def decodeJWT(token: str) -> dict:
120
+ try:
121
+ decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
122
+ return decoded_token if decoded_token["exp"] >= time.time() else None
123
+ except:
124
+ return {}
125
+
126
+ def get_refresh_token(refresh_token,token_now, email):
127
+ token_payload = get_token_payload(refresh_token, SECRET_KEY, JWT_ALGORITHM)
128
+ if not token_payload:
129
+ raise HTTPException(status_code=400, detail="Invalid Request.")
130
+ exp = token_payload.get('exp')
131
+ if exp >= time.time() and token_payload:
132
+ return returnAccessToken(email,refresh_token)
133
+ elif not token_payload:
134
+ return signJWT(email)
cert.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
3
+ TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
4
+ cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
5
+ WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
6
+ ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
7
+ MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
8
+ h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
9
+ 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
10
+ A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
11
+ T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
12
+ B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
13
+ B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
14
+ KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
15
+ OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
16
+ jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
17
+ qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
18
+ rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
19
+ HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
20
+ hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
21
+ ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
22
+ 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
23
+ NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
24
+ ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
25
+ TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
26
+ jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
27
+ oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
28
+ 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
29
+ mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
30
+ emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
31
+ -----END CERTIFICATE-----
certificate/firebae_certificate.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "cogent-octane-384105",
4
+ "private_key_id": "94d2eb71fcc53c8504e822a2367157b49b65b16d",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+awYE99nwJwid\neFuujKYL1cxdknb5lze6ON2wwn6F/lZCjf0wyYTyYAzk2yVDy8p+xy+jsbT22iaX\n8K6fwCqMVUMby9e813cQuS7ycF7WSS1Fw9JwljktnMLplJZuTv3zmlolNiePz/rS\nPcPaSvjQWO4s/G1A8knbY2gXaY4e7ie37GGKDOsgfEF8sQJ2TRll79qzoAWqIz1I\np87s+vR+Z3nPlVqiCM7cYP9ddvFEQxF381STDIExQzKSYbQyUsnU1lOZ7zWKb4F+\nHGjLzYBhf6CzU+l3M/kiaTJck+T7H/tSWo+bzFYFRpeh6Q7/UBwbBYN+7VOXTJ1Q\nEBQdwolBAgMBAAECggEAGG8v+405GG751Qhvw1XlrMPHkK5NuWNlJu6gdqEj49p/\ng9TSi43LEzWuEePpGT+vrABapZ0VGqQNqxZFt4F3iZXF9xgmMTj43LAr97eMWTT/\nVozKlotAVRELleDs7hoRePlH3gSKo71Ncz2ybHLjELaIrER2rzcoBmXwIn5MsBJ+\nDOqdZAo3UadvzcRpTUY6ju1Kd8w72FYgW/3RfK6eikZEw8sX8vKQ7QEH8bKeZVt7\nWOrkBK2kHEyR8dTga2igQRI7Cezqv48yiYjYbi+D/DBocjpHtJnPLbgOOWyjbmDU\n5fB+bxf+7qXZn/AIp96Iq1s2ZHxldlKk38yne40N7QKBgQDf/+A2lQswySNdLR1+\nNJME3OGgBG9Jq0mnBoe9rWOBBBAQNYv4uZO4MVvmLwzIN1y32MV6zkbnD9fMWKIf\nciIzje8xip/9ei6weB5n0Yp13f9JxBW0r1HaUVk7jpHyH7rk3GvNcebZNKM+yndh\n1rdyE1V6xGNqAXzX9vP4t6IiYwKBgQDZnwEwggMToQrl1jsxz7VlujPNSUhOgwGL\nj0nHCbUf2/jZ1hyMRU659RWmWGA70rsALwQ4IQoM5UHZkKc12MjswmXllrkk1Jmu\nc04OE5SWde7SWAzSj5oqCIoQt0B/3r7cRjgr0TK3SwxxIUOcazyFzvLrxJxsGFHc\nOfE3jP5lCwKBgCf0kl/qEgbvudki9QHQCvFxHOXYJKm1XfvnFEtnJDqdKOhbRM5m\n+8x9MXFLrzH/fhBlIESZitgoYUvX+4M0bplXlfT2Tzd9ldpwcqv+Gn6PzLuxuFV0\neFtC63HOKoZP1pyAHNKWoKDZ3MyUfNr829gDTtoJMdp0zXoQWNBioQ8VAoGBAKvd\n5aSXqTJhZyfpL0rBjbNPgQXJsG9BC4Faopus0PzeTwRLErS9L9Ww924uMaJNZR5a\nA20IutVAYecfVM8z7Er/pFXT2Vh7Bvw9WBHJ6PmDHh/FJitM+iXkJJXbA/d4xSdV\n1ZrVVsZnYOYfrTPlhSDwNe15k0fTVSMmJ5kFowvNAoGAc101K46kuKl+K/V6gdnW\nN2reMwlJf4Wgaz7yX0Gkha95dNGmy1ZC+NdD3qlSbOv353OITzNCBo7pSAAphQr2\noVkpyToTQOcSBjjAzTkXHabn3N1Rmj1P7GPwz5WyDPjp4t+GmT8Se3aJ1gtCnKeb\noxwTPi7EHyoIiYnEXYRuzSw=\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "firebase-adminsdk-z0bu3@cogent-octane-384105.iam.gserviceaccount.com",
7
+ "client_id": "105944722897200826755",
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/firebase-adminsdk-z0bu3%40cogent-octane-384105.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
14
+
controller/ChatController.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Form, Request
2
+ from service import ChatService
3
+ from request import RequestChat
4
+ from typing import Optional
5
+ from fastapi.requests import Request
6
+ from function import support_function
7
+ from response import ResponseChat as res
8
+ router = APIRouter()
9
+
10
+ @router.post("/chatbot/query/", tags=["Chat"])
11
+ async def handle_query2_upgrade_old(request: Request,
12
+ user_id: str = Form(None),
13
+ text_all: str = Form(...),
14
+ question: Optional[str] = Form(None),
15
+ chat_name: Optional[str] = Form(None)):
16
+ check = support_function.check_value_user_id_controller(user_id)
17
+ if check is not True:
18
+ return check
19
+ request = RequestChat.RequestQuery2UpgradeOld(user_id=user_id, text_all=text_all, question=question, chat_name=chat_name)
20
+ return ChatService.query2_upgrade_old(request)
21
+
22
+ @router.get("/chatbot/extract_file/", tags=["Chat"])
23
+ async def extract_file(user_id: str):
24
+ check = support_function.check_value_user_id_controller(user_id)
25
+ if check is not True:
26
+ return check
27
+ request = RequestChat.RequestExtractFile(user_id=user_id)
28
+ return ChatService.extract_file(request)
29
+
30
+ @router.get("/chatbot/generate_question/",tags=["Chat"])
31
+ async def generate_question(user_id: str):
32
+ check = support_function.check_value_user_id_controller(user_id)
33
+ if check is not True:
34
+ return check
35
+ request = RequestChat.RequestGenerateQuestion(user_id=user_id)
36
+ return ChatService.generate_question(request)
controller/DefaultController.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import HTTPException, Depends, Query,APIRouter
2
+ from service import DefaultService
3
+ from request import RequestDefault
4
+ from request import RequestDefault as req
5
+ from function import support_function
6
+ from auth.authentication import decodeJWT
7
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
8
+ from fastapi.responses import JSONResponse
9
+ from auth import authentication
10
+ from fastapi.requests import Request
11
+ from response import ResponseDefault as res
12
+ from fastapi import File, UploadFile, Form
13
+ router = APIRouter()
14
+
15
+ @router.get("/is_me/", tags=["Default"])
16
+ async def is_me(token: str = Query(...)):
17
+ if token.strip() == "" or token is None:
18
+ return res.ReponseError(status=400,
19
+ data=res.Message(message="Token field is required."))
20
+ if token.lower() == "none":
21
+ return res.ReponseError(status=400,
22
+ data=res.Message(message="Token cannot be None."))
23
+ if not isinstance(token, str):
24
+ return res.ReponseError(status=400,
25
+ data=res.Message(message="Token must be a non-empty string."))
26
+ try:
27
+ float(token)
28
+ return res.ReponseError(status=400,
29
+ data=res.Message(message="Token must be a string, not a number."))
30
+ except ValueError:
31
+ pass
32
+ request = RequestDefault.RequestIsMe(token=token)
33
+ return DefaultService.is_me(request)
34
+
35
+ @router.post('/create_firebase_user_google', tags=["Default"])
36
+ async def get_or_create_firebase_user(request: RequestDefault.RequestCreateFireBaseUserGoogle):
37
+ email = request.email
38
+ check = support_function.check_value_email_controller(request.email)
39
+ if check is not True:
40
+ return check
41
+ return DefaultService.create_firebase_user(request)
42
+
43
+ @router.get("/info_user", tags=["Default"])
44
+ async def get_user(user_id: str = Query(None)):
45
+ check = support_function.check_value_user_id_controller(user_id)
46
+ if check is not True:
47
+ return check
48
+ request = RequestDefault.RequestInfoUser(user_id=user_id)
49
+ return DefaultService.info_user(request)
50
+
51
+ ALLOWED_IMAGE_EXTENSIONS = {"jpeg", "jpg", "png"}
52
+
53
+ def allowed_file(filename: str) -> bool:
54
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_IMAGE_EXTENSIONS
55
+
56
+ @router.post("/upload_image/", tags=["Default"])
57
+ async def upload_image(user_id: str = Form(None), file: UploadFile = File(...)):
58
+ check = support_function.check_value_user_id_controller(user_id)
59
+ if check is not True:
60
+ return check
61
+ request = req.RequestUpLoadImage(user_id=user_id, files= file)
62
+ return DefaultService.upload_image_service(request)
controller/FileController.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Form, File, UploadFile,Query
2
+ from typing import List,Optional
3
+ from service import FileService
4
+ from function import support_function
5
+ from fastapi import HTTPException
6
+ from response import ResponseFile as res
7
+ from request import RequestFile
8
+ router = APIRouter()
9
+
10
+ ALLOWED_EXTENSIONS = {'csv', 'txt', 'doc', 'docx', 'pdf', 'xlsx', 'pptx', 'json', 'html'}
11
+ def allowed_file(filename):
12
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
13
+
14
+ @router.delete("/delete_all_file/", tags=["File"])
15
+ async def delete_folder(request: RequestFile.RequestDeleteAllFile):
16
+ check = support_function.check_value_user_id_controller(request.user_id)
17
+ if check is not True:
18
+ return check
19
+ # request = RequestFile.RequestDeleteAllFile(user_id=user_id)
20
+ return FileService.deleteAllFile(request)
21
+
22
+ @router.get("/list_name_files/", tags=["File"])
23
+ async def get_name(user_id: str):
24
+ check = support_function.check_value_user_id_controller(user_id)
25
+ if check is not True:
26
+ return check
27
+ request = RequestFile.RequestGetNameFile(user_id=user_id)
28
+ return FileService.listNameFiles(request)
29
+
30
+ @router.delete("/delete_one_file/", tags=["File"])
31
+ async def delete_one_file(request: RequestFile.RequestDeleteFile):
32
+ user_id = request.user_id
33
+ check = support_function.check_value_user_id_controller(user_id)
34
+ if check is not True:
35
+ return check
36
+ name_file = request.name_file
37
+ if name_file is None or name_file.strip() == "":
38
+ return res.ReponseError(status=400,
39
+ data=res.Message(message="Name file is required."))
40
+ return FileService.deleteFile(request)
41
+
42
+ @router.post("/chatbot/download_folder/", tags=["File"])
43
+ async def download_folder_from_dropbox(request: RequestFile.RequestDownLoadFolder):
44
+ user_id = request.user_id
45
+ check = support_function.check_value_user_id_controller(user_id)
46
+ if check is not True:
47
+ return check
48
+ return FileService.download_folder(request)
49
+
50
+ @router.post("/chatbot/download_files/", tags=["File"])
51
+ async def download_file_by_id(request: RequestFile.RequestDownLoadFile):
52
+ user_id = request.user_id
53
+ check = support_function.check_value_user_id_controller(user_id)
54
+ if check is not True:
55
+ return check
56
+ return FileService.download_file(request)
57
+
58
+ @router.post("/upload_files/", tags=["File"])
59
+ async def upload_files_dropbox(user_id: str = Form(None), files: Optional[List[UploadFile]] = File(None)):
60
+ check = support_function.check_value_user_id_controller(user_id)
61
+ if check is not True:
62
+ return check
63
+ request = RequestFile.RequestUploadFile(files=files, user_id=user_id)
64
+ return FileService.upload_files(request)
controller/LoginController.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Query
2
+ from request import RequestLogin
3
+ from response import ResponseLogin as res
4
+ from service import LoginService
5
+ from function import support_function
6
+ from fastapi import HTTPException
7
+ from response import ResponseLogin as res
8
+ router = APIRouter()
9
+
10
+ @router.post('/login', tags=["Login"])
11
+ async def login(request: RequestLogin.RequestLoginEmail):
12
+ email = request.email
13
+ check = support_function.check_value_email_controller(email)
14
+ if check is not True:
15
+ return check
16
+ password = request.password
17
+ if password is None or password.strip() == "":
18
+ return res.ReponseError(status=400,
19
+ data=res.Message(message="Password is required."))
20
+ return LoginService.login(request)
21
+
22
+ @router.post('/login_google', tags=["Login"])
23
+ async def login_google(request: RequestLogin.RequestLoginGoogle):
24
+ email = request.email
25
+ token_google = request.token_google
26
+ check = support_function.check_value_email_controller(email)
27
+ if check is not True:
28
+ return check
29
+ if token_google is None or token_google.strip() == "":
30
+ return res.ReponseError(status=400,
31
+ data=res.Message(message="token_google oauth2 is required."))
32
+ if token_google.isdigit():
33
+ return res.ReponseError(status=400,
34
+ data=res.Message(message="token_google must be a string, not a number."))
35
+ return LoginService.login_google(request)
36
+
37
+ @router.post("/update_user_info", tags=["Login"])
38
+ async def update_user_info(request: RequestLogin.RequestUpdateUserInfo):
39
+ user_id = request.user_id
40
+ check = support_function.check_value_user_id_controller(user_id)
41
+ if check is not True:
42
+ return check
43
+ uid = request.uid
44
+ email = request.email
45
+ display_name = request.display_name
46
+ photo_url = request.photo_url
47
+ if uid is None or uid.strip() == "":
48
+ return res.ReponseError(status=400,
49
+ data=res.Message(message="uid field is required."))
50
+ if email is None or email.strip() == "":
51
+ return res.ReponseError(status=400,
52
+ data=res.Message(message="email field is required."))
53
+ if display_name is None or display_name.strip() == "":
54
+ return res.ReponseError(status=400,
55
+ data=res.Message(message="display_name field is required."))
56
+ if photo_url is None or photo_url.strip() == "":
57
+ return res.ReponseError(status=400,
58
+ data=res.Message(message="photo_url field is required."))
59
+ return LoginService.update_user_info(request)
60
+
61
+ @router.get('/check_info_google', tags=["Login"])
62
+ async def check_info_google(user_id: str = Query(None)):
63
+ check = support_function.check_value_user_id_controller(user_id)
64
+ if check is not True:
65
+ return check
66
+ request = RequestLogin.RequestCheckInfoGoogle(user_id=user_id)
67
+ return LoginService.check_info_google(request)
68
+
69
+ @router.get('/check_info_google_signup', tags=["Login"])
70
+ async def check_info_google_signup(email: str = None):
71
+ check = support_function.check_value_email_controller(email)
72
+ if check is not True:
73
+ return check
74
+ request = RequestLogin.RequestCheckInfoGoogleEmail(email=email)
75
+ return LoginService.check_info_google_email(request)
76
+
77
+ @router.get('/check_state_login', tags=["Login"])
78
+ async def check_state_login(user_id: str = Query(None), session_id_now: str = Query(None)):
79
+ check = support_function.check_value_user_id_controller(user_id)
80
+ if check is not True:
81
+ return check
82
+ if session_id_now is None or session_id_now.strip() == "":
83
+ return res.ReponseError(status=400,
84
+ data=res.Message(message="Session Id is required."))
85
+ try:
86
+ int(session_id_now)
87
+ return res.ReponseError(status=400,
88
+ data=res.Message(message="Session Id must be a string, not a number."))
89
+ except ValueError:
90
+ pass
91
+ request = RequestLogin.RequestCheckStateLogin(user_id=user_id, session_id_now=session_id_now)
92
+ return LoginService.check_state_login(request)
93
+
94
+ @router.post('/sign_up', tags=["Login"])
95
+ async def signup(request: RequestLogin.RequestSignUp):
96
+ email = request.email
97
+ check = support_function.check_value_email_controller(email)
98
+ if check is not True:
99
+ return check
100
+ password = request.password
101
+ if password is None or password.strip( )== "":
102
+ return res.ReponseError(status=400,
103
+ data=res.Message(message="Password is required."))
104
+ return LoginService.sign_up(request)
105
+
106
+ @router.post('/reset_password', tags=["Login"])
107
+ async def reset_password(request: RequestLogin.RequestResetPassword):
108
+ email = request.email
109
+ check = support_function.check_value_email_controller(email)
110
+ if check is not True:
111
+ return check
112
+ return LoginService.reset_password(request)
113
+
114
+ @router.put('/change_password', tags=["Login"])
115
+ async def reset_password_firebase(request: RequestLogin.RequestChangePassword):
116
+ user_id = request.user_id
117
+ check = support_function.check_value_user_id_controller(user_id)
118
+ if check is not True:
119
+ return check
120
+ new_password = request.new_password
121
+ current_password = request.current_password
122
+ if new_password is None or new_password.strip() == "":
123
+ return res.ReponseError(status=400,
124
+ data=res.Message(message="New password field is required."))
125
+ if current_password is None or current_password.strip() == "":
126
+ return res.ReponseError(status=400,
127
+ data=res.Message(message="Current password field is required."))
128
+ return LoginService.change_password(request)
129
+
130
+ @router.post('/refresh_token/', tags=["Login"])
131
+ async def refresh_token_account(request: RequestLogin.RequestRefreshTokenLogin):
132
+ user_id = request.user_id
133
+ check = support_function.check_value_user_id_controller(user_id)
134
+ if check is not True:
135
+ return check
136
+ token = request.token
137
+ if token is None or token.strip() == "":
138
+ return res.ReponseError(status=400,
139
+ data=res.Message(message="token is required."))
140
+ elif token.isdigit():
141
+ return res.ReponseError(status=400,
142
+ data=res.Message(message="token must be string"))
143
+
144
+ return LoginService.refresh_token(request)
controller/MySQLController.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Query, APIRouter
2
+ from service import MySQLService
3
+ from request import RequestMySQL
4
+ from response import ResponseMySQL as res
5
+ from typing import Optional
6
+ from request import RequestMySQL as req
7
+ from function import support_function
8
+ from fastapi import HTTPException
9
+ router = APIRouter()
10
+
11
+ @router.get("/render_chat_history", tags=["MySQL"])
12
+ async def render_chat(user_id: Optional[str] = Query(None)):
13
+ check = support_function.check_value_user_id_controller(user_id)
14
+ if check is not True:
15
+ return check
16
+ request = RequestMySQL.RequestRenderChatHistory(user_id=user_id)
17
+ return MySQLService.render_chat_history(request)
18
+
19
+ @router.get("/data_relevant", tags=["MySQL"])
20
+ async def render_chat_1(chat_detail_id: str):
21
+ if chat_detail_id is None or chat_detail_id.strip() == "":
22
+ return res.ReponseError(status=400,
23
+ data=res.Message(message="Id field is required."))
24
+ chat_detail_id = chat_detail_id.strip("'").strip('"')
25
+ try:
26
+ chat_detail_id_int = int(chat_detail_id)
27
+ except ValueError:
28
+ return res.ReponseError(status=400,
29
+ data=res.Message(message="Value must be an integer"))
30
+ if not support_function.is_positive_integer(chat_detail_id_int):
31
+ return res.ReponseError(status=400,
32
+ data=res.Message(message="Value must be greater than 0"))
33
+ request = req.RequestGetChatDetails(id=chat_detail_id)
34
+ return MySQLService.get_detail_chat_by_chat_id(request)
35
+
36
+ @router.get("/load_chat_history", tags=["MySQL"])
37
+ async def load_chat(chat_id: Optional[str] = Query(None), user_id: Optional[str] = Query(None)):
38
+ check = support_function.check_value_user_id_controller(user_id)
39
+ if check is not True:
40
+ return check
41
+ if chat_id is None or chat_id.strip() == "":
42
+ return res.ReponseError(status=400,
43
+ data=res.Message(message="Chat id field is required."))
44
+ chat_id = chat_id.strip("'").strip('"')
45
+ try:
46
+ chat_id_int = int(chat_id)
47
+ except ValueError:
48
+ return res.ReponseError(status=400,
49
+ data=res.Message(message="Value must be an integer"))
50
+ if not support_function.is_positive_integer(chat_id_int):
51
+ return res.ReponseError(status=400,
52
+ data=res.Message(message="Value must be greater than 0"))
53
+ request = req.RequestLoadChatHistory(chat_id=chat_id,user_id = user_id)
54
+ return MySQLService.load_chat_history(request)
55
+
56
+ @router.put("/edit_chat/", tags=["MySQL"])
57
+ async def edit_chat(request: RequestMySQL.RequestEditNameChat):
58
+ user_id = request.user_id
59
+ check = support_function.check_value_user_id_controller(user_id)
60
+ if check is not True:
61
+ return check
62
+ return MySQLService.edit_chat(request)
63
+
64
+ @router.delete("/delete_chat/", tags=["MySQL"])
65
+ async def delete_chat(request: RequestMySQL.RequestDeleteChat):
66
+ user_id = request.user_id
67
+ check = support_function.check_value_user_id_controller(user_id)
68
+ if check is not True:
69
+ return check
70
+ return MySQLService.delete_chat(request)
controller/OTPController.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from function import support_function
3
+ from request import RequestOTP
4
+ from service import OTPService
5
+ from fastapi import HTTPException
6
+ from pydantic.error_wrappers import ErrorWrapper
7
+ from pydantic import BaseModel
8
+ from response import ResponseOTP as res
9
+ router = APIRouter()
10
+
11
+ @router.post('/create_otp', tags=["OTP"])
12
+ async def create_otp(request: RequestOTP.RequestCreateOTP):
13
+ email = request.email
14
+ check = support_function.check_value_email_controller(email)
15
+ if check is not True:
16
+ return check
17
+ return OTPService.createOTP(request)
18
+
19
+ @router.post('/verify_otp', tags=["OTP"])
20
+ async def verify_otp(request: RequestOTP.RequestVerifyOTP):
21
+ check = support_function.check_value_email_controller(request.email)
22
+ if check is not True:
23
+ return check
24
+ check_otp = support_function.check_value_otp(request.otp)
25
+ if check_otp is not True:
26
+ return check_otp
27
+ return OTPService.verifyOTP(request)
28
+
29
+ @router.post('/verify_otp_reset_password', tags=["OTP"])
30
+ async def verify_otp_reset(request: RequestOTP.RequestVerifyOTP):
31
+ check = support_function.check_value_email_controller(request.email)
32
+ if check is not True:
33
+ return check
34
+ check_otp = support_function.check_value_otp(request.otp)
35
+ if check_otp is not True:
36
+ return check_otp
37
+ return OTPService.verifyOTPReset(request)
controller/__pycache__/ChatController.cpython-310.pyc ADDED
Binary file (1.5 kB). View file
 
controller/__pycache__/ChatController.cpython-311.pyc ADDED
Binary file (2.63 kB). View file
 
controller/__pycache__/ChatController.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Form, Request
2
+ from service import ChatService
3
+ from request import RequestChat
4
+ from typing import Optional
5
+ from fastapi.requests import Request
6
+ from function import support_function
7
+ from response import ResponseChat as res
8
+ router = APIRouter()
9
+
10
+ @router.post("/chatbot/query/", tags=["Chat"])
11
+ async def handle_query2_upgrade_old(request: Request,
12
+ user_id: str = Form(None),
13
+ text_all: str = Form(...), question: Optional[str] = Form(None),
14
+ chat_name: Optional[str] = Form(None)):
15
+ check = support_function.check_value_user_id_controller(user_id)
16
+ if check is not True:
17
+ return check
18
+ request = RequestChat.RequestQuery2UpgradeOld(user_id=user_id, text_all=text_all, question=question, chat_name=chat_name)
19
+ return ChatService.query2_upgrade_old(request)
20
+
21
+ @router.get("/chatbot/extract_file/", tags=["Chat"])
22
+ async def extract_file(user_id: str):
23
+ check = support_function.check_value_user_id_controller(user_id)
24
+ if check is not True:
25
+ return check
26
+ request = RequestChat.RequestExtractFile(user_id=user_id)
27
+ return ChatService.extract_file(request)
28
+
29
+ @router.get("/chatbot/generate_question/",tags=["Chat"])
30
+ async def generate_question(user_id: str):
31
+ check = support_function.check_value_user_id_controller(user_id)
32
+ if check is not True:
33
+ return check
34
+ request = RequestChat.RequestGenerateQuestion(user_id=user_id)
35
+ return ChatService.generate_question(request)
controller/__pycache__/DefaultController.cpython-310.pyc ADDED
Binary file (2.73 kB). View file
 
controller/__pycache__/DefaultController.cpython-311.pyc ADDED
Binary file (4.91 kB). View file
 
controller/__pycache__/FileController.cpython-310.pyc ADDED
Binary file (2.67 kB). View file
 
controller/__pycache__/FileController.cpython-311.pyc ADDED
Binary file (4.8 kB). View file
 
controller/__pycache__/LoginController.cpython-310.pyc ADDED
Binary file (4.75 kB). View file
 
controller/__pycache__/LoginController.cpython-311.pyc ADDED
Binary file (9.92 kB). View file
 
controller/__pycache__/MySQLController.cpython-310.pyc ADDED
Binary file (2.6 kB). View file
 
controller/__pycache__/MySQLController.cpython-311.pyc ADDED
Binary file (5.35 kB). View file
 
controller/__pycache__/OTPController.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
controller/__pycache__/OTPController.cpython-311.pyc ADDED
Binary file (2.4 kB). View file
 
entity/Database_Entity.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import Column, String, Text, DateTime, Integer, ForeignKey, TIMESTAMP
2
+ from sqlalchemy.orm import relationship
3
+ from sqlalchemy.orm import DeclarativeBase
4
+ from sqlalchemy.sql import func
5
+ class Base(DeclarativeBase):
6
+ pass
7
+
8
+ class User(Base):
9
+ __tablename__ = 'users'
10
+ id = Column(Integer, primary_key=True, autoincrement=True)
11
+ email = Column(String(255))
12
+ access_token = Column(Text)
13
+ refresh_token = Column(Text)
14
+ expires_at = Column(DateTime)
15
+
16
+ chat_histories = relationship("ChatHistory", back_populates="user")
17
+ user_logins = relationship("UserLogin", back_populates="user")
18
+ user_infos = relationship("UserInfo", back_populates="user")
19
+
20
+ class ChatHistory(Base):
21
+ __tablename__ = 'chat_history'
22
+
23
+ id = Column(Integer, primary_key=True,autoincrement=True)
24
+ email = Column(String(255), ForeignKey('users.email'))
25
+ name_chat = Column(String(255), unique=True)
26
+
27
+ user = relationship("User", back_populates="chat_histories")
28
+ detail_chats = relationship("DetailChat", back_populates="chat_history")
29
+
30
+ class UserLogin(Base):
31
+ __tablename__ = 'user_login'
32
+
33
+ id = Column(Integer, primary_key=True,autoincrement=True)
34
+ user_email = Column(String(100), ForeignKey('users.email'), primary_key=True)
35
+ user_session_id = Column(String(100), primary_key=True)
36
+
37
+ user = relationship("User", back_populates="user_logins")
38
+
39
+ class UserInfo(Base):
40
+ __tablename__ = 'user_info'
41
+
42
+ id = Column(Integer, primary_key=True, autoincrement=True)
43
+ uid = Column(Text)
44
+ email = Column(String(255), ForeignKey('users.email'), unique=True)
45
+ display_name = Column(Text)
46
+ photo_url = Column(Text)
47
+
48
+ user = relationship("User", back_populates="user_infos")
49
+
50
+ class DetailChat(Base):
51
+ __tablename__ = 'detail_chat'
52
+
53
+ id = Column(Integer, primary_key=True, autoincrement=True)
54
+ chat_id = Column(Integer, ForeignKey('chat_history.id'))
55
+ YouMessage = Column(Text)
56
+ AiMessage = Column(Text)
57
+ data_relevant = Column(Text)
58
+ source_file = Column(Text)
59
+
60
+ chat_history = relationship("ChatHistory", back_populates="detail_chats")
61
+
62
+ class OTP(Base):
63
+ __tablename__ = 'otp'
64
+
65
+ id = Column(Integer, primary_key=True, autoincrement=True)
66
+ email = Column(String(255), nullable=False)
67
+ otp = Column(String(6), nullable=False)
68
+ created_at = Column(TIMESTAMP, server_default=func.now())
entity/__pycache__/Database_Entity.cpython-310.pyc ADDED
Binary file (2.8 kB). View file
 
entity/__pycache__/Database_Entity.cpython-311.pyc ADDED
Binary file (4.77 kB). View file
 
entity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (168 Bytes). View file
 
firebase_certificate.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "cogent-octane-384105",
4
+ "private_key_id": "94d2eb71fcc53c8504e822a2367157b49b65b16d",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+awYE99nwJwid\neFuujKYL1cxdknb5lze6ON2wwn6F/lZCjf0wyYTyYAzk2yVDy8p+xy+jsbT22iaX\n8K6fwCqMVUMby9e813cQuS7ycF7WSS1Fw9JwljktnMLplJZuTv3zmlolNiePz/rS\nPcPaSvjQWO4s/G1A8knbY2gXaY4e7ie37GGKDOsgfEF8sQJ2TRll79qzoAWqIz1I\np87s+vR+Z3nPlVqiCM7cYP9ddvFEQxF381STDIExQzKSYbQyUsnU1lOZ7zWKb4F+\nHGjLzYBhf6CzU+l3M/kiaTJck+T7H/tSWo+bzFYFRpeh6Q7/UBwbBYN+7VOXTJ1Q\nEBQdwolBAgMBAAECggEAGG8v+405GG751Qhvw1XlrMPHkK5NuWNlJu6gdqEj49p/\ng9TSi43LEzWuEePpGT+vrABapZ0VGqQNqxZFt4F3iZXF9xgmMTj43LAr97eMWTT/\nVozKlotAVRELleDs7hoRePlH3gSKo71Ncz2ybHLjELaIrER2rzcoBmXwIn5MsBJ+\nDOqdZAo3UadvzcRpTUY6ju1Kd8w72FYgW/3RfK6eikZEw8sX8vKQ7QEH8bKeZVt7\nWOrkBK2kHEyR8dTga2igQRI7Cezqv48yiYjYbi+D/DBocjpHtJnPLbgOOWyjbmDU\n5fB+bxf+7qXZn/AIp96Iq1s2ZHxldlKk38yne40N7QKBgQDf/+A2lQswySNdLR1+\nNJME3OGgBG9Jq0mnBoe9rWOBBBAQNYv4uZO4MVvmLwzIN1y32MV6zkbnD9fMWKIf\nciIzje8xip/9ei6weB5n0Yp13f9JxBW0r1HaUVk7jpHyH7rk3GvNcebZNKM+yndh\n1rdyE1V6xGNqAXzX9vP4t6IiYwKBgQDZnwEwggMToQrl1jsxz7VlujPNSUhOgwGL\nj0nHCbUf2/jZ1hyMRU659RWmWGA70rsALwQ4IQoM5UHZkKc12MjswmXllrkk1Jmu\nc04OE5SWde7SWAzSj5oqCIoQt0B/3r7cRjgr0TK3SwxxIUOcazyFzvLrxJxsGFHc\nOfE3jP5lCwKBgCf0kl/qEgbvudki9QHQCvFxHOXYJKm1XfvnFEtnJDqdKOhbRM5m\n+8x9MXFLrzH/fhBlIESZitgoYUvX+4M0bplXlfT2Tzd9ldpwcqv+Gn6PzLuxuFV0\neFtC63HOKoZP1pyAHNKWoKDZ3MyUfNr829gDTtoJMdp0zXoQWNBioQ8VAoGBAKvd\n5aSXqTJhZyfpL0rBjbNPgQXJsG9BC4Faopus0PzeTwRLErS9L9Ww924uMaJNZR5a\nA20IutVAYecfVM8z7Er/pFXT2Vh7Bvw9WBHJ6PmDHh/FJitM+iXkJJXbA/d4xSdV\n1ZrVVsZnYOYfrTPlhSDwNe15k0fTVSMmJ5kFowvNAoGAc101K46kuKl+K/V6gdnW\nN2reMwlJf4Wgaz7yX0Gkha95dNGmy1ZC+NdD3qlSbOv353OITzNCBo7pSAAphQr2\noVkpyToTQOcSBjjAzTkXHabn3N1Rmj1P7GPwz5WyDPjp4t+GmT8Se3aJ1gtCnKeb\noxwTPi7EHyoIiYnEXYRuzSw=\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "firebase-adminsdk-z0bu3@cogent-octane-384105.iam.gserviceaccount.com",
7
+ "client_id": "105944722897200826755",
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/firebase-adminsdk-z0bu3%40cogent-octane-384105.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
14
+
function/__pycache__/chatbot.cpython-310.pyc ADDED
Binary file (22.5 kB). View file
 
function/__pycache__/chatbot.cpython-311.pyc ADDED
Binary file (42.3 kB). View file
 
function/__pycache__/dropbox.cpython-310.pyc ADDED
Binary file (6 kB). View file
 
function/__pycache__/dropbox.cpython-311.pyc ADDED
Binary file (12.4 kB). View file
 
function/__pycache__/support_function.cpython-310.pyc ADDED
Binary file (4.12 kB). View file
 
function/__pycache__/support_function.cpython-311.pyc ADDED
Binary file (7.76 kB). View file
 
function/chatbot.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.text_splitter import CharacterTextSplitter
2
+ import json
3
+ import os
4
+ import random
5
+ import re
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import google.generativeai as genai
8
+ import nltk
9
+ import pandas as pd
10
+ from groq import Groq
11
+ from langchain.chains.summarize import load_summarize_chain
12
+ from langchain.docstore.document import Document
13
+ from langchain.prompts import PromptTemplate
14
+ from langchain.retrievers import BM25Retriever, EnsembleRetriever
15
+ from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
16
+ from langchain.text_splitter import CharacterTextSplitter
17
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
18
+ from langchain_cohere import CohereRerank
19
+ from langchain_community.document_loaders import Docx2txtLoader
20
+ from langchain_community.document_loaders import TextLoader
21
+ from langchain_community.document_loaders import UnstructuredCSVLoader
22
+ from langchain_community.document_loaders import UnstructuredExcelLoader
23
+ from langchain_community.document_loaders import UnstructuredHTMLLoader
24
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
25
+ from langchain_community.document_loaders import UnstructuredPDFLoader
26
+ from langchain_community.document_loaders import UnstructuredPowerPointLoader
27
+ from langchain_community.document_loaders import UnstructuredXMLLoader
28
+ from langchain_community.document_loaders.csv_loader import CSVLoader
29
+ from langchain_community.llms import Cohere
30
+ from langchain_community.vectorstores import Chroma
31
+ from langchain_core.output_parsers.openai_tools import PydanticToolsParser
32
+ from langchain_core.prompts import ChatPromptTemplate
33
+ from langchain_core.pydantic_v1 import BaseModel, Field
34
+ from langchain_core.runnables import RunnablePassthrough
35
+ from langchain_openai import ChatOpenAI
36
+ from typing import List
37
+ nltk.download('punkt')
38
+
39
+ def process_json_file(file_path):
40
+ json_data = []
41
+ with open(file_path, 'r') as file:
42
+ for line in file:
43
+ try:
44
+ data = json.loads(line)
45
+ json_data.append(data)
46
+ except json.JSONDecodeError:
47
+ try:
48
+ data = json.loads(line[:-1])
49
+ json_data.append(data)
50
+ except json.JSONDecodeError as e:
51
+ print(f"Error decoding JSON: {e}")
52
+ return json_data
53
+
54
+
55
+ from dotenv import load_dotenv
56
+ import os
57
+ load_dotenv()
58
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
59
+ COHERE_API_KEY = os.getenv("COHERE_API_KEY")
60
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
61
+ GOOGLE_API_KEY1= os.getenv("GOOGLE_API_KEY_1")
62
+ GOOGLE_API_KEY= os.getenv("GOOGLE_API_KEY")
63
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY
64
+ os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
65
+ client = Groq(
66
+ api_key= GROQ_API_KEY,
67
+ )
68
+ genai.configure(api_key=GOOGLE_API_KEY1)
69
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
70
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
71
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
72
+ llm = ChatGoogleGenerativeAI(model='gemini-pro',
73
+ max_output_tokens=2048,
74
+ temperature=0.3,
75
+ convert_system_message_to_human=True)
76
+ def extract_multi_metadata_content(texts, tests):
77
+ extracted_content = []
78
+ precomputed_metadata = [x.metadata['source'].lower() for x in texts]
79
+ for idx, test in enumerate(tests):
80
+ temp_content = []
81
+ test_terms = set(test.lower().split()) # Use set for faster lookup
82
+ for metadata_lower, x in zip(precomputed_metadata, texts):
83
+ if any(term in metadata_lower for term in test_terms):
84
+ temp_content.append(x.page_content)
85
+ if idx == 0:
86
+ extracted_content.append(f"Dữ liệu của {test}:\n{''.join(temp_content)}")
87
+ else:
88
+ extracted_content.append(''.join(temp_content))
89
+ return '\n'.join(extracted_content)
90
+
91
+ def find_matching_files_in_docs_12_id(text, id):
92
+ folder_path = f"./user_file/{id}"
93
+ search_terms = []
94
+ search_terms_old = []
95
+ matching_index = []
96
+ search_origin = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text)
97
+ search_terms_origin = []
98
+ for word in search_origin:
99
+ if '.' in word:
100
+ search_terms_origin.append(word)
101
+ else:
102
+ search_terms_origin.extend(re.findall(r'\b\w+\b', word))
103
+
104
+ file_names_with_extension = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text.lower())
105
+ file_names_with_extension_old = re.findall(r'\b(\w+\.\w+)\b', text)
106
+ for file_name in search_terms_origin:
107
+ if "." in file_name:
108
+ term_position = search_terms_origin.index(file_name)
109
+ search_terms_old.append(file_name)
110
+ for file_name in file_names_with_extension_old:
111
+ if "." in file_name:
112
+ search_terms_old.append(file_name)
113
+ for file_name in file_names_with_extension:
114
+ search_terms.append(file_name)
115
+ clean_text_old = text
116
+ clean_text = text.lower()
117
+ search_terms_old1 = list(set(search_terms_old))
118
+ for term in search_terms_old:
119
+ clean_text_old = clean_text_old.replace(term, '')
120
+ for term in search_terms:
121
+ clean_text = clean_text.replace(term, '')
122
+ words_old = re.findall(r'\b\w+\b', clean_text_old)
123
+ search_terms_old.extend(words_old)
124
+ matching_files = set()
125
+ matching_files_old = set()
126
+ for root, dirs, files in os.walk(folder_path):
127
+ for file in files:
128
+ for term in search_terms:
129
+ if term.lower() in file.lower():
130
+ term_position = search_terms.index(term)
131
+ term_value = search_terms_origin[term_position]
132
+ matching_files.add(file)
133
+ matching_index.append(term_position)
134
+ break
135
+ matching_files_old1 = []
136
+ matching_index.sort()
137
+ for x in matching_index:
138
+ matching_files_old1.append(search_terms_origin[x])
139
+ return matching_files, matching_files_old1, search_terms_old1
140
+
141
+ def convert_xlsx_to_csv(xlsx_file_path, csv_file_path):
142
+ df = pd.read_excel(xlsx_file_path)
143
+ df.to_csv(csv_file_path, index=False)
144
+
145
+ def save_list_CSV_id(file_list, id):
146
+ text = ""
147
+ for x in file_list:
148
+ if x.endswith('.xlsx'):
149
+ old = f"./user_file/{id}/{x}"
150
+ new = old.replace(".xlsx", ".csv")
151
+ convert_xlsx_to_csv(old, new)
152
+ x = x.replace(".xlsx", ".csv")
153
+ loader1 = CSVLoader(f"./user_file/{id}/{x}")
154
+ docs1 = loader1.load()
155
+ text += f"Dữ liệu file {x}:\n"
156
+ for z in docs1:
157
+ text += z.page_content + "\n"
158
+ return text
159
+
160
+ def merge_files(file_set, file_list):
161
+ """Hàm này ghép lại các tên file dựa trên điều kiện đã cho."""
162
+ merged_files = {}
163
+ for file_name in file_list:
164
+ name = file_name.split('.')[0]
165
+ for f in file_set:
166
+ if name in f:
167
+ merged_files[name] = f
168
+ break
169
+ return merged_files
170
+
171
+ def replace_keys_with_values(original_dict, replacement_dict):
172
+ new_dict = {}
173
+ for key, value in original_dict.items():
174
+ if key in replacement_dict:
175
+ new_key = replacement_dict[key]
176
+ new_dict[new_key] = value
177
+ else:
178
+ new_dict[key] = value
179
+ return new_dict
180
+
181
+ def aws1_csv_id(new_dict_csv, id):
182
+ text = ""
183
+ query_all = ""
184
+ keyword = []
185
+ for key, value in new_dict_csv.items():
186
+ print(key, value)
187
+ query_all += value
188
+ keyword.append(key)
189
+ test = save_list_CSV_id(keyword, id)
190
+ text += test
191
+ sources = ",".join(keyword)
192
+ return text, query_all, sources
193
+
194
+ def chat_llama3(prompt_query):
195
+ try:
196
+ chat_completion = client.chat.completions.create(
197
+ messages=[
198
+ {
199
+ "role": "system",
200
+ "content": "Bạn là một trợ lý trung thưc, trả lời dựa trên nội dung tài liệu được cung cấp. Chỉ trả lời liên quan đến câu hỏi một cách đầy đủ chính xác, không bỏ sót thông tin."
201
+ },
202
+ {
203
+ "role": "user",
204
+ "content": f"{prompt_query}",
205
+ }
206
+ ],
207
+ model="llama3-70b-8192",
208
+ temperature=0.0,
209
+ max_tokens=9000,
210
+ stop=None,
211
+ stream=False,
212
+ )
213
+ return chat_completion.choices[0].message.content
214
+ except Exception as error:
215
+ return False
216
+
217
+ def chat_gemini(prompt):
218
+ generation_config = {
219
+ "temperature": 0.0,
220
+ "top_p": 0.0,
221
+ "top_k": 0,
222
+ "max_output_tokens": 8192,
223
+ }
224
+ safety_settings = [
225
+ {
226
+ "category": "HARM_CATEGORY_HARASSMENT",
227
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
228
+ },
229
+ {
230
+ "category": "HARM_CATEGORY_HATE_SPEECH",
231
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
232
+ },
233
+ {
234
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
235
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
236
+ },
237
+ {
238
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
239
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
240
+ },
241
+ ]
242
+ model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest",
243
+ generation_config=generation_config,
244
+ safety_settings=safety_settings)
245
+ convo = model.start_chat(history=[])
246
+ convo.send_message(prompt)
247
+ return convo.last.text
248
+
249
+ def question_answer(question):
250
+ completion = chat_llama3(question)
251
+ if completion:
252
+ return completion
253
+ else:
254
+ answer = chat_gemini(question)
255
+ return answer
256
+
257
+ def check_persist_directory(id, file_name):
258
+ directory_path = f"./vector_database/{id}/{file_name}"
259
+ return os.path.exists(directory_path)
260
+
261
+ from langchain_community.vectorstores import FAISS
262
+
263
+ def check_path_exists(path):
264
+ return os.path.exists(path)
265
+ def aws1_all_id(new_dict, text_alls, id, thread_id):
266
+ answer = ""
267
+ COHERE_API_KEY1 = os.getenv("COHERE_API_KEY_1")
268
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY1
269
+ answer_relevant = ""
270
+ directory = ""
271
+
272
+ for key, value in new_dict.items():
273
+ query = value
274
+ keyword, keyword2, keyword3 = find_matching_files_in_docs_12_id(query, id)
275
+ data = extract_multi_metadata_content(text_alls, keyword)
276
+ if keyword:
277
+ file_name = next(iter(keyword))
278
+ text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
279
+ texts_data = text_splitter.split_text(data)
280
+
281
+ if check_persist_directory(id, file_name):
282
+ vectordb_query = Chroma(persist_directory=f"./vector_database/{id}/{file_name}", embedding_function=embeddings)
283
+ else:
284
+ vectordb_query = Chroma.from_texts(texts_data,
285
+ embedding=embeddings,
286
+ persist_directory=f"./vector_database/{id}/{file_name}")
287
+
288
+ k_1 = len(texts_data)
289
+ retriever = vectordb_query.as_retriever(search_kwargs={f"k": k_1})
290
+ bm25_retriever = BM25Retriever.from_texts(texts_data)
291
+ bm25_retriever.k = k_1
292
+ ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, retriever],
293
+ weights=[0.6, 0.4])
294
+ docs = ensemble_retriever.get_relevant_documents(f"{query}")
295
+
296
+ path = f"./vector_database/FAISS/{id}/{file_name}"
297
+ if check_path_exists(path):
298
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
299
+ else:
300
+ docsearch = FAISS.from_documents(docs, embeddings)
301
+ docsearch.save_local(f"./vector_database/FAISS/{id}/{file_name}")
302
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
303
+
304
+ k_2 = len(docs)
305
+ compressor = CohereRerank(top_n=5)
306
+ retrieve3 = docsearch.as_retriever(search_kwargs={f"k": k_2})
307
+ compression_retriever = ContextualCompressionRetriever(
308
+ base_compressor=compressor, base_retriever=retrieve3
309
+ )
310
+ compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
311
+
312
+ if compressed_docs:
313
+ data = compressed_docs[0].page_content
314
+ text = ''.join(map(lambda x: x.page_content, compressed_docs))
315
+ prompt_document = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi nội dung mà mình đã cung cấp"
316
+ answer_for = question_answer(prompt_document)
317
+ answer += answer_for + "\n"
318
+ answer_relevant = data
319
+ directory = file_name
320
+
321
+ return answer, answer_relevant, directory
322
+
323
+ def extract_content_between_keywords(query, keywords):
324
+ contents = {}
325
+ num_keywords = len(keywords)
326
+ keyword_positions = []
327
+ for i in range(num_keywords):
328
+ keyword = keywords[i]
329
+ keyword_position = query.find(keyword)
330
+ keyword_positions.append(keyword_position)
331
+ if keyword_position == -1:
332
+ continue
333
+ next_keyword_position = len(query)
334
+ for j in range(i + 1, num_keywords):
335
+ next_keyword = keywords[j]
336
+ next_keyword_position = query.find(next_keyword)
337
+ if next_keyword_position != -1:
338
+ break
339
+ if i == 0:
340
+ content_before = query[:keyword_position].strip()
341
+ else:
342
+ content_before = query[keyword_positions[i - 1] + len(keywords[i - 1]):keyword_position].strip()
343
+ if i == num_keywords - 1:
344
+ content_after = query[keyword_position + len(keyword):].strip()
345
+ else:
346
+ content_after = query[keyword_position + len(keyword):next_keyword_position].strip()
347
+ content = f"{content_before} {keyword} {content_after}"
348
+ contents[keyword] = content
349
+ return contents
350
+
351
+ def generate_random_questions(filtered_ques_list):
352
+ if len(filtered_ques_list) >= 2:
353
+ random_questions = random.sample(filtered_ques_list, 2)
354
+ else:
355
+ random_questions = filtered_ques_list
356
+ return random_questions
357
+
358
+ def generate_question_main(loader, name_file):
359
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=4500, chunk_overlap=2500)
360
+ texts = text_splitter.split_documents(loader)
361
+ question_gen = f"nội dung {name_file} : \n"
362
+ question_gen += texts[0].page_content
363
+ splitter_ques_gen = RecursiveCharacterTextSplitter(
364
+ chunk_size=4500,
365
+ chunk_overlap=2200
366
+ )
367
+ chunks_ques_gen = splitter_ques_gen.split_text(question_gen)
368
+ document_ques_gen = [Document(page_content=t) for t in chunks_ques_gen]
369
+ llm_ques_gen_pipeline = llm
370
+ prompt_template_vn = """
371
+ Bạn là một chuyên gia tạo câu hỏi dựa trên tài liệu và tài liệu hướng dẫn.
372
+ Bạn làm điều này bằng cách đặt các câu hỏi về đoạn văn bản dưới đây:
373
+
374
+ ------------
375
+ {text}
376
+ ------------
377
+
378
+ Hãy tạo ra các câu hỏi từ đoạn văn bản này.Nếu đoạn văn là tiếng Việt hãy tạo câu hỏi tiếng Việt. Nếu đoạn văn là tiếng Anh hãy tạo câu hỏi tiếng Anh.
379
+ Hãy chắc chắn không bỏ sót bất kỳ thông tin quan trọng nào. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất.Nếu trong đoạn tài liệu có các tên liên quan đến file như demo1.pdf( nhiều file khác) thì phải kèm nó vào nội dung câu hỏi bạn tạo ra.
380
+
381
+ CÁC CÂU HỎI:
382
+ """
383
+
384
+ PROMPT_QUESTIONS_VN = PromptTemplate(template=prompt_template_vn, input_variables=["text"])
385
+ refine_template_vn = ("""
386
+ Bạn là một chuyên gia tạo câu hỏi thực hành dựa trên tài liệu và tài liệu hướng dẫn.
387
+ Mục tiêu của bạn là giúp người học chuẩn bị cho một kỳ thi.
388
+ Chúng tôi đã nhận được một số câu hỏi thực hành ở mức độ nào đó: {existing_answer}.
389
+ Chúng tôi có thể tinh chỉnh các câu hỏi hiện có hoặc thêm câu hỏi mới
390
+ (chỉ khi cần thiết) với một số ngữ cảnh bổ sung dưới đây.
391
+ ------------
392
+ {text}
393
+ ------------
394
+
395
+ Dựa trên ngữ cảnh mới, hãy tinh chỉnh các câu hỏi bằng tiếng Việt nếu đoạn văn đó cung cấp tiếng Việt. Nếu không hãy tinh chỉnh câu hỏi bằng tiếng Anh nếu đoạn đó cung cấp tiếng Anh.
396
+ Nếu ngữ cảnh không hữu ích, vui lòng cung cấp các câu hỏi gốc. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất. Nếu trong đoạn tài liệu có các tên file thì phải kèm nó vào câu hỏi.
397
+ CÁC CÂU HỎI:
398
+ """
399
+ )
400
+
401
+ REFINE_PROMPT_QUESTIONS = PromptTemplate(
402
+ input_variables=["existing_answer", "text"],
403
+ template=refine_template_vn,
404
+ )
405
+ ques_gen_chain = load_summarize_chain(llm=llm_ques_gen_pipeline,
406
+ chain_type="refine",
407
+ verbose=True,
408
+ question_prompt=PROMPT_QUESTIONS_VN,
409
+ refine_prompt=REFINE_PROMPT_QUESTIONS)
410
+ ques = ques_gen_chain.run(document_ques_gen)
411
+ ques_list = ques.split("\n")
412
+ filtered_ques_list = ["{}: {}".format(name_file, re.sub(r'^\d+\.\s*', '', element)) for element in ques_list if
413
+ element.endswith('?') or element.endswith('.')]
414
+ return generate_random_questions(filtered_ques_list)
415
+
416
+ def load_file(loader):
417
+ return loader.load()
418
+
419
+ def extract_data2(id):
420
+ documents = []
421
+ directory_path = f"./user_file/{id}"
422
+ if not os.path.exists(directory_path) or not any(
423
+ os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
424
+ return False
425
+ tasks = []
426
+ with ThreadPoolExecutor() as executor:
427
+ for file in os.listdir(directory_path):
428
+ if file.endswith(".pdf"):
429
+ pdf_path = os.path.join(directory_path, file)
430
+ loader = UnstructuredPDFLoader(pdf_path)
431
+ tasks.append(executor.submit(load_file, loader))
432
+ elif file.endswith('.docx') or file.endswith('.doc'):
433
+ doc_path = os.path.join(directory_path, file)
434
+ loader = Docx2txtLoader(doc_path)
435
+ tasks.append(executor.submit(load_file, loader))
436
+ elif file.endswith('.txt'):
437
+ txt_path = os.path.join(directory_path, file)
438
+ loader = TextLoader(txt_path, encoding="utf8")
439
+ tasks.append(executor.submit(load_file, loader))
440
+ elif file.endswith('.pptx'):
441
+ ppt_path = os.path.join(directory_path, file)
442
+ loader = UnstructuredPowerPointLoader(ppt_path)
443
+ tasks.append(executor.submit(load_file, loader))
444
+ elif file.endswith('.csv'):
445
+ csv_path = os.path.join(directory_path, file)
446
+ loader = UnstructuredCSVLoader(csv_path)
447
+ tasks.append(executor.submit(load_file, loader))
448
+ elif file.endswith('.xlsx'):
449
+ excel_path = os.path.join(directory_path, file)
450
+ loader = UnstructuredExcelLoader(excel_path)
451
+ tasks.append(executor.submit(load_file, loader))
452
+ elif file.endswith('.json'):
453
+ json_path = os.path.join(directory_path, file)
454
+ loader = TextLoader(json_path)
455
+ tasks.append(executor.submit(load_file, loader))
456
+ elif file.endswith('.md'):
457
+ md_path = os.path.join(directory_path, file)
458
+ loader = UnstructuredMarkdownLoader(md_path)
459
+ tasks.append(executor.submit(load_file, loader))
460
+ for future in as_completed(tasks):
461
+ result = future.result()
462
+ documents.extend(result)
463
+ text_splitter = CharacterTextSplitter(chunk_size=4500, chunk_overlap=2500)
464
+ texts = text_splitter.split_documents(documents)
465
+ Chroma.from_documents(documents=texts,
466
+ embedding=embeddings,
467
+ persist_directory=f"./vector_database/{id}")
468
+ return texts
469
+
470
+ def generate_question(id):
471
+ directory_path = f"./user_file/{id}"
472
+ if not os.path.exists(directory_path) or not any(
473
+ os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
474
+ return False
475
+ all_questions = []
476
+ tasks = []
477
+ with ThreadPoolExecutor() as executor:
478
+ for file in os.listdir(directory_path):
479
+ if file.endswith(".pdf"):
480
+ pdf_path = os.path.join(directory_path, file)
481
+ loader = UnstructuredPDFLoader(pdf_path).load()
482
+ tasks.append(executor.submit(generate_question_main, loader, file))
483
+ elif file.endswith('.docx') or file.endswith('.doc'):
484
+ doc_path = os.path.join(directory_path, file)
485
+ loader = Docx2txtLoader(doc_path).load()
486
+ tasks.append(executor.submit(generate_question_main, loader, file))
487
+ elif file.endswith('.txt'):
488
+ txt_path = os.path.join(directory_path, file)
489
+ loader = TextLoader(txt_path, encoding="utf8").load()
490
+ tasks.append(executor.submit(generate_question_main, loader, file))
491
+ elif file.endswith('.pptx'):
492
+ ppt_path = os.path.join(directory_path, file)
493
+ loader = UnstructuredPowerPointLoader(ppt_path).load()
494
+ tasks.append(executor.submit(generate_question_main, loader, file))
495
+ elif file.endswith('.json'):
496
+ json_path = os.path.join(directory_path, file)
497
+ loader = TextLoader(json_path, encoding="utf8").load()
498
+ tasks.append(executor.submit(generate_question_main, loader, file))
499
+ elif file.endswith('.md'):
500
+ md_path = os.path.join(directory_path, file)
501
+ loader = UnstructuredMarkdownLoader(md_path).load()
502
+ tasks.append(executor.submit(generate_question_main, loader, file))
503
+ for future in as_completed(tasks):
504
+ result = future.result()
505
+ all_questions.extend(result)
506
+ return all_questions
507
+
508
+ class Search(BaseModel):
509
+ queries: List[str] = Field(
510
+ ...,
511
+ description="Truy vấn riêng biệt để tìm kiếm, giữ nguyên ý chính câu hỏi riêng biệt",
512
+ )
513
+
514
+ def query_analyzer(query):
515
+ output_parser = PydanticToolsParser(tools=[Search])
516
+ system = """Bạn có khả năng đưa ra các truy vấn tìm kiếm chính xác để lấy thông tin giúp trả lời các yêu cầu của người dùng. Các truy vấn của bạn phải chính xác, không được bỏ ngắn rút gọn.
517
+ Nếu bạn cần tra cứu hai hoặc nhiều thông tin riêng biệt, bạn có thể làm điều đó!. Trả lời câu hỏi bằng tiếng Việt(Vietnamese), không được dùng ngôn ngữ khác"""
518
+ prompt = ChatPromptTemplate.from_messages(
519
+ [
520
+ ("system", system),
521
+ ("human", "{question}"),
522
+ ]
523
+ )
524
+ llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.0)
525
+ structured_llm = llm.with_structured_output(Search)
526
+ query_analyzer = {"question": RunnablePassthrough()} | prompt | structured_llm
527
+ text = query_analyzer.invoke(query)
528
+ return text
529
+
530
+ def handle_query(question, text_all, compression_retriever, id, thread_id):
531
+ query = question
532
+ x = query
533
+ keyword, key_words_old, key3 = find_matching_files_in_docs_12_id(query, id)
534
+ if keyword == set() or key_words_old == list():
535
+ return "Not found file"
536
+ file_list = keyword
537
+
538
+ if file_list:
539
+ list_keywords2 = list(key_words_old)
540
+ contents1 = extract_content_between_keywords(query, list_keywords2)
541
+ merged_result = merge_files(keyword, list_keywords2)
542
+ original_dict = contents1
543
+ replacement_dict = merged_result
544
+ new_dict = replace_keys_with_values(original_dict, replacement_dict)
545
+ files_to_remove = [filename for filename in new_dict.keys() if
546
+ filename.endswith('.xlsx') or filename.endswith('.csv')]
547
+ removed_files = {}
548
+ for filename in files_to_remove:
549
+ removed_files[filename] = new_dict[filename]
550
+ for filename in files_to_remove:
551
+ new_dict.pop(filename)
552
+ test_csv = ""
553
+ text_csv, query_csv, source = aws1_csv_id(removed_files, id)
554
+ prompt_csv = ""
555
+ answer_csv = ""
556
+ if test_csv:
557
+ prompt_csv = f"Dựa vào nội dung sau: {text_csv}. Hãy trả lời câu hỏi sau đây: {query_csv}.Bằng tiếng Việt"
558
+ answer_csv = question_answer(prompt_csv)
559
+ answer_document, data_relevant, source = aws1_all_id(new_dict, text_all, id, thread_id)
560
+ answer_all1 = answer_document + answer_csv
561
+ return answer_all1, data_relevant, source
562
+ else:
563
+ compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
564
+ relevance_score_float = float(compressed_docs[0].metadata['relevance_score'])
565
+ if relevance_score_float <= 0.25:
566
+ documents1 = []
567
+ for file in os.listdir(f"./user_file/{id}"):
568
+ if file.endswith('.csv'):
569
+ csv_path = f"./user_file/{id}/" + file
570
+ loader = UnstructuredCSVLoader(csv_path)
571
+ documents1.extend(loader.load())
572
+ elif file.endswith('.xlsx'):
573
+ excel_path = f"./user_file/{id}/" + file
574
+ loader = UnstructuredExcelLoader(excel_path)
575
+ documents1.extend(loader.load())
576
+ text_splitter_csv = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=2200, chunk_overlap=1500)
577
+ texts_csv = text_splitter_csv.split_documents(documents1)
578
+ vectordb_csv = Chroma.from_documents(documents=texts_csv,
579
+ embedding=embeddings, persist_directory=f'./vector_database/csv/{thread_id}')
580
+ k = len(texts_csv)
581
+ retriever_csv = vectordb_csv.as_retriever(search_kwargs={"k": k})
582
+ llm = Cohere(temperature=0)
583
+ compressor_csv = CohereRerank(top_n=3, model="rerank-english-v2.0")
584
+ compression_retriever_csv = ContextualCompressionRetriever(
585
+ base_compressor=compressor_csv, base_retriever=retriever_csv
586
+ )
587
+ compressed_docs_csv = compression_retriever_csv.get_relevant_documents(f"{query}")
588
+ file_path = compressed_docs_csv[0].metadata['source']
589
+ print(file_path)
590
+ if file_path.endswith('.xlsx'):
591
+ new = file_path.replace(".xlsx", ".csv")
592
+ convert_xlsx_to_csv(file_path, new)
593
+ loader1 = CSVLoader(new)
594
+ else:
595
+ loader1 = CSVLoader(file_path)
596
+ docs1 = loader1.load()
597
+ text = " "
598
+ for z in docs1:
599
+ text += z.page_content + "\n"
600
+ prompt_csv = f"Dựa vào nội dung sau: {text}. Hãy trả lời câu hỏi sau đây: {query}. Bằng tiếng Việt"
601
+ answer_csv = question_answer(prompt_csv)
602
+ return answer_csv
603
+ else:
604
+ file_path = compressed_docs[0].metadata['source']
605
+ if file_path.endswith(".pdf"):
606
+ loader = UnstructuredPDFLoader(file_path)
607
+ elif file_path.endswith('.docx') or file_path.endswith('doc'):
608
+ loader = Docx2txtLoader(file_path)
609
+ elif file_path.endswith('.txt'):
610
+ loader = TextLoader(file_path, encoding="utf8")
611
+ elif file_path.endswith('.pptx'):
612
+ loader = UnstructuredPowerPointLoader(file_path)
613
+ elif file_path.endswith('.xml'):
614
+ loader = UnstructuredXMLLoader(file_path)
615
+ elif file_path.endswith('.html'):
616
+ loader = UnstructuredHTMLLoader(file_path)
617
+ elif file_path.endswith('.json'):
618
+ loader = TextLoader(file_path)
619
+ elif file_path.endswith('.md'):
620
+ loader = UnstructuredMarkdownLoader(file_path)
621
+ elif file_path.endswith('.xlsx'):
622
+ file_path_new = file_path.replace(".xlsx", ".csv")
623
+ convert_xlsx_to_csv(file_path, file_path_new)
624
+ loader = CSVLoader(file_path_new)
625
+ elif file_path.endswith('.csv'):
626
+ loader = CSVLoader(file_path)
627
+ text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
628
+ texts = text_splitter.split_documents(loader.load())
629
+ k_1 = len(texts)
630
+ file_name = os.path.basename(file_path)
631
+ if check_persist_directory(id, file_name):
632
+ vectordb_file = Chroma(persist_directory=f"./vector_database/{id}/{file_name}",
633
+ embedding_function=embeddings)
634
+ else:
635
+ vectordb_file = Chroma.from_documents(texts,
636
+ embedding=embeddings,
637
+ persist_directory=f"./vector_database/{id}/{file_name}")
638
+ retriever_file = vectordb_file.as_retriever(search_kwargs={f"k": k_1})
639
+ compressor_file = CohereRerank(top_n=5, model="rerank-english-v2.0")
640
+ compression_retriever_file = ContextualCompressionRetriever(
641
+ base_compressor=compressor_file, base_retriever=retriever_file
642
+ )
643
+ compressed_docs_file = compression_retriever_file.get_relevant_documents(f"{x}")
644
+ query = question
645
+ text = ''.join(map(lambda x: x.page_content, compressed_docs_file))
646
+ prompt = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp"
647
+ answer = question_answer(prompt)
648
+ list_relevant = compressed_docs_file[0].page_content
649
+ source = file_name
650
+ return answer, list_relevant, source
651
+
652
+ def handle_query_upgrade_keyword_old(query_all, text_all, id):
653
+ COHERE_API_KEY_2 = os.environ["COHERE_API_KEY_2"]
654
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY_2
655
+ test = query_analyzer(query_all)
656
+ test_string = str(test)
657
+ matches = re.findall(r"'([^']*)'", test_string)
658
+ vectordb = Chroma(persist_directory=f"./vector_database/{id}", embedding_function=embeddings)
659
+ k = len(text_all)
660
+ retriever = vectordb.as_retriever(search_kwargs={"k": k})
661
+ compressor = CohereRerank(top_n=5, model="rerank-english-v2.0")
662
+ compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever= retriever)
663
+ with ThreadPoolExecutor() as executor:
664
+ futures = {executor.submit(handle_query, query, text_all, compression_retriever, id, i): query for i, query in
665
+ enumerate(matches)}
666
+ results = []
667
+ data_relevant = []
668
+ sources = []
669
+ for future in as_completed(futures):
670
+ try:
671
+ result, list_data, list_source = future.result()
672
+ results.append(result)
673
+ data_relevant.append(list_data)
674
+ sources.append(list_source)
675
+ except Exception as e:
676
+ print(f'An error occurred: {e}')
677
+ answer_all = ''.join(results)
678
+ prompt1 = f"Dựa vào nội dung sau:{answer_all}. Hãy trả lời câu hỏi sau đây: {query_all}. Mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp"
679
+ answer1 = question_answer(prompt1)
680
+ return answer1, data_relevant, sources
function/dropbox.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dropbox.files
2
+ import os
3
+ import shutil
4
+ import requests, base64
5
+ from fastapi import HTTPException
6
+ from dotenv import load_dotenv
7
+ import os
8
+ load_dotenv()
9
+ DROPBOX_APP_KEY=os.getenv('DROPBOX_APP_KEY')
10
+ DROPBOX_APP_SECRET=os.getenv('DROPBOX_APP_SECRET')
11
+ DROPBOX_REFRESH_TOKEN=os.getenv('DROPBOX_REFRESH_TOKEN')
12
+
13
+ def refresh_token_dropbox():
14
+ app_key = DROPBOX_APP_KEY
15
+ app_secret = DROPBOX_APP_SECRET
16
+ refresh_token = DROPBOX_REFRESH_TOKEN
17
+ url = 'https://api.dropbox.com/oauth2/token'
18
+ auth_string = f"{app_key}:{app_secret}"
19
+ base64authorization = base64.b64encode(auth_string.encode()).decode('utf-8')
20
+ headers = {
21
+ 'Authorization': f'Basic {base64authorization}',
22
+ 'Content-Type': 'application/x-www-form-urlencoded'
23
+ }
24
+ data = {
25
+ 'refresh_token': refresh_token,
26
+ 'grant_type': 'refresh_token'
27
+ }
28
+ response = requests.post(url, headers=headers, data=data)
29
+ response_json = response.json()
30
+ access_token = response_json.get('access_token', None)
31
+ return access_token
32
+
33
+ def delete_file(id,name_file):
34
+ try:
35
+ TOKEN = refresh_token_dropbox()
36
+ dbx=dropbox.Dropbox(TOKEN)
37
+ file_path = f"/{id}/{name_file}"
38
+ dbx.files_delete_v2(file_path)
39
+ print(f"Xóa file '{file_path}' thành công.")
40
+ except dropbox.exceptions.ApiError as e:
41
+ print(f"Lỗi khi xóa file '{file_path}': {e}")
42
+
43
+ def list_files(id):
44
+ file_names = []
45
+ try:
46
+ TOKEN = refresh_token_dropbox()
47
+ dbx=dropbox.Dropbox(TOKEN)
48
+ result = dbx.files_list_folder(f"/{id}")
49
+ for entry in result.entries:
50
+ if isinstance(entry, dropbox.files.FileMetadata):
51
+ file_names.append(os.path.basename(entry.path_display))
52
+ except dropbox.exceptions.ApiError as e:
53
+ print(f"Error listing files: {e}")
54
+ return file_names
55
+
56
+ def upload_file_fix(local_path,cloud_path,token):
57
+ try:
58
+ TOKEN = refresh_token_dropbox()
59
+ dbx=dropbox.Dropbox(TOKEN)
60
+ with open(local_path, "rb") as f:
61
+ data = f.read()
62
+ dbx.files_upload(data, cloud_path)
63
+ print(f"Uploaded file '{local_path}' to '{cloud_path}'")
64
+ except dropbox.exceptions.ApiError as e:
65
+ print(f"Error uploading file '{local_path}': {e}")
66
+
67
+ def upload_file(local_path, cloud_path):
68
+ try:
69
+ TOKEN = refresh_token_dropbox()
70
+ dbx=dropbox.Dropbox(TOKEN)
71
+ with open(local_path, "rb") as f:
72
+ data = f.read()
73
+ dbx.files_upload(data, cloud_path)
74
+ print(f"Uploaded file '{local_path}' to '{cloud_path}'")
75
+ except dropbox.exceptions.ApiError as e:
76
+ upload_file_fix()
77
+
78
+ def clear_local_folder(path):
79
+ try:
80
+ for filename in os.listdir(path):
81
+ file_path = os.path.join(path, filename)
82
+ if os.path.isfile(file_path) or os.path.islink(file_path):
83
+ os.unlink(file_path)
84
+ elif os.path.isdir(file_path):
85
+ shutil.rmtree(file_path)
86
+ except Exception as e:
87
+ print(f"Failed to delete contents of {path}. Reason: {e}")
88
+
89
+ def download_folder(id):
90
+ try:
91
+ TOKEN = refresh_token_dropbox()
92
+ dbx = dropbox.Dropbox(TOKEN)
93
+ local_path = f"./user_file/{id}"
94
+ os.makedirs(local_path, exist_ok=True)
95
+ clear_local_folder(local_path)
96
+ result = dbx.files_list_folder(f"/{id}")
97
+ for entry in result.entries:
98
+ if isinstance(entry, dropbox.files.FileMetadata):
99
+ cloud_file_path = entry.path_display
100
+ file_name = os.path.basename(cloud_file_path)
101
+ local_file_path = os.path.join(local_path, file_name)
102
+ dbx.files_download_to_file(local_file_path, cloud_file_path)
103
+ print(f"Downloaded file '{file_name}' to '{local_file_path}'")
104
+ except dropbox.exceptions.ApiError as e:
105
+ print(f"Error downloading file '{id}': {e}")
106
+
107
+ def download_file_id(file_name, id):
108
+ try:
109
+ TOKEN = refresh_token_dropbox()
110
+ dbx = dropbox.Dropbox(TOKEN)
111
+ local_folder_path = f"./user_file/{id}"
112
+ os.makedirs(local_folder_path, exist_ok=True)
113
+ local_file_path = os.path.join(local_folder_path, file_name)
114
+ with open(local_file_path, "wb") as f:
115
+ metadata, response = dbx.files_download(f"/{id}/{file_name}")
116
+ f.write(response.content)
117
+ print(f"Downloaded file '{file_name}' to '{local_file_path}'")
118
+ except dropbox.exceptions.ApiError as e:
119
+ print(f"Error downloading file '{file_name}': {e}")
120
+ raise HTTPException(status_code=500, detail="Internal Server Error")
121
+
122
+ def search_and_download_file(start_char, id):
123
+ try:
124
+ TOKEN = refresh_token_dropbox()
125
+ dbx = dropbox.Dropbox(TOKEN)
126
+ result = dbx.files_list_folder(f"/{id}")
127
+ files_starting_with_char = [entry.name for entry in result.entries if entry.name.startswith(start_char)]
128
+ if len(files_starting_with_char) == 0:
129
+ print(f"No file found starting with '{start_char}' in folder '{id}'")
130
+ return
131
+ file_name = files_starting_with_char[0]
132
+ local_folder_path = f"./user_file/{id}"
133
+ os.makedirs(local_folder_path, exist_ok=True)
134
+ local_file_path = os.path.join(local_folder_path, file_name)
135
+ with open(local_file_path, "wb") as f:
136
+ metadata, response = dbx.files_download(f"/{id}/{file_name}")
137
+ f.write(response.content)
138
+ print(f"Downloaded file '{file_name}' to '{local_file_path}'")
139
+ except dropbox.exceptions.ApiError as e:
140
+ print(f"Error searching or downloading file: {e}")
141
+ raise HTTPException(status_code=500, detail="Internal Server Error")
142
+
143
+ def delete_all_files_in_folder(folder_id):
144
+ try:
145
+ TOKEN = refresh_token_dropbox()
146
+ dbx = dropbox.Dropbox(TOKEN)
147
+ result = dbx.files_list_folder(f"/{folder_id}")
148
+ for entry in result.entries:
149
+ if isinstance(entry, dropbox.files.FileMetadata):
150
+ file_path = entry.path_display
151
+ dbx.files_delete_v2(file_path)
152
+ print(f"Deleted file '{file_path}'")
153
+ print(f"All files in folder '{folder_id}' have been deleted.")
154
+ except dropbox.exceptions.ApiError as e:
155
+ print(f"Error deleting files: {e}")
function/support_function.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic.error_wrappers import ErrorWrapper
2
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
+ from service import MySQLService,LoginService,ChatService
4
+ from request import RequestMySQL,RequestLogin,RequestDefault
5
+ from auth.authentication import decodeJWT
6
+ from repository import UserRepository
7
+ from auth import authentication
8
+ from datetime import datetime, timedelta
9
+ from fastapi import Depends, HTTPException, Form, File, UploadFile
10
+ from typing import List
11
+ from service import FileService,DefaultService,LoginService
12
+ from request import RequestFile,RequestChat,RequestDefault
13
+ from fastapi import FastAPI, Request, HTTPException
14
+ from fastapi.responses import JSONResponse
15
+ from pydantic.error_wrappers import ErrorWrapper
16
+ import json
17
+ from function import support_function
18
+ from repository import UserRepository
19
+ from response import ResponseDefault as res
20
+ import re
21
+
22
+ def is_positive_integer(value):
23
+ if isinstance(value, int) and value > 0:
24
+ return True
25
+ else:
26
+ return False
27
+
28
+ def check_value_user_id_controller(user_id: str):
29
+ if user_id is None or user_id.strip() == "":
30
+ return res.ReponseError(status=400,
31
+ data=res.Message(message="user_id field is required."))
32
+ user_id = user_id.strip("'").strip('"')
33
+ try:
34
+ user_id_int = int(user_id)
35
+ except ValueError:
36
+ return res.ReponseError(status=400,
37
+ data=res.Message(message="user_id must be an integer"))
38
+
39
+ if not support_function.is_positive_integer(user_id_int):
40
+ return res.ReponseError(status=400,
41
+ data=res.Message(message="user_id must be greater than 0"))
42
+ return True
43
+
44
+ def check_value_user_id(user_id: str, current_user_email: str):
45
+ if user_id is None or user_id.strip() == "":
46
+ return res.ReponseError(status=400,
47
+ data=res.Message(message="user_id field is required."))
48
+ user_id = user_id.strip("'").strip('"')
49
+ try:
50
+ user_id_int = int(user_id)
51
+ except ValueError:
52
+ return res.ReponseError(status=400,
53
+ data=res.Message(message="user_id must be an integer"))
54
+
55
+ if not support_function.is_positive_integer(user_id_int):
56
+ return res.ReponseError(status=400,
57
+ data=res.Message(message="user_id must be greater than 0"))
58
+ email = UserRepository.getEmailUserByIdFix(user_id)
59
+ if email is None:
60
+ return res.ReponseError(status=400,
61
+ data=res.Message(message="user_id not exist"))
62
+ email = email[0]
63
+ if email != current_user_email:
64
+ return res.ReponseError(status=400,
65
+ data=res.Message(message="Sorry, you can't perform actions with this user id."))
66
+ return True
67
+
68
+ def check_value_email_controller(email: str):
69
+ if email is None or email.strip() == "":
70
+ return res.ReponseError(status = 400,
71
+ data = res.Message(message="Email is required."))
72
+ try:
73
+ int(email)
74
+ return res.ReponseError(status=400,
75
+ data=res.Message(message="Email must be a string, not a number."))
76
+ except ValueError:
77
+ pass
78
+ return True
79
+
80
+ def check_value_otp(otp: str):
81
+ if otp is None:
82
+ return res.ReponseError(status=400,
83
+ data=res.Message(message="OTP is required"))
84
+ if otp.isdigit():
85
+ return res.ReponseError(status=400,
86
+ data=res.Message(message="OTP must be a string, not a number."))
87
+ if len(otp) != 6:
88
+ return res.ReponseError(status=400,
89
+ data=res.Message(message="OTP max length is 6"))
90
+ return True
91
+
92
+ regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
93
+ def check_email(email):
94
+ if(re.fullmatch(regex, email)):
95
+ return True
96
+ else:
97
+ return False
98
+ def check_email_service(user_id: str):
99
+ email1 = UserRepository.getEmailUserByIdFix(user_id)
100
+ if email1 is None:
101
+ return res.ReponseError(
102
+ status=400,
103
+ data=res.Message(message="Id not exist")
104
+ )
105
+ email = email1[0]
106
+ if email is None:
107
+ return res.ReponseError(
108
+ status=400,
109
+ data=res.Message(message="Email is empty")
110
+ )
111
+ if check_email(email) == False:
112
+ return res.ReponseError(
113
+ status=400,
114
+ data=res.Message(message="Email invalid")
115
+ )
116
+ return email
117
+
118
+ def check_email_empty_invalid(email: str):
119
+ if email is None or email == "":
120
+ return res.ReponseError(
121
+ status=400,
122
+ data=res.Message(message="Email is empty")
123
+ )
124
+ if check_email(email) == False:
125
+ return res.ReponseError(
126
+ status=400,
127
+ data =res.Message(message="Email invalid")
128
+ )
129
+ return True
main.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Depends, Request
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.middleware.trustedhost import TrustedHostMiddleware
4
+ from controller import LoginController, FileController, MySQLController, ChatController, DefaultController, OTPController
5
+ import firebase_admin
6
+ from firebase_admin import credentials
7
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
8
+ from service import MySQLService,LoginService,ChatService
9
+ from request import RequestMySQL,RequestLogin,RequestDefault
10
+ from auth.authentication import decodeJWT
11
+ from repository import UserRepository
12
+ from auth import authentication
13
+ from datetime import datetime, timedelta
14
+ from fastapi import Depends, HTTPException, Form, File, UploadFile,Query
15
+ from typing import List,Optional
16
+ from service import FileService,DefaultService,LoginServiceF
17
+ from request import RequestFile,RequestChat,RequestDefault
18
+ from fastapi import FastAPI, Request, HTTPException
19
+ from fastapi.responses import JSONResponse
20
+ from pydantic.error_wrappers import ErrorWrapper
21
+ import json
22
+ from function import support_function
23
+ from response import ResponseDefault as res
24
+
25
+ app = FastAPI(
26
+ title="ChatBot HCMUTE",
27
+ description="Python ChatBot is intended for use in the topic Customizing chatbots. With the construction of 2 students Vo Nhu Y - 20133118 and Nguyen Quang Phuc 20133080",
28
+ swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"},
29
+ version="1.0.0",
30
+ contact={
31
+ "name": "Vo Nhu Y",
32
+ "url": "https://pychatbot1.streamlit.app",
33
+ "email": "vonhuy5112002@gmail.com",
34
+ },
35
+ license_info={
36
+ "name": "Apache 2.0",
37
+ "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
38
+ }
39
+ )
40
+ origins = [
41
+ "http://localhost:8000",
42
+ ]
43
+
44
+ app.add_middleware(
45
+ CORSMiddleware,
46
+ allow_origins=origins,
47
+ allow_credentials=True,
48
+ allow_methods=["*"],
49
+ allow_headers=["*"],
50
+ )
51
+ ALLOWED_EXTENSIONS = {'csv', 'txt', 'doc', 'docx', 'pdf', 'xlsx', 'pptx', 'json', 'md'}
52
+
53
+ def allowed_file(filename):
54
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
55
+
56
+ if not firebase_admin._apps:
57
+ cred = credentials.Certificate("firebase_certificate.json")
58
+ fred = firebase_admin.initialize_app(cred)
59
+
60
+ class JWTBearer(HTTPBearer):
61
+ def __init__(self, auto_error: bool = True):
62
+ super(JWTBearer, self).__init__(auto_error=auto_error)
63
+
64
+ async def __call__(self, request: Request):
65
+ credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
66
+ if credentials:
67
+ if credentials.scheme != "Bearer":
68
+ raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
69
+ if not self.verify_accesstoken(credentials.credentials):
70
+ raise HTTPException(status_code=403, detail="Token does not exist")
71
+ if not self.verify_jwt(credentials.credentials):
72
+ raise HTTPException(status_code=403, detail="Invalid token or expired token.")
73
+ return credentials.credentials
74
+ else:
75
+ raise HTTPException(status_code=401, detail="Invalid authorization code.")
76
+
77
+ def verify_accesstoken(self, jwtoken: str) -> bool:
78
+ check = LoginService.check_token_is_valid(jwtoken)
79
+ return check
80
+ def verify_jwt(self, jwtoken: str) -> bool:
81
+ try:
82
+ payload = decodeJWT(jwtoken)
83
+ email_encode = payload.get('sub')
84
+ self.email = authentication.str_decode(email_encode)
85
+ return True
86
+ except Exception as e:
87
+ print(e)
88
+ return False
89
+
90
+ def get_current_user_email(credentials: str = Depends(JWTBearer())):
91
+ try:
92
+ payload = decodeJWT(credentials)
93
+ email_encode = payload.get('sub')
94
+ email = authentication.str_decode(email_encode)
95
+ return email
96
+ except Exception as e:
97
+ print(e)
98
+ raise HTTPException(status_code=403, detail="Invalid token or expired token.")
99
+
100
+ @app.get("/api/mysql/render_chat_history",dependencies=[Depends(JWTBearer())], tags=["MySQL"])
101
+ async def override_render_chat(user_id: Optional[str] = Query(None), current_user_email: str = Depends(get_current_user_email)):
102
+ check = support_function.check_value_user_id(user_id, current_user_email)
103
+ if check != True:
104
+ return check
105
+ request = RequestMySQL.RequestRenderChatHistory(user_id=user_id)
106
+ return MySQLService.render_chat_history(request)
107
+
108
+ @app.put("/api/mysql/edit_chat/", dependencies=[Depends(JWTBearer())], tags=["MySQL"])
109
+ async def override_edit_chat(request: RequestMySQL.RequestEditNameChat, current_user_email: str = Depends(get_current_user_email)):
110
+ user_id = request.user_id
111
+ check = support_function.check_value_user_id(user_id, current_user_email)
112
+ if check != True:
113
+ return check
114
+ name_new = request.name_new
115
+ if name_new is None or name_new.strip() == "":
116
+ raise HTTPException(status_code=400, detail="name_new field is required.")
117
+ name_old = request.name_old
118
+ if name_old is None or name_old.strip() == "":
119
+ raise HTTPException(status_code=400, detail="name_old field is required.")
120
+ return MySQLService.edit_chat(request)
121
+
122
+ @app.delete("/api/mysql/delete_chat/", dependencies=[Depends(JWTBearer())], tags=["MySQL"])
123
+ async def override_delete_chat(request: RequestMySQL.RequestDeleteChat, current_user_email: str = Depends(get_current_user_email)):
124
+ user_id = request.user_id
125
+ check = support_function.check_value_user_id(user_id, current_user_email)
126
+ if check is not True:
127
+ return check
128
+ chat_name= request.chat_name
129
+ if chat_name is None or chat_name.strip() == "":
130
+ raise HTTPException(status_code=400, detail="chat_name field is required.")
131
+ return MySQLService.delete_chat(request)
132
+
133
+
134
+ @app.get("/load_chat_history",dependencies=[Depends(JWTBearer())] ,tags=["MySQL"])
135
+ async def override_load_chat(chat_id: Optional[str] = Query(None), user_id: Optional[str] = Query(None), current_user_email: str = Depends(get_current_user_email)):
136
+ check = support_function.check_value_user_id(user_id, current_user_email)
137
+ if check is not True:
138
+ return check
139
+ if chat_id is None or chat_id.strip() == "":
140
+ return res.ReponseError(status=400,
141
+ data=res.Message(message="Chat id field is required."))
142
+ chat_id = chat_id.strip("'").strip('"')
143
+ try:
144
+ chat_id_int = int(chat_id)
145
+ except ValueError:
146
+ return res.ReponseError(status=400,
147
+ data=res.Message(message="Value must be an integer"))
148
+ if not support_function.is_positive_integer(chat_id_int):
149
+ return res.ReponseError(status=400,
150
+ data=res.Message(message="Value must be greater than 0"))
151
+ request = RequestMySQL.RequestLoadChatHistory(chat_id=chat_id)
152
+ return MySQLService.load_chat_history(request)
153
+
154
+ @app.get("/info_user",dependencies=[Depends(JWTBearer())], tags=["Default"])
155
+ async def override_get_user(user_id: Optinal[str] = Query(None)):
156
+ check = support_function.check_value_user_id_controller(user_id)
157
+ if check is not True:
158
+ return check
159
+ request = RequestDefault.RequestInfoUser(user_id=user_id)
160
+ return DefaultService.info_user(request)
161
+
162
+ @app.post("/api/users/update_user_info", dependencies=[Depends(JWTBearer())], tags=["Login"])
163
+ async def override_update_user_info(request: RequestLogin.RequestUpdateUserInfo, current_user_email: str = Depends(get_current_user_email)):
164
+ user_id = request.user_id
165
+ check = support_function.check_value_user_id(user_id, current_user_email)
166
+ if check != True:
167
+ return check
168
+ uid = request.uid
169
+ email = request.email
170
+ display_name = request.display_name
171
+ photo_url = request.photo_url
172
+ if uid is None or uid.strip() == "":
173
+ raise HTTPException(status_code=400, detail="uid field is required.")
174
+ if email is None or email.strip() == "":
175
+ return res.ReponseError(status=400,
176
+ data=res.Message(message="email field is required."))
177
+ if display_name is None or display_name.strip() == "":
178
+ return res.ReponseError(status=400,
179
+ data=res.Message(message="display_name field is required."))
180
+ if photo_url is None or photo_url.strip() == "":
181
+ return res.ReponseError(status=400,
182
+ data=res.Message(message="photo_url field is required."))
183
+ return LoginService.update_user_info(request)
184
+
185
+ @app.put('/api/users/change_password', dependencies=[Depends(JWTBearer())], tags=["Login"])
186
+ async def override_reset_password_firebase(request: RequestLogin.RequestChangePassword, current_user_email: str = Depends(get_current_user_email)):
187
+ user_id = request.user_id
188
+ check = support_function.check_value_user_id(user_id, current_user_email)
189
+ if check != True:
190
+ return check
191
+ new_password = request.new_password
192
+ current_password = request.current_password
193
+ if new_password is None or new_password.strip() == "":
194
+ return res.ReponseError(status=400,
195
+ data=res.Message(message="new_password field is required."))
196
+ if current_password is None or current_password.strip() == "":
197
+ return res.ReponseError(status=400,
198
+ data=res.Message(message="current_password field is required."))
199
+ return LoginService.change_password(request)
200
+ @app.delete("/api/file/delete_all_file/", dependencies=[Depends(JWTBearer())], tags=["File"])
201
+ async def override_delete_folder(request: RequestFile.RequestDeleteAllFile, current_user_email: str = Depends(get_current_user_email)):
202
+ check = support_function.check_value_user_id(request.user_id, current_user_email)
203
+ if check != True:
204
+ return check
205
+ return FileService.deleteAllFile(request)
206
+
207
+ # @app.get("/api/file/list_name_files/", dependencies=[Depends(JWTBearer())], tags=["File"])
208
+ # async def override_get_list_name_files(user_id: str , current_user_email: str = Depends(get_current_user_email)):
209
+ # check = support_function.check_value_user_id(user_id, current_user_email)
210
+ # if check != True:
211
+ # return check
212
+ # request = RequestFile.RequestGetNameFile(user_id=user_id)
213
+ # return FileService.listNameFiles(request)
214
+
215
+ @app.delete("/api/file/delete_one_file/", dependencies=[Depends(JWTBearer())], tags=["File"])
216
+ async def override_delete_one_file(request: RequestFile.RequestDeleteFile, current_user_email: str = Depends(get_current_user_email)):
217
+ user_id = request.user_id
218
+ check = support_function.check_value_user_id(user_id, current_user_email)
219
+ if check != True:
220
+ return check
221
+ name_file = request.name_file
222
+ if name_file is None or name_file.strip() == "":
223
+ return res.ReponseError(status=400,
224
+ data=res.Message(message="name_file is required."))
225
+ return FileService.deleteFile(request)
226
+
227
+ @app.post("/api/file/chatbot/download_folder/", dependencies=[Depends(JWTBearer())], tags=["File"])
228
+ async def override_download_folder_from_dropbox(request: RequestFile.RequestDownLoadFolder, current_user_email: str = Depends(get_current_user_email)):
229
+ user_id = request.user_id
230
+ check = support_function.check_value_user_id(user_id, current_user_email)
231
+ if check != True:
232
+ return check
233
+ return FileService.download_folder(request)
234
+
235
+ @app.post("/api/file/chatbot/download_files/", dependencies=[Depends(JWTBearer())], tags=["File"])
236
+ async def override_download_file_by_id(request: RequestFile.RequestDownLoadFile, current_user_email: str = Depends(get_current_user_email)):
237
+ user_id = request.user_id
238
+ check = support_function.check_value_user_id(user_id, current_user_email)
239
+ if check != True:
240
+ return check
241
+ return FileService.download_file(request)
242
+
243
+ @app.post("/api/file/upload_files/", dependencies=[Depends(JWTBearer())], tags=["File"])
244
+ async def override_upload_files_dropbox(
245
+ user_id: str = Form(None),
246
+ files: List[UploadFile] = File(None),
247
+ current_user_email: str = Depends(get_current_user_email)
248
+ ):
249
+ check = support_function.check_value_user_id(user_id, current_user_email)
250
+ if check != True:
251
+ return check
252
+ request = RequestFile.RequestUploadFile(files=files, user_id=user_id)
253
+ return FileService.upload_files(request)
254
+
255
+ @app.post("/api/chat/chatbot/query/", dependencies=[Depends(JWTBearer())], tags=["Chatbot"])
256
+ async def override_handle_query2_upgrade_old(request: Request, user_id: str = Form(None), text_all: str = Form(...), question: str = Form(None), chat_name: str = Form(None), current_user_email: str = Depends(get_current_user_email)):
257
+ check = support_function.check_value_user_id(user_id, current_user_email)
258
+ if check != True:
259
+ return check
260
+ request = RequestChat.RequestQuery2UpgradeOld(user_id=user_id, text_all=text_all, question=question, chat_name=chat_name)
261
+ return ChatService.query2_upgrade_old(request)
262
+
263
+ @app.get("/api/chat/chatbot/extract_file/", dependencies=[Depends(JWTBearer())], tags=["Chatbot"])
264
+ async def override_extract_file(user_id: Optional[str] = Query(None), current_user_email: str = Depends(get_current_user_email)):
265
+ check = support_function.check_value_user_id(user_id,current_user_email)
266
+ if check != True:
267
+ return check
268
+ request = RequestChat.RequestExtractFile(user_id=user_id)
269
+ return ChatService.extract_file(request)
270
+
271
+ @app.get("/api/chat/chatbot/generate_question/", dependencies=[Depends(JWTBearer())], tags=["Chatbot"])
272
+ async def override_generate_question(user_id: Optional[str] = Query(None) , current_user_email: str = Depends(get_current_user_email)):
273
+ check = support_function.check_value_user_id(user_id,current_user_email)
274
+ if check != True:
275
+ return check
276
+ request = RequestChat.RequestGenerateQuestion(user_id=user_id)
277
+ return ChatService.generate_question(request)
278
+
279
+ @app.post("/api/default/upload_image/", dependencies=[Depends(JWTBearer())], tags=["Default"])
280
+ async def override_upload_image(user_id: str = Form(None), file: UploadFile = File(...),current_user_email: str = Depends(get_current_user_email)):
281
+ check = support_function.check_value_user_id(user_id,current_user_email)
282
+ if check != True:
283
+ return check
284
+ request = RequestDefault.RequestUpLoadImage(user_id=user_id, files=file)
285
+ return DefaultService.upload_image_service(request)
286
+
287
+ app.include_router(MySQLController.router, prefix="/api/mysql")
288
+ app.include_router(LoginController.router, prefix="/api/users")
289
+ app.include_router(FileController.router,prefix="/api/file")
290
+ app.include_router(ChatController.router,prefix="/api/chat")
291
+ app.include_router(DefaultController.router,prefix="/api/default")
292
+
293
+ routes_to_override = {
294
+ "/api/mysql/render_chat_history":{"GET"},
295
+ "/api/mysql/load_chat_history":{"GET"},
296
+ "/api/mysql/edit_chat/": {"PUT"},
297
+ "/api/mysql/delete_chat/": {"DELETE"},
298
+ "/api/users/update_user_info" :{"POST"},
299
+ "/api/users/change_password" :{"PUT"},
300
+ "/api/file/delete_all_file/" :{"DELETE"},
301
+ "/api/file/delete_one_file/" :{"DELETE"},
302
+ "/api/file/chatbot/download_folder/" :{"POST"},
303
+ "/api/file/chatbot/download_files/" :{"POST"},
304
+ "/api/file/upload_files/":{"POST"},
305
+ "/api/chat/query2_upgrade/":{"POST"},
306
+ "/api/chat/chatbot/query/" : {"POST"},
307
+ "/api/chat/chatbot/extract_file/":{"GET"},
308
+ "/api/chat/chatbot/generate_question/":{"GET"},
309
+ "/api/default/upload_image/":{"POST"}
310
+ }
311
+
312
+ app.router.routes = [
313
+ route for route in app.router.routes
314
+ if not (
315
+ route.path in routes_to_override and
316
+ route.methods.intersection(routes_to_override[route.path])
317
+ )
318
+ ]
319
+
320
+ app.add_api_route("/api/mysql/render_chat_history", override_render_chat, methods=["GET"], dependencies=[Depends(JWTBearer())], tags=["MySQL"])
321
+ app.add_api_route("/api/mysql/load_chat_history/", override_load_chat, methods=["GET"], dependencies=[Depends(JWTBearer())], tags=["MySQL"])
322
+ app.add_api_route("/api/mysql/edit_chat/", override_edit_chat, methods=["PUT"], dependencies=[Depends(JWTBearer())], tags=["MySQL"])
323
+ app.add_api_route("/api/mysql/delete_chat/", override_delete_chat, methods=["DELETE"], dependencies=[Depends(JWTBearer())], tags=["MySQL"])
324
+ app.add_api_route("/api/users/update_user_info",override_update_user_info,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["Login"])
325
+ app.add_api_route("/api/users/change_password",override_reset_password_firebase,methods=["PUT"],dependencies=[Depends(JWTBearer())], tags=["Login"])
326
+ app.add_api_route("/api/file/delete_all_file/",override_delete_folder,methods=["DELETE"],dependencies=[Depends(JWTBearer())], tags=["File"])
327
+ # app.add_api_route("/api/file/list_name_files/",override_get_list_name_files,methods=["GET"],dependencies=[Depends(JWTBearer())], tags=["File"])
328
+ app.add_api_route("/api/file/delete_one_file/",override_delete_one_file,methods=["DELETE"],dependencies=[Depends(JWTBearer())], tags=["File"])
329
+ app.add_api_route("/api/file/chatbot/download_folder/",override_download_folder_from_dropbox,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["File"])
330
+ app.add_api_route("/api/file/chatbot/download_files/",override_download_file_by_id,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["File"])
331
+ app.add_api_route("/api/file/upload_files/",override_upload_files_dropbox,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["File"])
332
+ app.add_api_route("/api/chat/chatbot/query/",override_handle_query2_upgrade_old,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["Chat"])
333
+ app.add_api_route("/api/chat/chatbot/extract_file/",override_extract_file,methods=["GET"],dependencies=[Depends(JWTBearer())], tags=["Chat"])
334
+ app.add_api_route("/api/chat/chatbot/generate_question/",override_generate_question,methods=["GET"],dependencies=[Depends(JWTBearer())], tags=["Chat"])
335
+ app.add_api_route("/api/default/upload_image/",override_upload_image,methods=["POST"],dependencies=[Depends(JWTBearer())], tags=["Default"])
336
+ app.include_router(OTPController.router, tags = ["OTP"], prefix="/api/otp")
repository/ChatHistoryRepository.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ import sys
3
+ import os
4
+ app_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
5
+ sys.path.insert(0, app_path)
6
+ from entity import Database_Entity
7
+ from repository import ConfigDatabase as cf
8
+ chat_history = Database_Entity.ChatHistory
9
+ users = Database_Entity.User
10
+ detail_chat = Database_Entity.DetailChat
11
+
12
+ def getIdChatHistoryByUserIdAndNameChat(user_id:int,name_old :str) -> chat_history.id:
13
+ try:
14
+ engine = cf.get_db_engine()
15
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
16
+ with Session() as session:
17
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
18
+ chat_id = session.query(chat_history.id).filter(chat_history.email == email, chat_history.name_chat == name_old).scalar()
19
+ session.commit()
20
+ if chat_id:
21
+ session.close()
22
+ return chat_id
23
+ else:
24
+ session.close()
25
+ return None
26
+ except:
27
+ engine = cf.get_db_engine1()
28
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
29
+ with Session() as session:
30
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
31
+ chat_id = session.query(chat_history.id).filter(chat_history.email == email, chat_history.name_chat == name_old).scalar()
32
+ session.commit()
33
+ if chat_id:
34
+ session.close()
35
+ return chat_id
36
+ else:
37
+ session.close()
38
+ return None
39
+
40
+ def getIdChatHistoryByUserIdAndNameChatNew(user_id:int,name_old :str) -> chat_history.id:
41
+ try:
42
+ engine = cf.get_db_engine()
43
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
44
+ with Session() as session:
45
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
46
+ chat_id = session.query(chat_history.id).filter(chat_history.email == email, chat_history.name_chat == name_old).scalar()
47
+ session.commit()
48
+ if chat_id:
49
+ session.close()
50
+ return chat_id
51
+ else:
52
+ session.close()
53
+ return None
54
+ except:
55
+ engine = cf.get_db_engine1()
56
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
57
+ with Session() as session:
58
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
59
+ chat_id = session.query(chat_history.id).filter(chat_history.email == email,
60
+ chat_history.name_chat == name_old).scalar()
61
+ session.commit()
62
+ if chat_id:
63
+ session.close()
64
+ return chat_id
65
+ else:
66
+ session.close()
67
+ return None
68
+
69
+ def updateNameChatHistory(user_id: int,name_old :str,name_new:str) -> bool:
70
+ try:
71
+ engine = cf.get_db_engine1()
72
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
73
+ with Session() as session:
74
+ try:
75
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
76
+ session.query(chat_history).filter(chat_history.email == email,chat_history.name_chat == name_old).update({chat_history.name_chat: name_new})
77
+ session.commit()
78
+ session.close()
79
+ return True
80
+ except:
81
+ session.rollback()
82
+ session.close()
83
+ return False
84
+ except:
85
+ engine = cf.get_db_engine()
86
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
87
+ with Session() as session:
88
+ try:
89
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
90
+ session.query(chat_history).filter(chat_history.email == email,chat_history.name_chat == name_old).update({chat_history.name_chat: name_new})
91
+ session.commit()
92
+ session.close()
93
+ return True
94
+ except:
95
+ session.rollback()
96
+ session.close()
97
+ return False
98
+
99
+ def deleteChatHistory(user_id,chat_name: str) -> bool:
100
+ try:
101
+ try:
102
+ engine = cf.get_db_engine1()
103
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
104
+ with Session() as session:
105
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
106
+ session.query(chat_history).filter(chat_history.email == email, chat_history.name_chat == chat_name).delete()
107
+ session.commit()
108
+ session.close()
109
+ return True
110
+ except Exception as e:
111
+ session.rollback()
112
+ session.close()
113
+ return False
114
+ except:
115
+ try:
116
+ engine = cf.get_db_engine()
117
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
118
+ with Session() as session:
119
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
120
+ session.query(chat_history).filter(chat_history.email == email, chat_history.name_chat == chat_name).delete()
121
+ session.commit()
122
+ session.close()
123
+ return True
124
+ except Exception as e:
125
+ session.rollback()
126
+ session.close()
127
+ return False
128
+
129
+ def getChatHistoryByEmail(email: str) -> chat_history:
130
+ try:
131
+ engine = cf.get_db_engine1()
132
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
133
+ with Session() as session:
134
+ chat_history1 = session.query(chat_history).filter(chat_history.email == email)
135
+ if chat_history1:
136
+ session.commit()
137
+ session.close()
138
+ return chat_history1
139
+ session.close()
140
+ return None
141
+ except:
142
+ engine = cf.get_db_engine()
143
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
144
+ with Session() as session:
145
+ chat_history1 = session.query(chat_history).filter(chat_history.email == email)
146
+ if chat_history1:
147
+ session.commit()
148
+ session.close()
149
+ return chat_history1
150
+ session.close()
151
+ return None
152
+
153
+ from sqlalchemy.orm import aliased
154
+
155
+ def getChatHistoryByChatIdAndUserId(chat_id: int, user_id: int) -> chat_history:
156
+ try:
157
+ engine = cf.get_db_engine()
158
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
159
+ with Session() as session:
160
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
161
+ chat_history1 = session.query(chat_history).filter(chat_history.id == chat_id,chat_history.email == email).one_or_none()
162
+ if chat_history1:
163
+ session.commit()
164
+ session.close()
165
+ return True
166
+ session.close()
167
+ return None
168
+ except:
169
+ engine = cf.get_db_engine1()
170
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
171
+ with Session() as session:
172
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
173
+ chat_history1 = session.query(chat_history).filter(chat_history.email == email)
174
+ if chat_history1:
175
+ session.commit()
176
+ session.close()
177
+ return True
178
+ session.close()
179
+ return None
180
+
181
+ def getChatHistoryById(id: int) -> chat_history:
182
+ try:
183
+ engine = cf.get_db_engine()
184
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
185
+ with Session() as session:
186
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
187
+ chat_history1 = session.query(chat_history).filter(chat_history.email == email)
188
+ if chat_history1:
189
+ session.commit()
190
+ session.close()
191
+ return chat_history1
192
+ session.close()
193
+ return None
194
+ except:
195
+ engine = cf.get_db_engine1()
196
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
197
+ with Session() as session:
198
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
199
+ chat_history1 = session.query(chat_history).filter(chat_history.email == email)
200
+ if chat_history1:
201
+ session.commit()
202
+ session.close()
203
+ return chat_history1
204
+ session.close()
205
+ return None
206
+
207
+ def addChatHistory(user_id: str, name_chat:str)->None:
208
+ try:
209
+ engine = cf.get_db_engine()
210
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
211
+ with Session() as session:
212
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
213
+ new_user = chat_history(
214
+ email = email,
215
+ name_chat = name_chat
216
+ )
217
+ session.add(new_user)
218
+ session.commit()
219
+ session.close()
220
+ except:
221
+ engine = cf.get_db_engine1()
222
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
223
+ with Session() as session:
224
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
225
+ new_user = chat_history(
226
+ email = email,
227
+ name_chat = name_chat
228
+ )
229
+ session.add(new_user)
230
+ session.commit()
231
+ session.close()
repository/ConfigDatabase.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import create_engine, URL
2
+ from sqlalchemy.orm import DeclarativeBase
3
+ Base = DeclarativeBase()
4
+ from sqlalchemy.engine import create_engine, URL
5
+ from dotenv import load_dotenv
6
+ import os
7
+ load_dotenv()
8
+ MYSQL_USER_NAME=os.getenv('MYSQL_USER_NAME')
9
+ MYSQL_PASSWORD=os.getenv('MYSQL_PASSWOR')
10
+ MYSQL_PORT=os.getenv('MYSQL_PORT')
11
+ MYSQL_DATABASE=os.getenv('MYSQL_DATABASE')
12
+ MYSQL_HOST=os.getenv('MYSQL_HOST')
13
+ #IF USE DOCKER HOST = host.docker.internal
14
+ def get_db_engine():
15
+ dsn = URL.create(
16
+ drivername="mysql+pymysql",
17
+ username=MYSQL_USER_NAME,
18
+ password=MYSQL_PASSWORD,
19
+ host=MYSQL_HOST,
20
+ port=MYSQL_PORT,
21
+ database=MYSQL_DATABASE
22
+ )
23
+ connect_args = {}
24
+ return create_engine(
25
+ dsn,
26
+ connect_args=connect_args,
27
+ )
28
+
29
+ def get_db_engine1():
30
+ dsn = URL.create(
31
+ drivername="mysql+pymysql",
32
+ username=MYSQL_USER_NAME,
33
+ password=MYSQL_PASSWORD,
34
+ host=MYSQL_HOST,
35
+ port=MYSQL_PORT,
36
+ database=MYSQL_DATABASE
37
+ )
38
+ connect_args = {}
39
+ return create_engine(
40
+ dsn,
41
+ connect_args=connect_args,
42
+ )
repository/DetailChatRepository.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ from entity import Database_Entity
3
+ from repository import ConfigDatabase as cf
4
+ detail_chat = Database_Entity.DetailChat
5
+ chat_history = Database_Entity.ChatHistory
6
+
7
+ def getListDetailChatByChatId(chat_id: int) -> detail_chat:
8
+ try:
9
+ engine = cf.get_db_engine1()
10
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11
+ with Session() as session:
12
+ chat_record= session.query(detail_chat).filter(detail_chat.chat_id == chat_id)
13
+ session.commit()
14
+ if chat_record:
15
+ session.close()
16
+ return chat_record
17
+ else:
18
+ session.close()
19
+ return None
20
+ except:
21
+ engine = cf.get_db_engine()
22
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
23
+ with Session() as session:
24
+ chat_record= session.query(detail_chat).filter(detail_chat.chat_id == chat_id)
25
+ session.commit()
26
+ if chat_record:
27
+ session.close()
28
+ return chat_record
29
+ else:
30
+ session.close()
31
+ return None
32
+
33
+ def addDetailChat(chat_id: int, YouMessage: str, AiMessage: str, data_relevant: str, source_file: str) -> None:
34
+ try:
35
+ engine = cf.get_db_engine()
36
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
37
+ with Session() as session:
38
+ new_user = detail_chat(
39
+ chat_id = chat_id,
40
+ YouMessage = YouMessage,
41
+ AiMessage = AiMessage,
42
+ data_relevant = data_relevant,
43
+ source_file = source_file
44
+ )
45
+ session.add(new_user)
46
+ session.commit()
47
+ return new_user.id
48
+ session.close()
49
+ except:
50
+ engine = cf.get_db_engine1()
51
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
52
+ with Session() as session:
53
+ new_user = detail_chat(
54
+ chat_id=chat_id,
55
+ YouMessage=YouMessage,
56
+ AiMessage=AiMessage,
57
+ data_relevant=data_relevant,
58
+ source_file=source_file
59
+ )
60
+ session.add(new_user)
61
+ session.commit()
62
+ return new_user.id
63
+ session.close()
64
+
65
+ def getDetailChatByChatId(id: int) -> detail_chat:
66
+ try:
67
+ engine = cf.get_db_engine()
68
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
69
+ with Session() as session:
70
+ try:
71
+ chat = session.query(detail_chat).filter(detail_chat.id == id).one_or_none()
72
+ return chat
73
+ except:
74
+ session.close()
75
+ return False
76
+ except:
77
+ engine = cf.get_db_engine1()
78
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
79
+ with Session() as session:
80
+ try:
81
+ chat = session.query(detail_chat.id,detail_chat.data_relevant,detail_chat.source_file).filter(detail_chat.id == id).one_or_none()
82
+ session.commit()
83
+ session.close()
84
+ return chat
85
+ except:
86
+ session.close()
87
+ return False
88
+
89
+ def delete_chat_detail(chat_name: str) -> bool:
90
+ try:
91
+ engine = cf.get_db_engine()
92
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
93
+ with Session() as session:
94
+ try:
95
+ session.query(detail_chat).filter(detail_chat.chat_id == chat_history.id).filter(chat_history.name_chat == chat_name).delete(synchronize_session=False)
96
+ session.commit()
97
+ session.close()
98
+ return True
99
+ except:
100
+ session.close()
101
+ return False
102
+ except:
103
+ engine = cf.get_db_engine1()
104
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
105
+ with Session() as session:
106
+ try:
107
+ session.query(detail_chat).filter(detail_chat.chat_id == chat_history.id).filter(chat_history.name_chat == chat_name).delete(synchronize_session=False)
108
+ session.commit()
109
+ session.close()
110
+ return True
111
+ except:
112
+ session.close()
113
+ return False
repository/OTPRepository.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ from entity import Database_Entity
3
+ from repository import ConfigDatabase as cf
4
+ otp_user = Database_Entity.OTP
5
+
6
+ def getOtpByEmail(email: str) -> otp_user:
7
+ try:
8
+ engine = cf.get_db_engine()
9
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
10
+ with Session() as session:
11
+ user_record= session.query(otp_user).filter(otp_user.email == email).one_or_none()
12
+ if user_record:
13
+ session.close()
14
+ return user_record
15
+ else:
16
+ session.close()
17
+ return None
18
+ except:
19
+ engine = cf.get_db_engine1()
20
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
21
+ with Session() as session:
22
+ user_record= session.query(otp_user).filter(otp_user.email == email).one_or_none()
23
+ if user_record:
24
+ session.close()
25
+ return user_record
26
+ else:
27
+ session.close()
28
+ return None
29
+
30
+ def addOTP(email: str, otp: str) -> None:
31
+ try:
32
+ engine = cf.get_db_engine()
33
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
34
+ with Session() as session:
35
+ otp_record = session.query(otp_user).filter_by(email=email).first()
36
+ if otp_record:
37
+ session.delete(otp_record)
38
+ session.commit()
39
+ new_user = otp_user(
40
+ email = email,
41
+ otp= otp
42
+ )
43
+ session.add(new_user)
44
+ session.commit()
45
+ session.close()
46
+ except:
47
+ engine = cf.get_db_engine1()
48
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
49
+ with Session() as session:
50
+ otp_record = session.query(otp_user).filter_by(email=email).first()
51
+ if otp_record:
52
+ session.delete(otp_record)
53
+ session.commit()
54
+ new_user = otp_user(
55
+ email = email,
56
+ otp= otp
57
+ )
58
+ session.add(new_user)
59
+ session.commit()
60
+ session.close()
61
+
62
+ def deleteOTP(email: str, otp:str) -> None:
63
+ try:
64
+ engine = cf.get_db_engine()
65
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
66
+ with Session() as session:
67
+ otp_record = session.query(otp_user).filter_by(email=email, otp=otp).first()
68
+ if otp_record:
69
+ session.delete(otp_record)
70
+ session.commit()
71
+ except:
72
+ engine = cf.get_db_engine1()
73
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
74
+ with Session() as session:
75
+ otp_record = session.query(otp_user).filter_by(email=email, otp=otp).first()
76
+ if otp_record:
77
+ session.delete(otp_record)
78
+ session.commit()
repository/UserInfoRepository.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ from entity import Database_Entity
3
+ from repository import ConfigDatabase as cf
4
+ user_info = Database_Entity.UserInfo
5
+ users = Database_Entity.User
6
+ def getUserInfo(user_id: int) -> user_info:
7
+ try:
8
+ engine = cf.get_db_engine()
9
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
10
+ with Session() as session:
11
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
12
+ user_record= session.query(user_info).filter(user_info.email == email).one_or_none()
13
+ if user_record:
14
+ session.close()
15
+ return user_record
16
+ else:
17
+ session.close()
18
+ return None
19
+ except:
20
+ engine = cf.get_db_engine1()
21
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
22
+ with Session() as session:
23
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()[0]
24
+ user_record= session.query(user_info).filter(user_info.email == email).one_or_none()
25
+ if user_record:
26
+ session.close()
27
+ return user_record
28
+ else:
29
+ session.close()
30
+ return None
31
+
32
+ def getUserInfoByEmail(email:str) -> user_info:
33
+ try:
34
+ engine = cf.get_db_engine()
35
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
36
+ with Session() as session:
37
+ user_record= session.query(user_info).filter(user_info.email == email).one_or_none()
38
+ if user_record:
39
+ session.close()
40
+ return user_record
41
+ else:
42
+ session.close()
43
+ return None
44
+ except:
45
+ engine = cf.get_db_engine1()
46
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
47
+ with Session() as session:
48
+ user_record= session.query(user_info).filter(user_info.email == email).one_or_none()
49
+ if user_record:
50
+ session.close()
51
+ return user_record
52
+ else:
53
+ session.close()
54
+ return None
55
+
56
+ def addUserInfo(uid: str, email: str, display_name: str, photo_url: str) -> None:
57
+ try:
58
+ engine = cf.get_db_engine()
59
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
60
+ with Session() as session:
61
+ new_user = user_info(
62
+ uid = uid,
63
+ email = email,
64
+ display_name = display_name,
65
+ photo_url = photo_url
66
+ )
67
+ session.add(new_user)
68
+ session.commit()
69
+ session.close()
70
+ except:
71
+ engine = cf.get_db_engine1()
72
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
73
+ with Session() as session:
74
+ new_user = user_info(
75
+ uid = uid,
76
+ email = email,
77
+ display_name = display_name,
78
+ photo_url = photo_url
79
+ )
80
+ session.add(new_user)
81
+ session.commit()
82
+ session.close()
83
+
84
+ def updateUserInfo(user_id, uid: str, email: str, display_name: str, photo_url: str) -> None:
85
+ try:
86
+ engine = cf.get_db_engine()
87
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
88
+ with Session() as session:
89
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()
90
+ user_update= session.query(user_info).filter(user_info.email == email).one_or_none()
91
+ if user_update is not None:
92
+ user_update.uid = uid,
93
+ user_update.display_name = display_name,
94
+ user_update.photo_url = photo_url
95
+ session.commit()
96
+ session.close()
97
+ except:
98
+ engine = cf.get_db_engine1()
99
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
100
+ with Session() as session:
101
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()
102
+ user_update= session.query(user_info).filter(user_info.email == email).one_or_none()
103
+ if user_update is not None:
104
+ user_update.uid = uid,
105
+ user_update.display_name = display_name,
106
+ user_update.photo_url = photo_url
107
+ session.commit()
108
+ session.close()
109
+
110
+ def updateImage(user_id, photo_url: str) -> None:
111
+ try:
112
+ engine = cf.get_db_engine()
113
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
114
+ with Session() as session:
115
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()
116
+ user_update= session.query(user_info).filter(user_info.email == email).one_or_none()
117
+ if user_update is not None:
118
+ user_update.photo_url = photo_url
119
+ session.commit()
120
+ session.close()
121
+ except:
122
+ engine = cf.get_db_engine1()
123
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
124
+ with Session() as session:
125
+ email = session.query(users.email).filter(users.id == user_id).one_or_none()
126
+ user_update = session.query(user_info).filter(user_info.email == email).one_or_none()
127
+ if user_update is not None:
128
+ user_update.photo_url = photo_url
129
+ session.commit()
130
+ session.close()
repository/UserLoginRepository.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ from entity import Database_Entity
3
+ from repository import ConfigDatabase as cf
4
+ user_login = Database_Entity.UserLogin
5
+ users = Database_Entity.User
6
+
7
+ def getUserLogin(email: str) -> user_login:
8
+ try:
9
+ engine = cf.get_db_engine()
10
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11
+ with Session() as session:
12
+ user_record = session.query(user_login).filter(user_login.user_email == email).one_or_none()
13
+ if user_record:
14
+ session.close()
15
+ return user_record
16
+ else:
17
+ session.close()
18
+ return None
19
+ except:
20
+ engine = cf.get_db_engine1()
21
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
22
+ with Session() as session:
23
+ user_record = session.query(user_login).filter(user_login.user_email == email).one_or_none()
24
+ if user_record:
25
+ session.close()
26
+ return user_record
27
+ else:
28
+ session.close()
29
+ return None
30
+
31
+ def getUserLoginById(id: int) -> user_login:
32
+ try:
33
+ engine = cf.get_db_engine()
34
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
35
+ with Session() as session:
36
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
37
+ user_record = session.query(user_login).filter(user_login.user_email == email).one_or_none()
38
+ if user_record:
39
+ session.close()
40
+ return user_record
41
+ else:
42
+ session.close()
43
+ return None
44
+ except:
45
+ engine = cf.get_db_engine1()
46
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
47
+ with Session() as session:
48
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
49
+ user_record = session.query(user_login).filter(user_login.user_email == email).one_or_none()
50
+ if user_record:
51
+ session.close()
52
+ return user_record
53
+ else:
54
+ session.close()
55
+ return None
56
+
57
+ def addUserLogin(user_email: str, session_id : str) -> None:
58
+ try:
59
+ engine = cf.get_db_engine()
60
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
61
+ with Session() as session:
62
+ new_user = user_login(
63
+ user_email = user_email,
64
+ user_session_id = session_id
65
+ )
66
+ session.add(new_user)
67
+ session.commit()
68
+ session.close()
69
+ except:
70
+ engine = cf.get_db_engine1()
71
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
72
+ with Session() as session:
73
+ new_user = user_login(
74
+ user_email = user_email,
75
+ user_session_id = session_id
76
+ )
77
+ session.add(new_user)
78
+ session.commit()
79
+ session.close()
80
+
81
+
82
+ def updateUserLogin(email: str, session_id : str ) -> None:
83
+ try:
84
+ engine = cf.get_db_engine()
85
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
86
+ with Session() as session:
87
+ user_update= session.query(user_login).filter(user_login.user_email == email).one_or_none()
88
+ if user_update is not None:
89
+ user_update.user_session_id = session_id
90
+ session.commit()
91
+ session.close()
92
+ except:
93
+ engine = cf.get_db_engine1()
94
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
95
+ with Session() as session:
96
+ user_update= session.query(user_login).filter(user_login.user_email == email).one_or_none()
97
+ if user_update is not None:
98
+ user_update.user_session_id = session_id
99
+ session.commit()
100
+ session.close()
101
+
102
+ def getUserSessionIdByUserEmail(id: int) -> user_login:
103
+ try:
104
+ engine = cf.get_db_engine()
105
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
106
+ with Session() as session:
107
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
108
+ session.commit()
109
+ user_record= session.query(user_login.user_session_id).filter(user_login.user_email == email).one_or_none()[0]
110
+ session.commit()
111
+ print(user_record)
112
+ if user_record:
113
+ session.close()
114
+ return user_record
115
+ else:
116
+ session.close()
117
+ return None
118
+ except:
119
+ engine = cf.get_db_engine1()
120
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
121
+ with Session() as session:
122
+ email = session.query(users.email).filter(users.id == id).one_or_none()[0]
123
+ session.commit()
124
+ user_record= session.query(user_login.user_session_id).filter(user_login.user_email == email).one_or_none()[0]
125
+ session.commit()
126
+ print(user_record)
127
+ if user_record:
128
+ session.close()
129
+ return user_record
130
+ else:
131
+ session.close()
132
+ return None
repository/UserRepository.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.orm import sessionmaker
2
+ from entity import Database_Entity
3
+ from repository import ConfigDatabase as cf
4
+ import pytz , datetime
5
+ from datetime import timedelta
6
+ user = Database_Entity.User
7
+
8
+ def getUserByEmail(email: str) -> user:
9
+ try:
10
+ engine = cf.get_db_engine()
11
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
12
+ with Session() as session:
13
+ user_record = session.query(user).filter(user.email == email).one_or_none()
14
+ session.close()
15
+ return user_record
16
+ except:
17
+ engine = cf.get_db_engine1()
18
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
19
+ with Session() as session:
20
+ user_record = session.query(user).filter(user.email == email).one_or_none()
21
+ session.close()
22
+ return user_record
23
+
24
+ def getUserIdByEmail(email: str) -> user.id:
25
+ try:
26
+ engine = cf.get_db_engine()
27
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
28
+ with Session() as session:
29
+ user_record = session.query(user.id).filter(user.email == email).one_or_none()[0]
30
+ session.close()
31
+ return user_record
32
+ except:
33
+ engine = cf.get_db_engine1()
34
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
35
+ with Session() as session:
36
+ user_record = session.query(user.id).filter(user.email == email).one_or_none()[0]
37
+ session.close()
38
+ return user_record
39
+
40
+ def getUserById(user_id: str) -> user:
41
+ try:
42
+ engine = cf.get_db_engine()
43
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
44
+ with Session() as session:
45
+ user_record = session.query(user).filter(user.id == user_id).one_or_none()
46
+ session.close()
47
+ return user_record
48
+ except:
49
+ engine = cf.get_db_engine1()
50
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
51
+ with Session() as session:
52
+ user_record = session.query(user).filter(user.id == user_id).one_or_none()
53
+ session.close()
54
+ return user_record
55
+
56
+ def getRefreshTokenUserByAccessToken(token: str) -> user.refresh_token:
57
+ try:
58
+ engine = cf.get_db_engine()
59
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
60
+ with Session() as session:
61
+ user_record = session.query(user.refresh_token).filter(user.access_token == token).one_or_none()
62
+ session.close()
63
+ return user_record
64
+ except:
65
+ engine = cf.get_db_engine1()
66
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
67
+ with Session() as session:
68
+ user_record = session.query(user.refresh_token).filter(user.access_token == token).one_or_none()
69
+ session.close()
70
+ return user_record
71
+
72
+ def getRefreshTokenUserByIdAndAccessToken(user_id: str,accessToken: str) -> user.refresh_token:
73
+ try:
74
+ engine = cf.get_db_engine()
75
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
76
+ with Session() as session:
77
+ user_record = session.query(user.refresh_token).filter(user.id == user_id,user.access_token == accessToken).one_or_none()[0]
78
+ session.close()
79
+ return user_record
80
+ except:
81
+ engine = cf.get_db_engine1()
82
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
83
+ with Session() as session:
84
+ user_record = session.query(user.refresh_token).filter(user.id == user_id).one_or_none()[0]
85
+ session.close()
86
+ return user_record
87
+ def getRefreshTokenUserById(user_id: str) -> user.refresh_token:
88
+ try:
89
+ engine = cf.get_db_engine()
90
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
91
+ with Session() as session:
92
+ user_record = session.query(user.refresh_token).filter(user.id == user_id).one_or_none()[0]
93
+ session.close()
94
+ return user_record
95
+ except:
96
+ engine = cf.get_db_engine1()
97
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
98
+ with Session() as session:
99
+ user_record = session.query(user.refresh_token).filter(user.id == user_id).one_or_none()[0]
100
+ session.close()
101
+ return user_record
102
+
103
+ def getEmailUser(email:str) -> user.email:
104
+ try:
105
+ engine = cf.get_db_engine()
106
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
107
+ with Session() as session:
108
+ user_email = session.query(user.email).filter(user.email == email).one_or_none()
109
+ session.close()
110
+ return user_email
111
+ except:
112
+ engine = cf.get_db_engine1()
113
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
114
+ with Session() as session:
115
+ user_email = session.query(user.email).filter(user.email == email).one_or_none()
116
+ session.close()
117
+ return user_email
118
+
119
+ def getEmailUserById(user_id:int) -> user.email:
120
+ try:
121
+ engine = cf.get_db_engine()
122
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
123
+ with Session() as session:
124
+ user_email = session.query(user.email).filter(user.id == user_id).one_or_none()[0]
125
+ session.close()
126
+ return user_email
127
+ except:
128
+ engine = cf.get_db_engine1()
129
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
130
+ with Session() as session:
131
+ user_email = session.query(user.email).filter(user.id == user_id).one_or_none()[0]
132
+ session.close()
133
+ return user_email
134
+
135
+ def getEmailUserByIdFix(user_id:int) -> user.email:
136
+ try:
137
+ engine = cf.get_db_engine()
138
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
139
+ with Session() as session:
140
+ user_email = session.query(user.email).filter(user.id == user_id).one_or_none()
141
+ session.close()
142
+ return user_email
143
+ except:
144
+ engine = cf.get_db_engine1()
145
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
146
+ with Session() as session:
147
+ user_email = session.query(user.email).filter(user.id == user_id).one_or_none()
148
+ session.close()
149
+ return user_email
150
+
151
+ def getEmailUserByAccessToken(token: str) -> user.email:
152
+ try:
153
+ engine = cf.get_db_engine()
154
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
155
+ with Session() as session:
156
+ user_email = session.query(user.email).filter(user.access_token == token).one_or_none()
157
+ session.close()
158
+ return user_email
159
+ except:
160
+ engine = cf.get_db_engine1()
161
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
162
+ with Session() as session:
163
+ user_email = session.query(user.email).filter(user.access_token == token).one_or_none()
164
+ session.close()
165
+ return user_email
166
+
167
+ def addUser(email: str, access_token: str, refresh_token: str, expires_at: datetime.datetime) -> None:
168
+ try:
169
+ engine = cf.get_db_engine()
170
+ Session = sessionmaker(bind=engine)
171
+ with Session() as session:
172
+ new_user = Database_Entity.User(
173
+ email=email,
174
+ access_token=access_token,
175
+ refresh_token=refresh_token,
176
+ expires_at=expires_at
177
+ )
178
+ session.add(new_user)
179
+ session.commit()
180
+ session.close()
181
+ except:
182
+ engine = cf.get_db_engine1()
183
+ Session = sessionmaker(bind=engine)
184
+ with Session() as session:
185
+ new_user = Database_Entity.User(
186
+ email=email,
187
+ access_token=access_token,
188
+ refresh_token=refresh_token,
189
+ expires_at=expires_at
190
+ )
191
+ session.add(new_user)
192
+ session.commit()
193
+ session.close()
194
+
195
+ def updateUserLogin(email: str, access_token: str, refresh_token: str, expires_at: datetime.datetime) -> bool:
196
+ try:
197
+ engine = cf.get_db_engine()
198
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
199
+ with Session() as session:
200
+ user_update = session.query(user).filter(user.email == email).one_or_none()
201
+ if user_update:
202
+ user_update.email = email
203
+ user_update.access_token = access_token
204
+ user_update.refresh_token = refresh_token
205
+ user_update.expires_at = expires_at
206
+ session.commit()
207
+ session.close()
208
+ return True
209
+ else:
210
+ session.close()
211
+ return False
212
+ except:
213
+ engine = cf.get_db_engine1()
214
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
215
+ with Session() as session:
216
+ user_update = session.query(user).filter(user.email == email).one_or_none()
217
+ if user_update:
218
+ user_update.email = email
219
+ user_update.access_token = access_token
220
+ user_update.refresh_token = refresh_token
221
+ user_update.expires_at = expires_at
222
+ session.commit()
223
+ session.close()
224
+ return True
225
+ else:
226
+ session.close()
227
+ return False
228
+
229
+ def updateAccessToken(user_id: int,access_token: str, expires_at: datetime.datetime) -> None:
230
+ try:
231
+ engine = cf.get_db_engine()
232
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
233
+ with Session() as session:
234
+ user_update = session.query(user).filter(user.id == user_id).one_or_none()
235
+ if user_update:
236
+ user_update.access_token = access_token
237
+ user_update.expires_at = expires_at
238
+ session.commit()
239
+ session.close()
240
+ except:
241
+ engine = cf.get_db_engine1()
242
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
243
+ with Session() as session:
244
+ user_update = session.query(user).filter(user.id == user_id).one_or_none()
245
+ if user_update:
246
+ user_update.access_token = access_token
247
+ user_update.expires_at = expires_at
248
+ session.commit()
249
+ session.close()
250
+
251
+ def updateAccessTokenById(id: int,access_token: str, expires_at: datetime.datetime) -> None:
252
+ try:
253
+ engine = cf.get_db_engine()
254
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
255
+ with Session() as session:
256
+ user_update = session.query(user).filter(user.id == id).one_or_none()
257
+ if user_update:
258
+ user_update.access_token = access_token
259
+ user_update.expires_at = expires_at
260
+ session.commit()
261
+ session.close()
262
+ except:
263
+ engine = cf.get_db_engine1()
264
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
265
+ with Session() as session:
266
+ user_update = session.query(user).filter(user.id == id).one_or_none()
267
+ if user_update:
268
+ user_update.access_token = access_token
269
+ user_update.expires_at = expires_at
270
+ session.commit()
271
+ session.close()
272
+
273
+ def UpdateAccessTokenRefreshToken(email: str, access_token: str, refresh_token: str, expires_at: datetime.datetime) -> None:
274
+ try:
275
+ engine = cf.get_db_engine()
276
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
277
+ with Session() as session:
278
+ user_update = session.query(user).filter(user.email == email).one_or_none()
279
+ if user_update:
280
+ user_update.access_token = access_token
281
+ user_update.refresh_token = refresh_token
282
+ user_update.expires_at = expires_at
283
+ session.commit()
284
+ session.close()
285
+ except:
286
+ engine = cf.get_db_engine1()
287
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
288
+ with Session() as session:
289
+ user_update = session.query(user).filter(user.email == email).one_or_none()
290
+ if user_update:
291
+ user_update.access_token = access_token
292
+ user_update.refresh_token = refresh_token
293
+ user_update.expires_at = expires_at
294
+ session.commit()
295
+ session.close()
296
+
297
+ def UpdateAccessTokenRefreshTokenById(user_id: int,access_token: str, refresh_token: str, expires_at: datetime.datetime) -> None:
298
+ try:
299
+ engine = cf.get_db_engine()
300
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
301
+ with Session() as session:
302
+ user_update = session.query(user).filter(user.id == user_id).one_or_none()
303
+ if user_update:
304
+ user_update.access_token = access_token
305
+ user_update.refresh_token = refresh_token
306
+ user_update.expires_at = expires_at
307
+ session.commit()
308
+ session.close()
309
+ except:
310
+ engine = cf.get_db_engine1()
311
+ Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
312
+ with Session() as session:
313
+ user_update = session.query(user).filter(user.id == user_id).one_or_none()
314
+ if user_update:
315
+ user_update.access_token = access_token
316
+ user_update.refresh_token = refresh_token
317
+ user_update.expires_at = expires_at
318
+ session.commit()
319
+ session.close()
repository/__pycache__/ChatHistoryRepository.cpython-310.pyc ADDED
Binary file (5.5 kB). View file