trunks_service.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. from sqlalchemy import func
  2. from sqlalchemy.orm import Session
  3. from db.session import get_db
  4. from typing import List, Optional
  5. from model.trunks_model import Trunks
  6. from db.session import SessionLocal
  7. import logging
  8. from utils.sentence_util import SentenceUtil
  9. from utils.vectorizer import Vectorizer
  10. logger = logging.getLogger(__name__)
  11. class TrunksService:
  12. def __init__(self):
  13. self.db = next(get_db())
  14. def create_trunk(self, trunk_data: dict) -> Trunks:
  15. # 自动生成向量和全文检索字段
  16. content = trunk_data.get('content')
  17. if 'embedding' in trunk_data and len(trunk_data['embedding']) != 1024:
  18. raise ValueError("向量维度必须为1024")
  19. trunk_data['embedding'] = Vectorizer.get_embedding(content)
  20. if 'type' not in trunk_data:
  21. trunk_data['type'] = 'default'
  22. if 'title' not in trunk_data:
  23. from pathlib import Path
  24. trunk_data['title'] = Path(trunk_data['file_path']).stem
  25. print("embedding length:", len(trunk_data['embedding']))
  26. logger.debug(f"生成的embedding长度: {len(trunk_data['embedding'])}, 内容摘要: {content[:20]}")
  27. # trunk_data['content_tsvector'] = func.to_tsvector('chinese', content)
  28. db = SessionLocal()
  29. try:
  30. trunk = Trunks(**trunk_data)
  31. db.add(trunk)
  32. db.commit()
  33. db.refresh(trunk)
  34. return trunk
  35. except Exception as e:
  36. db.rollback()
  37. logger.error(f"创建trunk失败: {str(e)}")
  38. raise
  39. finally:
  40. db.close()
  41. def get_trunk_by_id(self, trunk_id: int) -> Optional[dict]:
  42. db = SessionLocal()
  43. try:
  44. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  45. if trunk:
  46. return {
  47. 'id': trunk.id,
  48. 'file_path': trunk.file_path,
  49. 'content': trunk.content,
  50. 'embedding': trunk.embedding.tolist(),
  51. 'type': trunk.type,
  52. 'title':trunk.title
  53. }
  54. return None
  55. finally:
  56. db.close()
  57. def search_by_vector(self, text: str, limit: int = 10, file_path: Optional[str]=None,metadata_condition: Optional[dict] = None, type: Optional[str] = None, conversation_id: Optional[str] = None) -> List[dict]:
  58. embedding = Vectorizer.get_embedding(text)
  59. db = SessionLocal()
  60. try:
  61. query = db.query(
  62. Trunks.id,
  63. Trunks.file_path,
  64. Trunks.content,
  65. Trunks.embedding.l2_distance(embedding).label('distance'),
  66. Trunks.title,
  67. Trunks.embedding,
  68. Trunks.page_no,
  69. Trunks.referrence
  70. )
  71. if metadata_condition:
  72. query = query.filter_by(**metadata_condition)
  73. if type:
  74. query = query.filter(Trunks.type == type)
  75. if file_path:
  76. query = query.filter(Trunks.file_path.like('%'+file_path+'%'))
  77. results = query.order_by('distance').limit(limit).all()
  78. result_list = [{
  79. 'id': r.id,
  80. 'file_path': r.file_path,
  81. 'content': r.content,
  82. #保留小数点后三位
  83. 'distance': round(r.distance, 3),
  84. 'title': r.title,
  85. 'embedding': r.embedding.tolist(),
  86. 'page_no': r.page_no,
  87. 'referrence': r.referrence
  88. } for r in results]
  89. if conversation_id:
  90. self.set_cache(conversation_id, result_list)
  91. return result_list
  92. finally:
  93. db.close()
  94. def fulltext_search(self, query: str) -> List[Trunks]:
  95. db = SessionLocal()
  96. try:
  97. return db.query(Trunks).filter(
  98. Trunks.content_tsvector.match(query)
  99. ).all()
  100. finally:
  101. db.close()
  102. def update_trunk(self, trunk_id: int, update_data: dict) -> Optional[Trunks]:
  103. if 'content' in update_data:
  104. content = update_data['content']
  105. update_data['embedding'] = Vectorizer.get_embedding(content)
  106. if 'type' not in update_data:
  107. update_data['type'] = 'default'
  108. logger.debug(f"更新生成的embedding长度: {len(update_data['embedding'])}, 内容摘要: {content[:20]}")
  109. # update_data['content_tsvector'] = func.to_tsvector('chinese', content)
  110. db = SessionLocal()
  111. try:
  112. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  113. if trunk:
  114. for key, value in update_data.items():
  115. setattr(trunk, key, value)
  116. db.commit()
  117. db.refresh(trunk)
  118. return trunk
  119. except Exception as e:
  120. db.rollback()
  121. logger.error(f"更新trunk失败: {str(e)}")
  122. raise
  123. finally:
  124. db.close()
  125. def delete_trunk(self, trunk_id: int) -> bool:
  126. db = SessionLocal()
  127. try:
  128. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  129. if trunk:
  130. db.delete(trunk)
  131. db.commit()
  132. return True
  133. return False
  134. except Exception as e:
  135. db.rollback()
  136. logger.error(f"删除trunk失败: {str(e)}")
  137. raise
  138. finally:
  139. db.close()
  140. def highlight(self, trunk_id: int, targetSentences: List[str]) -> List[int]:
  141. trunk = self.get_trunk_by_id(trunk_id)
  142. if not trunk:
  143. return []
  144. content = trunk['content']
  145. sentence_util = SentenceUtil()
  146. cleanedContent = sentence_util.clean_text(content)
  147. result = []
  148. for i, targetSentence in enumerate(targetSentences):
  149. cleanedTarget = sentence_util.clean_text(targetSentence)
  150. if cleanedTarget in cleanedContent:
  151. result.append(i)
  152. return result
  153. _cache = {}
  154. def get_cache(self, conversation_id: str) -> List[dict]:
  155. """
  156. 根据conversation_id获取缓存结果
  157. :param conversation_id: 会话ID
  158. :return: 结果列表
  159. """
  160. return self._cache.get(conversation_id, [])
  161. def set_cache(self, conversation_id: str, result: List[dict]) -> None:
  162. """
  163. 设置缓存结果
  164. :param conversation_id: 会话ID
  165. :param result: 要缓存的结果
  166. """
  167. self._cache[conversation_id] = result
  168. def get_cached_result(self, conversation_id: str) -> List[dict]:
  169. """
  170. 根据conversation_id获取缓存结果
  171. :param conversation_id: 会话ID
  172. :return: 结果列表
  173. """
  174. return self.get_cache(conversation_id)
  175. def paginated_search_by_type_and_filepath(self, search_params: dict) -> dict:
  176. """
  177. 根据type和file_path进行分页查询
  178. :param search_params: 包含pageNo, limit的字典
  179. :return: 包含结果列表和分页信息的字典
  180. """
  181. page_no = search_params.get('pageNo', 1)
  182. limit = search_params.get('limit', 10)
  183. file_path = search_params.get('file_path', None)
  184. type = search_params.get('type', None)
  185. if page_no < 1:
  186. page_no = 1
  187. if limit < 1:
  188. limit = 10
  189. offset = (page_no - 1) * limit
  190. db = SessionLocal()
  191. try:
  192. query = db.query(
  193. Trunks.id,
  194. Trunks.file_path,
  195. Trunks.content,
  196. Trunks.type,
  197. Trunks.title
  198. )
  199. if type:
  200. query = query.filter(Trunks.type == type)
  201. if file_path:
  202. query = query.filter(Trunks.file_path.like('%' + file_path + '%'))
  203. query = query.filter(Trunks.page_no == None)
  204. results = query.offset(offset).limit(limit).all()
  205. return {
  206. 'data': [{
  207. 'id': r.id,
  208. 'file_path': r.file_path,
  209. 'content': r.content,
  210. 'type': r.type,
  211. 'title': r.title
  212. } for r in results]
  213. }
  214. finally:
  215. db.close()
  216. def paginated_search(self, search_params: dict) -> dict:
  217. """
  218. 分页查询方法
  219. :param search_params: 包含keyword, pageNo, limit的字典
  220. :return: 包含结果列表和分页信息的字典
  221. """
  222. keyword = search_params.get('keyword', '')
  223. page_no = search_params.get('pageNo', 1)
  224. limit = search_params.get('limit', 10)
  225. if page_no < 1:
  226. page_no = 1
  227. if limit < 1:
  228. limit = 10
  229. embedding = Vectorizer.get_embedding(keyword)
  230. offset = (page_no - 1) * limit
  231. db = SessionLocal()
  232. try:
  233. # 获取总条数
  234. total_count = db.query(func.count(Trunks.id)).filter(Trunks.type == search_params.get('type')).scalar()
  235. # 执行向量搜索
  236. results = db.query(
  237. Trunks.id,
  238. Trunks.file_path,
  239. Trunks.content,
  240. Trunks.embedding.l2_distance(embedding).label('distance'),
  241. Trunks.title
  242. ).filter(Trunks.type == search_params.get('type')).order_by('distance').offset(offset).limit(limit).all()
  243. return {
  244. 'data': [{
  245. 'id': r.id,
  246. 'file_path': r.file_path,
  247. 'content': r.content,
  248. #保留小数点后三位
  249. 'distance': round(r.distance, 3),
  250. 'title': r.title
  251. } for r in results],
  252. 'pagination': {
  253. 'total': total_count,
  254. 'pageNo': page_no,
  255. 'limit': limit,
  256. 'totalPages': (total_count + limit - 1) // limit
  257. }
  258. }
  259. finally:
  260. db.close()