File size: 13,176 Bytes
38d6a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""
Copyright 2024-2025 Infosys Ltd.”

Use of this source code is governed by MIT license that can be found in the LICENSE file or at
MIT license https://opensource.org/licenses/MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""

from io import BytesIO
from fairness.config.logger import CustomLogger
from fairness.dao.WorkBench.databaseconnection import DataBase_WB
from fairness.exception.custom_exception import CustomHTTPException
from fastapi import HTTPException
from gridfs.errors import NoFile, FileExists
from gridfs import GridFS
import shutil
import os
from dotenv import load_dotenv
load_dotenv()
from fairness.config.logger import CustomLogger
from fairness.dao.databaseconnection import DataBase
from fairness.Telemetry.Telemetry_call import SERVICE_UPLOAD_FILE_METADATA
import datetime
import time
import requests

log = CustomLogger()
        
   
# ModelWorkBench = DataBase_WB() 
class FileStoreReportDb:
    
    #fs = GridFS(devraidb)
    # Create a MongoDB database instance

    def __init__(self,db=None) -> None:
        if db is not None:
            log.info("inside filestore")
            self.fs = GridFS(db)
            self.db_type = os.getenv('DB_TYPE').lower()
        else:
            ModelWorkBench = DataBase_WB()
            self.fs = GridFS(ModelWorkBench.db)
            self.db_type = os.getenv('DB_TYPE').lower()
    

    def save_file(self,file, filename,contentType,tenet,container_name=None):
        if self.db_type == 'mongo':
            # Check if file_content is not None
            if file is None:
                raise HTTPException(status_code=500, detail="File content cannot be None")
            
            # Check if filename, contentType, and tenet are not None
            if filename is None or contentType is None or tenet is None:
                raise ValueError("Filename, contentType, and tenet cannot be None")
            
            localTime=time.time()
            time.sleep(1/1000)
            with self.fs.new_file(_id=str(localTime), 
                                        filename=filename,
                                        contentType=contentType,
                                        tenet = tenet,
                                        ) as f:
                f.write(file)

            return f._id
        else:
            if file is None:
                raise HTTPException(status_code=500, detail="File content cannot be None")
            
            # Check if filename, contentType, and tenet are not None
            if filename is None or contentType is None or tenet is None:
                raise ValueError("Filename, contentType, and tenet cannot be None")
                # container_name = os.getenv('HTML_CONTAINER_NAME')
            upload_file_api = os.getenv('AZURE_UPLOAD_API')
            # html_containerName = os.getenv('HTML_CONTAINER_NAME')
            log.info(f"container_name:{container_name}")
            # filename = "fairness_file"  # Replace with your actual filename if available
            response =requests.post(url =upload_file_api, files ={"file":(filename, file)}, data ={"container_name":container_name}).json()
            if response is None:
                raise HTTPException(f"An error occurred: file not found")
            blob_name =response["blob_name"]
            log.info(f"{blob_name} blob name")
            return blob_name
    

    def save_filecreate(self,file):
        
        # Check if file_content is not None
        if file is None:
            raise ValueError("File content cannot be None")
              
        localTime=time.time()
        with self.fs.new_file(_id=localTime,
                                     filename=file.filename,
                                     contentType=file.content_type,
                                     tenet = "fairness",
                                     ) as f:
            file.file.seek(0) # Go back to the start of the file
            shutil.copyfileobj(file.file, f)
        return f._id 
    

    def read_file(self,unique_id: str,container_name=None):
        if self.db_type == 'mongo':

            # try:
                # Find the file in the database
            log.info(unique_id)
            # file_metadata = FileStoreReportDb().fs.find_one({"_id": unique_id, "contentType": file_type})
            file_metadata = self.fs.find_one({"_id": unique_id})
            # Check if the file was found
            if file_metadata is None:
                log.info("inside file not found")
                raise HTTPException(status_code=500, detail=f"No file found with unique ID {unique_id}")
            # Get the file from the database
            file_content = self.fs.get(file_metadata._id).read()
            
            return {"data": file_content, "name":file_metadata.filename, "extension": file_metadata.filename.split('.')[-1],"contentType":file_metadata.content_type}
        else:
            download_file_api = os.getenv('AZURE_GET_API')
            if container_name is None:
                container_name = os.getenv('Dt_containerName')

            # Check if the environment variable is set
            if not download_file_api:
                raise HTTPException(status_code=500, detail=f"Environment variable AZURE_READ_API is not set")

            # Check if container_name and unique_id are not empty
            if not container_name or not unique_id:
                raise ValueError("container_name and unique_id must not be empty")
               
            response = requests.get(url=download_file_api, params={"container_name": container_name, "blob_name": unique_id})
            if response is None:
                raise HTTPException("occurred: file not found")
            # Check if the request was successful
            if response.status_code != 200:
                raise Exception(f"Request to {download_file_api} failed with status code {response.status_code}")

            return {'data': response.content, 'type': unique_id.split('.')[-1], 'name': unique_id.split('/')[-1],'contentType':response.headers['Content-Type'], 'extension': unique_id.split('.')[-1]}

    def read_chunked_file(self,unique_id: str,container_name=None):
        if self.db_type == 'mongo':
            # file_metadata = FileStoreReportDb().fs.find_one({"_id": unique_id, "contentType": file_type})
            file_metadata = self.fs.find_one({"_id": unique_id})
            # Check if the file was found
            if file_metadata is None:
                raise FileNotFoundError(f"No file found with unique ID {unique_id}")
            
            # Get the file from the database
            file_content = self.fs.get(file_metadata._id).read()
            
            return {"data": file_content, "name":file_metadata.filename, "extension": file_metadata.filename.split('.')[-1],"contentType":file_metadata.content_type}
        else:
            download_file_api = os.getenv('AZURE_GET_API')
            container_name = os.getenv('Model_CONTAINER_NAME')

            # Check if the environment variable is set
            if not download_file_api:
                raise ValueError("Environment variable AZURE_READ_API is not set")

            # Check if container_name and unique_id are not empty
            if not container_name or not unique_id:
                raise ValueError("container_name and unique_id must not be empty")

            file_bytes=BytesIO()
            content_type=""
            with requests.get(url=download_file_api, params={"container_name": container_name, "blob_name": unique_id}, stream=True) as r:
                r.raise_for_status()
                content_type=r.headers['Content-Type']
                for chunk in r.iter_content(chunk_size=8192):
                    if chunk:
                        file_bytes.write(chunk)
            file_bytes.seek(0)
            # if response.status_code != 200:
            #     raise Exception(f"Request to {download_file_api} failed with status code {response.status_code}")

            return {'data': file_bytes.getvalue(), 'type': unique_id.split('.')[-1], 'name': unique_id.split('/')[-1],'contentType':content_type, 'extension': unique_id.split('.')[-1]}

    

    def read_modelfile(self,unique_id: str,container_name=None):
        if self.db_type == 'mongo':

            # Find the file in the database
            log.info(f"{unique_id}")
            # file_metadata = FileStoreReportDb().fs.find_one({"_id": unique_id, "contentType": file_type})
            file_metadata = self.fs.find_one({"_id": unique_id})
            # Check if the file was found
            if file_metadata is None:
                raise FileNotFoundError(f"No file found with unique ID {unique_id}")
            
            # Get the file from the database
            file_content = self.fs.get(file_metadata._id).read()
            
            return {"data": file_content, "name":file_metadata.filename, "extension": file_metadata.filename.split('.')[-1],"contentType":file_metadata.content_type}
        else:
            download_file_api = os.getenv('AZURE_GET_API')
            container_name = os.getenv('Model_CONTAINER_NAME')

            # Check if the environment variable is set
            if not download_file_api:
                raise ValueError("Environment variable AZURE_READ_API is not set")

            # Check if container_name and unique_id are not empty
            if not container_name or not unique_id:
                raise ValueError("container_name and unique_id must not be empty")
            response = requests.get(url=download_file_api, params={"container_name": container_name, "blob_name": unique_id})
            # Check if the request was successful
            if response.status_code != 200:
                raise Exception(f"Request to {download_file_api} failed with status code {response.status_code}")

            return {'data': response.content, 'type': unique_id.split('.')[-1], 'name': unique_id.split('/')[-1],'contentType':response.headers['Content-Type'], 'extension': unique_id.split('.')[-1]}

    
    def delete_file(self,unique_id: str, file_type: str):
        
        # Check if unique_id is not None and is a string
        if unique_id is None or not isinstance(unique_id, str):
            raise ValueError("Unique ID must be a non-empty string")
        
        # Check if file_type is not None and is a string
        if file_type is None or not isinstance(file_type, str):
            raise ValueError("File type must be a non-empty string")
        
        try:
            # Find the file in the database
            file_metadata = self.fs.find_one({"uniqueId": unique_id, "type": file_type})
            
            # Check if the file was found
            if file_metadata is None:
                raise FileNotFoundError(f"No file found with unique ID {unique_id} and type {file_type}")
            
            # Delete the file from the database
            FileStoreReportDb.fs.delete(file_metadata._id)
            
            return {"message": "File deleted successfully"}
        except NoFile:
            raise FileNotFoundError(f"No file found with unique ID {unique_id} and type {file_type}")
    

    def save_local_file(self,filePath,fileType):
        
        if os.path.exists(filePath):
            if os.path.getsize(filePath)<=0:
                raise ValueError("File content cannot be None")
        else:
            raise FileNotFoundError("No file found with the name "+filePath.split("/")[-1]+" locally")
        with open(filePath,'rb') as f:
             file_id=self.fs.put(f,filename=filePath.split('/')[-1],content_type=fileType)
        return file_id

    def getfilename(self,unique_id: str):
        try:
            # Find the file in the database
            file_metadata = self.fs.find_one({"_id": unique_id})
            log.info(f"file_metadata {file_metadata}")
            if file_metadata:

                filename = file_metadata.filename
                log.info(f"{filename} filename")
            return filename
        except NoFile:
            raise FileNotFoundError(f"No file found with unique ID {unique_id}")