trunks_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. #cleanedTarget长度小于5的不进行匹配
  151. if len(cleanedTarget)<5:
  152. continue
  153. if cleanedTarget in cleanedContent:
  154. result.append(i)
  155. # 补齐连续下标
  156. if result:
  157. result.sort()
  158. filled_result = []
  159. prev = result[0]
  160. filled_result.append(prev)
  161. for current in result[1:]:
  162. if current - prev <= 2:
  163. for i in range(prev + 1, current):
  164. filled_result.append(i)
  165. filled_result.append(current)
  166. prev = current
  167. return filled_result
  168. return result
  169. _cache = {}
  170. def get_cache(self, conversation_id: str) -> List[dict]:
  171. """
  172. 根据conversation_id获取缓存结果
  173. :param conversation_id: 会话ID
  174. :return: 结果列表
  175. """
  176. return self._cache.get(conversation_id, [])
  177. def set_cache(self, conversation_id: str, result: List[dict]) -> None:
  178. """
  179. 设置缓存结果
  180. :param conversation_id: 会话ID
  181. :param result: 要缓存的结果
  182. """
  183. self._cache[conversation_id] = result
  184. def get_cached_result(self, conversation_id: str) -> List[dict]:
  185. """
  186. 根据conversation_id获取缓存结果
  187. :param conversation_id: 会话ID
  188. :return: 结果列表
  189. """
  190. return self.get_cache(conversation_id)
  191. def paginated_search_by_type_and_filepath(self, search_params: dict) -> dict:
  192. """
  193. 根据type和file_path进行分页查询
  194. :param search_params: 包含pageNo, limit的字典
  195. :return: 包含结果列表和分页信息的字典
  196. """
  197. page_no = search_params.get('pageNo', 1)
  198. limit = search_params.get('limit', 10)
  199. file_path = search_params.get('file_path', None)
  200. type = search_params.get('type', None)
  201. if page_no < 1:
  202. page_no = 1
  203. if limit < 1:
  204. limit = 10
  205. offset = (page_no - 1) * limit
  206. db = SessionLocal()
  207. try:
  208. query = db.query(
  209. Trunks.id,
  210. Trunks.file_path,
  211. Trunks.content,
  212. Trunks.type,
  213. Trunks.title
  214. )
  215. if type:
  216. query = query.filter(Trunks.type == type)
  217. if file_path:
  218. query = query.filter(Trunks.file_path.like('%' + file_path + '%'))
  219. query = query.filter(Trunks.page_no == None)
  220. results = query.offset(offset).limit(limit).all()
  221. return {
  222. 'data': [{
  223. 'id': r.id,
  224. 'file_path': r.file_path,
  225. 'content': r.content,
  226. 'type': r.type,
  227. 'title': r.title
  228. } for r in results]
  229. }
  230. finally:
  231. db.close()
  232. def paginated_search(self, search_params: dict) -> dict:
  233. """
  234. 分页查询方法
  235. :param search_params: 包含keyword, pageNo, limit的字典
  236. :return: 包含结果列表和分页信息的字典
  237. """
  238. keyword = search_params.get('keyword', '')
  239. page_no = search_params.get('pageNo', 1)
  240. limit = search_params.get('limit', 10)
  241. if page_no < 1:
  242. page_no = 1
  243. if limit < 1:
  244. limit = 10
  245. embedding = Vectorizer.get_embedding(keyword)
  246. offset = (page_no - 1) * limit
  247. db = SessionLocal()
  248. try:
  249. # 获取总条数
  250. total_count = db.query(func.count(Trunks.id)).filter(Trunks.type == search_params.get('type')).scalar()
  251. # 执行向量搜索
  252. results = db.query(
  253. Trunks.id,
  254. Trunks.file_path,
  255. Trunks.content,
  256. Trunks.embedding.l2_distance(embedding).label('distance'),
  257. Trunks.title
  258. ).filter(Trunks.type == search_params.get('type')).order_by('distance').offset(offset).limit(limit).all()
  259. return {
  260. 'data': [{
  261. 'id': r.id,
  262. 'file_path': r.file_path,
  263. 'content': r.content,
  264. #保留小数点后三位
  265. 'distance': round(r.distance, 3),
  266. 'title': r.title
  267. } for r in results],
  268. 'pagination': {
  269. 'total': total_count,
  270. 'pageNo': page_no,
  271. 'limit': limit,
  272. 'totalPages': (total_count + limit - 1) // limit
  273. }
  274. }
  275. finally:
  276. db.close()