File size: 1,817 Bytes
eb474ee
 
 
1e0a76d
 
 
 
 
 
eb474ee
 
 
 
 
1e0a76d
eb474ee
 
 
 
 
 
 
 
 
 
 
1e0a76d
 
eb474ee
 
 
 
 
 
 
1e0a76d
 
 
 
 
 
eb474ee
 
 
1e0a76d
 
eb474ee
562d1b9
eb474ee
 
 
 
 
091afc0
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from fastapi import UploadFile

from src.utils import PineconeClient
from src.models import File, VectorStoreRecordId
from src.repositories import (
    FileRepository,
    VectorStoreRecordIdRepository,
    UserRepository,
)


class FileService:
    def __init__(self):
        self.pinecone_client = PineconeClient
        self.user_repository = UserRepository()
        self.file_repository = FileRepository()
        self.vector_store_record_id_repository = VectorStoreRecordIdRepository()

    async def __aenter__(self):
        return self

    async def __aexit__(self, *args):
        pass

    async def insert_file(self, file: UploadFile, user_id: str):
        try:
            user_object = await self.user_repository.get_by_id(user_id)

            metadata = [{"file_name": file.filename}]
            while content := await file.read():
                async with self.pinecone_client() as client:
                    ids = await client.insert_data(
                        text=[content.decode()], metadata=metadata
                    )

            file_object = await self.file_repository.insert_one(
                File(
                    user=user_object,
                    file_name=file.filename,
                    file_type=file.content_type,
                )
            )

            for id in ids:
                await self.vector_store_record_id_repository.insert_one(
                    VectorStoreRecordId(file=file_object, record_id=id)
                )
            return file_object

        finally:
            await file.close()

    async def semantic_search(self, query):
        try:
            async with self.pinecone_client() as client:
                return await client.similarity_search(query=query)
        except Exception as e:
            return str(e)