commands.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import base64
  2. import json
  3. import secrets
  4. import click
  5. from flask import current_app
  6. from werkzeug.exceptions import NotFound
  7. from core.rag.datasource.vdb.vector_factory import Vector
  8. from core.rag.models.document import Document
  9. from extensions.ext_database import db
  10. from libs.helper import email as email_validate
  11. from libs.password import hash_password, password_pattern, valid_password
  12. from libs.rsa import generate_key_pair
  13. from models.account import Tenant
  14. from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment
  15. from models.dataset import Document as DatasetDocument
  16. from models.model import Account
  17. from models.provider import Provider, ProviderModel
  18. @click.command('reset-password', help='Reset the account password.')
  19. @click.option('--email', prompt=True, help='The email address of the account whose password you need to reset')
  20. @click.option('--new-password', prompt=True, help='the new password.')
  21. @click.option('--password-confirm', prompt=True, help='the new password confirm.')
  22. def reset_password(email, new_password, password_confirm):
  23. """
  24. Reset password of owner account
  25. Only available in SELF_HOSTED mode
  26. """
  27. if str(new_password).strip() != str(password_confirm).strip():
  28. click.echo(click.style('sorry. The two passwords do not match.', fg='red'))
  29. return
  30. account = db.session.query(Account). \
  31. filter(Account.email == email). \
  32. one_or_none()
  33. if not account:
  34. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  35. return
  36. try:
  37. valid_password(new_password)
  38. except:
  39. click.echo(
  40. click.style('sorry. The passwords must match {} '.format(password_pattern), fg='red'))
  41. return
  42. # generate password salt
  43. salt = secrets.token_bytes(16)
  44. base64_salt = base64.b64encode(salt).decode()
  45. # encrypt password with salt
  46. password_hashed = hash_password(new_password, salt)
  47. base64_password_hashed = base64.b64encode(password_hashed).decode()
  48. account.password = base64_password_hashed
  49. account.password_salt = base64_salt
  50. db.session.commit()
  51. click.echo(click.style('Congratulations!, password has been reset.', fg='green'))
  52. @click.command('reset-email', help='Reset the account email.')
  53. @click.option('--email', prompt=True, help='The old email address of the account whose email you need to reset')
  54. @click.option('--new-email', prompt=True, help='the new email.')
  55. @click.option('--email-confirm', prompt=True, help='the new email confirm.')
  56. def reset_email(email, new_email, email_confirm):
  57. """
  58. Replace account email
  59. :return:
  60. """
  61. if str(new_email).strip() != str(email_confirm).strip():
  62. click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red'))
  63. return
  64. account = db.session.query(Account). \
  65. filter(Account.email == email). \
  66. one_or_none()
  67. if not account:
  68. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  69. return
  70. try:
  71. email_validate(new_email)
  72. except:
  73. click.echo(
  74. click.style('sorry. {} is not a valid email. '.format(email), fg='red'))
  75. return
  76. account.email = new_email
  77. db.session.commit()
  78. click.echo(click.style('Congratulations!, email has been reset.', fg='green'))
  79. @click.command('reset-encrypt-key-pair', help='Reset the asymmetric key pair of workspace for encrypt LLM credentials. '
  80. 'After the reset, all LLM credentials will become invalid, '
  81. 'requiring re-entry.'
  82. 'Only support SELF_HOSTED mode.')
  83. @click.confirmation_option(prompt=click.style('Are you sure you want to reset encrypt key pair?'
  84. ' this operation cannot be rolled back!', fg='red'))
  85. def reset_encrypt_key_pair():
  86. """
  87. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  88. After the reset, all LLM credentials will become invalid, requiring re-entry.
  89. Only support SELF_HOSTED mode.
  90. """
  91. if current_app.config['EDITION'] != 'SELF_HOSTED':
  92. click.echo(click.style('Sorry, only support SELF_HOSTED mode.', fg='red'))
  93. return
  94. tenant = db.session.query(Tenant).first()
  95. if not tenant:
  96. click.echo(click.style('Sorry, no workspace found. Please enter /install to initialize.', fg='red'))
  97. return
  98. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  99. db.session.query(Provider).filter(Provider.provider_type == 'custom').delete()
  100. db.session.query(ProviderModel).delete()
  101. db.session.commit()
  102. click.echo(click.style('Congratulations! '
  103. 'the asymmetric key pair of workspace {} has been reset.'.format(tenant.id), fg='green'))
  104. @click.command('vdb-migrate', help='migrate vector db.')
  105. def vdb_migrate():
  106. """
  107. Migrate vector database datas to target vector database .
  108. """
  109. click.echo(click.style('Start migrate vector db.', fg='green'))
  110. create_count = 0
  111. config = current_app.config
  112. vector_type = config.get('VECTOR_STORE')
  113. page = 1
  114. while True:
  115. try:
  116. datasets = db.session.query(Dataset).filter(Dataset.indexing_technique == 'high_quality') \
  117. .order_by(Dataset.created_at.desc()).paginate(page=page, per_page=50)
  118. except NotFound:
  119. break
  120. page += 1
  121. for dataset in datasets:
  122. try:
  123. click.echo('Create dataset vdb index: {}'.format(dataset.id))
  124. if dataset.index_struct_dict:
  125. if dataset.index_struct_dict['type'] == vector_type:
  126. continue
  127. if vector_type == "weaviate":
  128. dataset_id = dataset.id
  129. collection_name = "Vector_index_" + dataset_id.replace("-", "_") + '_Node'
  130. index_struct_dict = {
  131. "type": 'weaviate',
  132. "vector_store": {"class_prefix": collection_name}
  133. }
  134. dataset.index_struct = json.dumps(index_struct_dict)
  135. elif vector_type == "qdrant":
  136. if dataset.collection_binding_id:
  137. dataset_collection_binding = db.session.query(DatasetCollectionBinding). \
  138. filter(DatasetCollectionBinding.id == dataset.collection_binding_id). \
  139. one_or_none()
  140. if dataset_collection_binding:
  141. collection_name = dataset_collection_binding.collection_name
  142. else:
  143. raise ValueError('Dataset Collection Bindings is not exist!')
  144. else:
  145. dataset_id = dataset.id
  146. collection_name = "Vector_index_" + dataset_id.replace("-", "_") + '_Node'
  147. index_struct_dict = {
  148. "type": 'qdrant',
  149. "vector_store": {"class_prefix": collection_name}
  150. }
  151. dataset.index_struct = json.dumps(index_struct_dict)
  152. elif vector_type == "milvus":
  153. dataset_id = dataset.id
  154. collection_name = "Vector_index_" + dataset_id.replace("-", "_") + '_Node'
  155. index_struct_dict = {
  156. "type": 'milvus',
  157. "vector_store": {"class_prefix": collection_name}
  158. }
  159. dataset.index_struct = json.dumps(index_struct_dict)
  160. else:
  161. raise ValueError(f"Vector store {config.get('VECTOR_STORE')} is not supported.")
  162. vector = Vector(dataset)
  163. click.echo(f"vdb_migrate {dataset.id}")
  164. try:
  165. vector.delete()
  166. except Exception as e:
  167. raise e
  168. dataset_documents = db.session.query(DatasetDocument).filter(
  169. DatasetDocument.dataset_id == dataset.id,
  170. DatasetDocument.indexing_status == 'completed',
  171. DatasetDocument.enabled == True,
  172. DatasetDocument.archived == False,
  173. ).all()
  174. documents = []
  175. for dataset_document in dataset_documents:
  176. segments = db.session.query(DocumentSegment).filter(
  177. DocumentSegment.document_id == dataset_document.id,
  178. DocumentSegment.status == 'completed',
  179. DocumentSegment.enabled == True
  180. ).all()
  181. for segment in segments:
  182. document = Document(
  183. page_content=segment.content,
  184. metadata={
  185. "doc_id": segment.index_node_id,
  186. "doc_hash": segment.index_node_hash,
  187. "document_id": segment.document_id,
  188. "dataset_id": segment.dataset_id,
  189. }
  190. )
  191. documents.append(document)
  192. if documents:
  193. try:
  194. vector.create(documents)
  195. except Exception as e:
  196. raise e
  197. click.echo(f"Dataset {dataset.id} create successfully.")
  198. db.session.add(dataset)
  199. db.session.commit()
  200. create_count += 1
  201. except Exception as e:
  202. db.session.rollback()
  203. click.echo(
  204. click.style('Create dataset index error: {} {}'.format(e.__class__.__name__, str(e)),
  205. fg='red'))
  206. continue
  207. click.echo(click.style('Congratulations! Create {} dataset indexes.'.format(create_count), fg='green'))
  208. def register_commands(app):
  209. app.cli.add_command(reset_password)
  210. app.cli.add_command(reset_email)
  211. app.cli.add_command(reset_encrypt_key_pair)
  212. app.cli.add_command(vdb_migrate)