commands.py 10 KB

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