r2r_file.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import tempfile
  2. import uuid
  3. from typing import List
  4. import aiofiles
  5. import aiofiles.os
  6. from fastapi import UploadFile
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from app.models import File
  9. from app.providers.r2r import r2r
  10. from app.providers.storage import storage
  11. from app.services.file.impl.oss_file import OSSFileService
  12. import asyncio
  13. import nest_asyncio
  14. # 使得异步代码可以在已运行的事件循环中嵌套
  15. nest_asyncio.apply()
  16. class R2RFileService(OSSFileService):
  17. @staticmethod
  18. async def create_file(
  19. *, session: AsyncSession, purpose: str, file: UploadFile
  20. ) -> File:
  21. # 文件是否存在
  22. # statement = (
  23. # select(File)
  24. # .where(File.purpose == purpose)
  25. # .where(File.filename == file.filename)
  26. # .where(File.bytes == file.size)
  27. # )
  28. # result = await session.execute(statement)
  29. # ext_file = result.scalars().first()
  30. # if ext_file is not None:
  31. # # TODO: 文件去重策略
  32. # return ext_file
  33. file_key = f"{uuid.uuid4()}-{file.filename}"
  34. with tempfile.NamedTemporaryFile(
  35. suffix="_" + file.filename, delete=True
  36. ) as temp_file:
  37. tmp_file_path = temp_file.name
  38. async with aiofiles.open(tmp_file_path, "wb") as f:
  39. while content := await file.read(1024):
  40. await f.write(content)
  41. storage.save_from_path(filename=file_key, local_file_path=tmp_file_path)
  42. await r2r.init()
  43. await r2r.ingest_file(
  44. file_path=tmp_file_path, metadata={"file_key": file_key}
  45. )
  46. # 存储
  47. db_file = File(
  48. purpose=purpose, filename=file.filename, bytes=file.size, key=file_key
  49. )
  50. session.add(db_file)
  51. await session.commit()
  52. await session.refresh(db_file)
  53. return db_file
  54. @staticmethod
  55. def search_in_files(query: str, file_keys: List[str]) -> dict:
  56. files = {}
  57. loop = asyncio.get_event_loop() # 获取当前事件循环
  58. loop.run_until_complete(r2r.init()) # 确保 r2r 已初始化
  59. search_results = loop.run_until_complete(
  60. r2r.search(query, filters={"file_key": {"$in": file_keys}})
  61. )
  62. if not search_results:
  63. return files
  64. for doc in search_results:
  65. file_key = doc.get("metadata").get("file_key")
  66. text = doc.get("text")
  67. if file_key in files and files[file_key]:
  68. files[file_key] += f"\n\n{text}"
  69. else:
  70. files[file_key] = doc.get("text")
  71. return files
  72. # TODO 删除s3&r2r文件