Kiran5 commited on
Commit
54fa0c8
·
1 Parent(s): a1bf5c4

Track large files and images with Git LFS

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. src/.env +1 -0
  3. src/imageToSave.png +0 -0
  4. src/logger.ini +5 -0
  5. src/main.py +141 -0
  6. src/privacy/.env +26 -0
  7. src/privacy/__init__.py +0 -0
  8. src/privacy/__pycache__/__init__.cpython-311.pyc +0 -0
  9. src/privacy/code_generator/codegeneration.py +257 -0
  10. src/privacy/code_generator/template_recognizer.py +56 -0
  11. src/privacy/config/__init__.py +0 -0
  12. src/privacy/config/__pycache__/__init__.cpython-311.pyc +0 -0
  13. src/privacy/config/__pycache__/config.cpython-311.pyc +0 -0
  14. src/privacy/config/__pycache__/logger.cpython-311.pyc +0 -0
  15. src/privacy/config/config.py +36 -0
  16. src/privacy/config/logger.py +221 -0
  17. src/privacy/constants/__init__.py +0 -0
  18. src/privacy/constants/__pycache__/__init__.cpython-311.pyc +0 -0
  19. src/privacy/constants/__pycache__/local_constants.cpython-311.pyc +0 -0
  20. src/privacy/constants/local_constants.py +21 -0
  21. src/privacy/dao/AccDataGrpMappingDb.py +75 -0
  22. src/privacy/dao/AccMasterDb.py +73 -0
  23. src/privacy/dao/AccPtrnMappingDb.py +71 -0
  24. src/privacy/dao/DataRecogdb.py +78 -0
  25. src/privacy/dao/DatabaseConnection.py +32 -0
  26. src/privacy/dao/EntityDb.py +70 -0
  27. src/privacy/dao/TelemetryFlagDb.py +70 -0
  28. src/privacy/dao/__init__.py +0 -0
  29. src/privacy/dao/privacy/DatabaseConnection.py +27 -0
  30. src/privacy/dao/privacy/PrivacyException.py +67 -0
  31. src/privacy/dao/privacy/TelemetryDb.py +70 -0
  32. src/privacy/dao/temp.txt +24 -0
  33. src/privacy/exception/__init__.py +0 -0
  34. src/privacy/exception/__pycache__/__init__.cpython-311.pyc +0 -0
  35. src/privacy/exception/__pycache__/exception.cpython-311.pyc +0 -0
  36. src/privacy/exception/exception.py +50 -0
  37. src/privacy/mappers/__init__.py +0 -0
  38. src/privacy/mappers/__pycache__/__init__.cpython-311.pyc +0 -0
  39. src/privacy/mappers/__pycache__/mappers.cpython-311.pyc +0 -0
  40. src/privacy/mappers/mappers.py +177 -0
  41. src/privacy/routing/__init__.py +0 -0
  42. src/privacy/routing/__pycache__/__init__.cpython-311.pyc +0 -0
  43. src/privacy/routing/__pycache__/privacy_router.cpython-311.pyc +0 -0
  44. src/privacy/routing/privacy_router.py +1747 -0
  45. src/privacy/service/Video_service.py +207 -0
  46. src/privacy/service/__init__.py +51 -0
  47. src/privacy/service/api_req.py +88 -0
  48. src/privacy/service/azureComputerVision.py +137 -0
  49. src/privacy/service/code_detect_service.py +51 -0
  50. src/privacy/service/dicomPrivacy.py +70 -0
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ src/privacy/util/code_detect/ner/pii_inference/nermodel/pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
37
+ src/privacy/util/face_detect/face_detector/res10_300x300_ssd_iter_140000.caffemodel filter=lfs diff=lfs merge=lfs -text
38
+ src/privacy/util/model/craft_mlt_25k.pth filter=lfs diff=lfs merge=lfs -text
39
+ src/privacy/util/model/english_g2.pth filter=lfs diff=lfs merge=lfs -text
40
+ src/privacy/util/face_detect/doc/10.jpg filter=lfs diff=lfs merge=lfs -text
41
+ src/privacy/util/face_detect/doc/5.jpg filter=lfs diff=lfs merge=lfs -text
42
+ src/privacy/util/face_detect/doc/8.jpg filter=lfs diff=lfs merge=lfs -text
43
+ src/privacy/util/face_detect/doc/*.jpg filter=lfs diff=lfs merge=lfs -text
src/.env ADDED
@@ -0,0 +1 @@
 
 
1
+ FILE_NAME = "presidio_analyzer-3.0.0-py3-none-any.whl"
src/imageToSave.png ADDED
src/logger.ini ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [logDetails]
2
+ LOG_LEVEL=DEBUG
3
+ FILE_NAME=projectmanagementservicelogs
4
+ VERBOSE=False
5
+ LOG_DIR=/aicloud/logs
src/main.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+ from typing import List
11
+
12
+
13
+ import uvicorn
14
+ from privacy.config.logger import CustomLogger
15
+ from privacy.config.config import read_config_yaml
16
+ from fastapi import Depends, FastAPI, Request, Response
17
+ from fastapi.exceptions import RequestValidationError
18
+ from starlette.exceptions import HTTPException as StarletteHTTPException
19
+ from privacy.routing.privacy_router import router
20
+ # from starlette.middleware.cors import CORSMiddleware
21
+ # from starlette.middleware import Middleware
22
+ from fastapi.responses import JSONResponse, PlainTextResponse, Response
23
+ from fastapi.middleware.cors import CORSMiddleware
24
+
25
+ from aicloudlibs.utils.global_exception import UnSupportedMediaTypeException
26
+ from aicloudlibs.utils import global_exception_handler
27
+
28
+
29
+ log=CustomLogger()
30
+ ## initialize the app with openapi and docs url
31
+
32
+ ## reading metadata configuration from config file
33
+
34
+
35
+
36
+ app = FastAPI(**read_config_yaml('../config/metadata.yaml'))
37
+
38
+ """
39
+
40
+ Adding the CORS Middleware which handles the requests from different origins
41
+
42
+ allow_origins - A list of origins that should be permitted to make cross-origin requests.
43
+ using ['*'] to allow any origin
44
+ allow_methods - A list of HTTP methods that should be allowed for cross-origin requests.
45
+ using ['*'] to allow all standard method
46
+ allow_headers - A list of HTTP request headers that should be supported for cross-origin requests.
47
+ using ['*'] to allow all headers
48
+ """
49
+
50
+ # origins = [
51
+ # 'http://10.66.155.13',
52
+ # 'http://10.66.155.13:30010',
53
+
54
+ # ]
55
+
56
+
57
+ app.add_middleware(
58
+ CORSMiddleware,
59
+ allow_origins=["*"],
60
+ allow_credentials=True,
61
+ allow_methods=["*"],
62
+ allow_headers=["*"]
63
+ )
64
+
65
+ """
66
+ FAST API raise RequestValidationError in case request contains invalid data.
67
+ A global exception handler function to handle the requests which contains the invalid data
68
+
69
+ """
70
+
71
+ # @app.options("/{rest_of_path:path}")
72
+ # async def preflight_handler(request: Request, rest_of_path: str) -> Response:
73
+ # """
74
+ # Handles OPTIONS requests to /*.
75
+ # """
76
+ # response = Response()
77
+ # response.headers["Access-Control-Allow-Origin"] = "*"
78
+ # response.headers["Access-Control-Allow-Methods"] = "POST, GET, DELETE, PATCH, OPTIONS"
79
+ # response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
80
+ # return response
81
+
82
+ # @app.middleware("http")
83
+ # async def add_cors_header(request , call_next):
84
+ # """
85
+ # Sets CORS headers.
86
+ # """
87
+ # response = await call_next(request)
88
+ # response.headers["Access-Control-Allow-Origin"] = "http://10.66.155.13:30010"
89
+ # response.headers["Access-Control-Allow-Credentials"] = "true"
90
+ # response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
91
+ # response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
92
+ # return response
93
+
94
+ # origins = [
95
+ # "http://10.66.155.13",
96
+ # "http://10.66.155.13:30010",
97
+ # ]
98
+
99
+ # app.add_middleware(
100
+ # CORSMiddleware,
101
+ # allow_origins=origins,
102
+ # allow_credentials=True,
103
+ # allow_methods=["*"],
104
+ # allow_headers=["*"],
105
+ # )
106
+
107
+
108
+
109
+
110
+
111
+ @app.exception_handler(RequestValidationError)
112
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
113
+ return global_exception_handler.validation_error_handler(exc)
114
+
115
+
116
+ """
117
+ A global exception handler function to handle the unsupported media type exception
118
+ """
119
+ @app.exception_handler(UnSupportedMediaTypeException)
120
+ async def unsupported_mediatype_error_handler(request: Request, exc: UnSupportedMediaTypeException):
121
+ return global_exception_handler.unsupported_mediatype_error_handler(exc)
122
+
123
+
124
+
125
+ """
126
+ A global exception handler function to handle the http exception
127
+ """
128
+ @app.exception_handler(StarletteHTTPException)
129
+ async def http_exception_handler(request, exc):
130
+ return global_exception_handler.http_exception_handler(exc)
131
+
132
+
133
+
134
+ """
135
+ incude the routing details of service
136
+ """
137
+
138
+ app.include_router(router, prefix='/v1', tags=["PII Privacy"])
139
+
140
+ if __name__ == "__main__":
141
+ uvicorn.run(app, host="0.0.0.0", port=30002)
src/privacy/.env ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PRIVADMIN_API = "${admin}"
2
+ # PRIVADMIN_API = "http://localhost:8080"
3
+ # PRIVADMIN_API = "http://10.66.155.13:30016"
4
+ ISDB=False
5
+
6
+
7
+ # PRIVADMIN_API= "http://localhost:8080/api/v1/rai/admin/PrivacyDataList"
8
+ en_core_web_lg={"lang_code": "en", "model_name": "en_core_web_lg"}
9
+ en_core_web_trf={"lang_code": "en", "model_name": "en_core_web_trf"}
10
+ PRIVACY_TELEMETRY_URL = "${privacytelemetryurl}"
11
+ PRIVACY_ERROR_URL = "${privacyerrorurl}"
12
+ PRIVADMIN_API="${adminapi}"
13
+
14
+
15
+ AUTH_TYPE = none # Options: azure , jwt , none
16
+ SECRET_KEY = "${secretkey}" # Secret key for JWT token
17
+ AZURE_CLIENT_ID="${azureclientid}"
18
+ AZURE_TENANT_ID="${azuretenantid}"
19
+ AZURE_AD_JWKS_URL = "${azuread_jwks_url}"
20
+
21
+ TELE_FLAG="False"
22
+ ADMIN_CONNECTION="False"
23
+ API_KEY="${api_key}"
24
+ API_ENDPOINT="${api_endpoint}"
25
+ GCS_DEVELOPER_KEY="${gcsdeveloperkey}"
26
+
src/privacy/__init__.py ADDED
File without changes
src/privacy/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (222 Bytes). View file
 
src/privacy/code_generator/codegeneration.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import os
12
+ import subprocess
13
+ import shutil
14
+ # from dotenv import load_dotenv
15
+ # load_dotenv()
16
+
17
+ # def test():
18
+ # print(os.environ)
19
+ # #test = os.environ["FILE_NAME"]
20
+ # #print(test)
21
+
22
+ # print(os.getenv('FILE_NAME'))
23
+
24
+
25
+ # FILE CREATION
26
+ def create_new_recognizer_file(file_name, regex_expression):
27
+ template_file = "template_recognizer.py" # Assign the template file name directly
28
+ # Get the absolute path of the current script's directory
29
+ script_dir = os.path.dirname(os.path.abspath(__file__))
30
+ # print(script_dir)
31
+ # Construct the full path to the template file
32
+ template_file_path = os.path.join(script_dir, template_file)
33
+ #output file path
34
+ # output_directory = os.path.join(script_dir, "..\\..\\..\\..\\presidio_analyzer\\presidio_analyzer\\Infosys_presidio_analyzer\\presidio_analyzer\\presidio_analyzer\\predefined_recognizers")
35
+ output_directory = "../../presidio_analyzer/presidio_analyzer/Infosys_presidio_analyzer/presidio_analyzer/presidio_analyzer/predefined_recognizers/"
36
+ os.makedirs(output_directory, exist_ok=True)
37
+ #new file name
38
+ new_file = f"{file_name}_recognizer.py"
39
+ #combine the path
40
+ output_path = os.path.join(output_directory, new_file)
41
+ with open(template_file_path, "r") as f:
42
+ template_content = f.read()
43
+
44
+ # Replace the placeholder values in the template
45
+ # have to start replacing the content in the template file
46
+ # Replace the class name in the template
47
+ new_content = template_content.replace("Class_Name", file_name)
48
+ # Replace the supported_entity parameter value
49
+ supported_entity = file_name.upper()
50
+ new_content = new_content.replace('supported_entity: str = "AADHAR_NUMBER"',
51
+ f'supported_entity: str = "{supported_entity}"')
52
+ # Replacing the pattern name
53
+ new_content = new_content.replace("pattern_name", f"{file_name.lower()}_pattern")
54
+
55
+ # Replacing the regex expression
56
+ new_content = new_content.replace("REGEX_PATTERN", regex_expression)
57
+ # Write the modified content to the new file at the specified output path
58
+ with open(output_path, "w") as f:
59
+ f.write(new_content)
60
+ print(f"Created new recognizer file: {new_file}")
61
+
62
+ # ADDING IMPORTS IN RECOGNIZERS REGISTRY
63
+
64
+ def modify_recognizer_registry(file_name):
65
+ script_dir = os.path.dirname(os.path.abspath(__file__))
66
+ recognizer_registry_file = os.path.join(
67
+ script_dir,
68
+ "../../../../presidio_analyzer/presidio_analyzer/Infosys_presidio_analyzer/presidio_analyzer/presidio_analyzer/recognizer_registry/recognizer_registry.py",
69
+ )
70
+
71
+ # Check if the class name is already imported
72
+ with open(recognizer_registry_file, "r") as f:
73
+ lines = f.readlines()
74
+
75
+ class_name = f"class {file_name}"
76
+ existing_lines = [line.strip().lower() for line in lines]
77
+ new_import_line = f" {file_name},"
78
+
79
+ # Check if the class name is already imported
80
+ is_imported = any(class_name.lower() == line.lower().strip() for line in existing_lines)
81
+
82
+ # If the class name is already imported, skip the addition
83
+ if is_imported:
84
+ print(f"Skipping addition: Import for {file_name} already exists")
85
+ return
86
+
87
+ # Find the position to insert the new import line
88
+ import_section_start = existing_lines.index("from presidio_analyzer.predefined_recognizers import (") + 1
89
+ import_section_end = existing_lines.index(")", import_section_start)
90
+
91
+ en_section_start = lines.index(" \"en\": [\n") # Find the start of the 'en' section
92
+ en_section_end = lines.index(" ],\n", en_section_start) # Find the end of the 'en' section
93
+
94
+ # Check if the import statement already exists in the 'en' section
95
+ is_imported_en = any(file_name.lower() in line.lower().strip() for line in existing_lines[en_section_start:en_section_end])
96
+
97
+ # If the import statement already exists in the 'en' section, skip the addition
98
+ if is_imported_en:
99
+ print(f"Skipping addition: Import for {file_name} already exists in the 'en' section")
100
+ return
101
+
102
+ # Add the filename import to the 'en' section
103
+ lines.insert(en_section_end, f" {file_name},\n")
104
+ # Insert the new import line before the closing parenthesis
105
+ lines.insert(import_section_end, new_import_line + "\n")
106
+
107
+ # Write the modified content back to the file
108
+ with open(recognizer_registry_file, "w") as f:
109
+ f.writelines(lines)
110
+
111
+ print(f"Modified recognizer_registry.py: Added import for {file_name}")
112
+
113
+
114
+ # def modify_recognizer_registry(file_name):
115
+ # script_dir = os.path.dirname(os.path.abspath(__file__))
116
+ # recognizer_registry_file = os.path.join(script_dir, "../Packages/presidio_analyzer/presidio_analyzer/presidio_analyzer/presidio_analyzer/presidio_analyzer/recognizer_registry/recognizer_registry.py")
117
+
118
+ # # Check if the class name is already imported
119
+ # with open(recognizer_registry_file, "r") as f:
120
+ # lines = f.readlines()
121
+
122
+
123
+ # class_name = f"class {file_name}"
124
+ # existing_lines = [line.strip().lower() for line in lines]
125
+ # new_import_line = f" {file_name},"
126
+
127
+
128
+ # # Check if the class name is already imported
129
+ # is_imported = any(class_name.lower() == line.lower().strip() for line in existing_lines)
130
+
131
+ # # If the class name is already imported, skip the addition
132
+ # if is_imported:
133
+ # print(f"Skipping addition: Import for {file_name} already exists")
134
+ # return
135
+
136
+ # # Find the position to insert the new import line
137
+ # import_section_start = existing_lines.index("from presidio_analyzer.predefined_recognizers import (") + 1
138
+ # import_section_end = existing_lines.index(")", import_section_start)
139
+ # en_section_start = lines.index(" \"en\": [\n") # Find the start of the 'en' section
140
+ # en_section_end = lines.index(" ],\n", en_section_start) # Find the end of the 'en' section
141
+ # # Add the filename import to the 'en' section
142
+ # lines.insert(en_section_end, f" {file_name},\n")
143
+ # # Insert the new import line before the closing parenthesis
144
+ # lines.insert(import_section_end, new_import_line + "\n")
145
+
146
+ # # Write the modified content back to the file
147
+ # with open(recognizer_registry_file, "w") as f:
148
+ # f.writelines(lines)
149
+
150
+ # print(f"Modified recognizer_registry.py: Added import for {file_name}")
151
+
152
+ # Adding import in initpy of predefined recognizers
153
+
154
+ def modify_init_py(file_name):
155
+ script_dir = os.path.dirname(os.path.abspath(__file__))
156
+ init_py_file = os.path.join(script_dir, "../../../../presidio_analyzer/presidio_analyzer/Infosys_presidio_analyzer/presidio_analyzer/presidio_analyzer/predefined_recognizers/__init__.py")
157
+
158
+ # Check if the import statement is already present
159
+ with open(init_py_file, "r") as f:
160
+ lines = f.readlines()
161
+
162
+ import_line = f"from .{file_name}_recognizer import {file_name}\n"
163
+
164
+ # Check if the import statement is already present, skip the addition
165
+ is_imported = any(import_line.strip() == line.strip() for line in lines)
166
+
167
+ if is_imported:
168
+ print(f"Skipping addition: Import for {file_name} already exists in __init__.py")
169
+ return
170
+
171
+ # Find the position to insert the new import line
172
+ import_section_end = next(i for i, line in enumerate(lines) if not line.startswith("from "))
173
+
174
+ # Insert the new import line after the last import statement
175
+ lines.insert(import_section_end + 1, import_line)
176
+ # Write the modified content back to the file
177
+ with open(init_py_file, "w") as f:
178
+ f.writelines(lines)
179
+
180
+ print(f"Modified __init__.py: Added import for {file_name}")
181
+
182
+
183
+ # MAKING OF WHEEL FILES
184
+
185
+
186
+ import os
187
+
188
+ def run_wheel_creation_commands():
189
+
190
+ script_dir = os.path.dirname(os.path.abspath(__file__))
191
+ directory = os.path.join(script_dir, "../../../../presidio_analyzer/presidio_analyzer/Infosys_presidio_analyzer")
192
+ # Specify the directory where you want to run the commands
193
+
194
+ # Change to the specified directory
195
+ os.chdir(directory)
196
+
197
+ # Command 1: pip install pyc_wheel build
198
+ command1 = "pip install pyc_wheel build"
199
+ subprocess.run(command1, shell=True, check=True)
200
+
201
+ # Command 2: python create_wheel_file.py
202
+ command2 = "python create_wheel_file.py"
203
+ subprocess.run(command2, shell=True, check=True)
204
+
205
+
206
+ def copy_wheel_file():
207
+ script_dirsourcewheel = os.path.dirname(os.path.abspath(__file__))
208
+ script_dirdestinationwheel = os.path.dirname(os.path.abspath(__file__))
209
+
210
+ source_directory = os.path.join(script_dirsourcewheel, "../../../../presidio_analyzer/presidio_analyzer/Infosys_presidio_analyzer")
211
+ # Get the path of the wheel file
212
+ source_wheel_file = os.path.join(source_directory, "dist", "presidio_analyzer-4.0.5-py3-none-any.whl")
213
+
214
+ destination_directory = os.path.join(script_dirdestinationwheel, "../../../lib")
215
+
216
+ # Get the path of the destination wheel file
217
+ destination_wheel_file = os.path.join(destination_directory, "presidio_analyzer-4.0.5-py3-none-any.whl")
218
+
219
+ # Remove the destination wheel file if it already exists
220
+ if os.path.exists(destination_wheel_file):
221
+ os.remove(destination_wheel_file)
222
+
223
+ # Copy the wheel file to the destination directory
224
+ shutil.copy2(source_wheel_file, destination_wheel_file)
225
+
226
+ # Change to the destination directory
227
+ os.chdir(destination_directory)
228
+
229
+ # Uninstall the previous version of presidio_analyzer
230
+ uninstall_command = "pip uninstall -y presidio_analyzer-4.0.5-py3-none-any.whl"
231
+ subprocess.run(uninstall_command, shell=True, check=True)
232
+
233
+ # Install the new version of presidio_analyzer
234
+ install_command = "pip install presidio_analyzer-4.0.5-py3-none-any.whl"
235
+ subprocess.run(install_command, shell=True, check=True)
236
+
237
+ print("Wheel file copied and installed successfully.")
238
+
239
+
240
+ # # Call the function with the specified directory
241
+ # run_wheel_creation_commands(directory)
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
src/privacy/code_generator/template_recognizer.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ from typing import Optional, List
12
+
13
+ from presidio_analyzer import Pattern, PatternRecognizer
14
+
15
+
16
+ class Class_Name(PatternRecognizer):
17
+ """
18
+ Recognizes US bank number using regex.
19
+
20
+ :param patterns: List of patterns to be used by this recognizer
21
+ :param context: List of context words to increase confidence in detection
22
+ :param supported_language: Language this recognizer supports
23
+ :param supported_entity: The entity this recognizer can detect
24
+ """
25
+
26
+ PATTERNS = [
27
+ Pattern(name="pattern_name", regex="REGEX_PATTERN", score=0.5),
28
+ ]
29
+
30
+ CONTEXT = [
31
+ "bank"
32
+ # Task #603: Support keyphrases: change to "checking account"
33
+ # as part of keyphrase change
34
+ "check",
35
+ "account",
36
+ "account#",
37
+ "acct",
38
+ "save",
39
+ "debit",
40
+ ]
41
+
42
+ def __init__(
43
+ self,
44
+ patterns: Optional[List[Pattern]] = None,
45
+ context: Optional[List[str]] = None,
46
+ supported_language: str = "en",
47
+ supported_entity: str = "Class_Name",
48
+ ):
49
+ patterns = patterns if patterns else self.PATTERNS
50
+ context = context if context else self.CONTEXT
51
+ super().__init__(
52
+ supported_entity=supported_entity,
53
+ patterns=patterns,
54
+ context=context,
55
+ supported_language=supported_language,
56
+ )
src/privacy/config/__init__.py ADDED
File without changes
src/privacy/config/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (229 Bytes). View file
 
src/privacy/config/__pycache__/config.cpython-311.pyc ADDED
Binary file (1.42 kB). View file
 
src/privacy/config/__pycache__/logger.cpython-311.pyc ADDED
Binary file (10.3 kB). View file
 
src/privacy/config/config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ from configparser import ConfigParser
12
+ import yaml
13
+
14
+
15
+ def readConfig(section,filename):
16
+ # create a parser
17
+ parser = ConfigParser()
18
+ # read config file
19
+ parser.read(filename)
20
+
21
+ # get section, default to postgresql
22
+ db = {}
23
+ if parser.has_section(section):
24
+ params = parser.items(section)
25
+ for param in params:
26
+ db[param[0]] = param[1]
27
+ else:
28
+ raise Exception('Section {0} not found in the {1} file'.format(section, filename))
29
+
30
+ return db
31
+
32
+
33
+ def read_config_yaml(filename):
34
+ with open(filename) as config_file:
35
+ config_details = yaml.safe_load(config_file)
36
+ return config_details
src/privacy/config/logger.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import datetime
12
+ import logging
13
+ import os
14
+ import sys
15
+
16
+ import httpx
17
+ from .config import readConfig
18
+ import http
19
+ import contextvars
20
+ # from request_id_store import request_ids
21
+
22
+ import uuid
23
+ # class UserLogger(logging.getLoggerClass()):
24
+ # def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
25
+ # if extra is None:
26
+ # extra = {}
27
+ # extra['user_id'] = self.user_id
28
+ # return super().makeRecord(name, level, fn, lno, msg, args, exc_info, func, extra, sinfo)
29
+ request_ids=[]
30
+ request_id_var = contextvars.ContextVar("request_id_var")
31
+
32
+ class CustomLogger(logging.getLoggerClass()):
33
+ # UserLogger(__)
34
+
35
+ # def __init__(self, user_id):
36
+ # self.user_id = user_id
37
+ # super().__init__(self)
38
+
39
+ # def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
40
+ # if extra is None:
41
+ # extra = {}
42
+ # print("self===",self)
43
+ # extra['user_id'] = self.user_id
44
+ # return super().makeRecord(name, level, fn, lno, msg, args, exc_info, func, extra, sinfo)
45
+
46
+ for request_id in request_ids:
47
+ print("request_id400000000==========",request_id)
48
+ # print("logging.getLoggerClass()",logging.getLoggerClass())
49
+ def __init__(self):
50
+ """Create a custom logger with the specified `name`. When `log_dir` is None, a simple
51
+ console logger is created. Otherwise, a file logger is created in addition to the console
52
+ logger.
53
+
54
+ By default, the five standard logging levels (DEBUG through CRITICAL) only display
55
+ information in the log file if a file handler is added to the logger, but **not** to the
56
+ console.
57
+ :param name: name for the logger
58
+ :param verbose: bool: whether the logging should be verbose; if True, then all messages get
59
+ logged both to stdout and to the log file (if `log_dir` is specified); if False, then
60
+ messages only get logged to the log file (if `log_dir` is specified)
61
+ :param log_dir: str: (optional) the directory for the log file; if not present, no log file
62
+ is created
63
+ """
64
+
65
+ # print("self=====",self)
66
+ # Create custom logger logging all five levels
67
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
68
+ log_cfg_path = os.path.join(BASE_DIR, 'logger.ini')
69
+ # print("log_cfg_path======",log_cfg_path)
70
+ log_params = readConfig('logDetails', log_cfg_path)
71
+ # print("log_params======",log_params)
72
+
73
+ name = log_params['file_name']
74
+ # user_id = log_params['user_id']
75
+ try:
76
+ verbose = bool(log_params['verbose'])
77
+ except:
78
+ verbose = False
79
+
80
+ log_dir = str(log_params['log_dir'])
81
+
82
+ super().__init__(name)
83
+ self.setLevel(logging.DEBUG)
84
+
85
+ # Add new logging level
86
+ logging.addLevelName(logging.INFO, 'INFO')
87
+
88
+ # Determine verbosity settings
89
+ self.verbose = verbose
90
+
91
+ # Create stream handler for logging to stdout (log all five levels)
92
+ self.stdout_handler = logging.StreamHandler(sys.stdout)
93
+ self.stdout_handler.setLevel(logging.DEBUG)
94
+ self.stdout_handler.setFormatter(logging.Formatter('%(message)s'))
95
+ # self.stdout_handler.setFormatter(logging.Formatter('%(user_id)s'))
96
+ self.enable_console_output()
97
+ user_id=12345
98
+ # self.user_id =user_id
99
+ self.file_handler = None
100
+ if log_dir:
101
+ text="Hello WOrld"
102
+ # self.add_file_handler(text, log_dir)
103
+ # self.add_file_handler(user_id,log_dir)
104
+ self.add_file_handler(name, log_dir)
105
+
106
+
107
+
108
+
109
+
110
+
111
+ def add_file_handler(self, name, log_dir):
112
+
113
+ """Add a file handler for this logger with the specified `name` (and store the log file
114
+ under `log_dir`)."""
115
+ # Format for file log
116
+ # heloo = "h"
117
+ # print("self=====",self.user_id)
118
+ # print("log_dir======",user_id)
119
+ # UserLogger(__name__)
120
+ # CustomLogger.user_id = 1
121
+ fmt = '%(asctime)s | %(levelname)9s | %(filename)s:%(lineno)d | %(user_id)s | %(message)s '
122
+ formatter = logging.Formatter(fmt)
123
+
124
+ # Determine log path and file name; create log path if it does not exist
125
+ now = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
126
+ log_name = f'{str(name).replace(" ", "_")}_{now}'
127
+ if not os.path.exists(log_dir):
128
+ try:
129
+ os.makedirs(log_dir)
130
+ except:
131
+ print(f'{self.__class__.__name__}: Cannot create directory {log_dir}. ',
132
+ end='', file=sys.stderr)
133
+ log_dir = '/tmp' if sys.platform.startswith('linux') else '.'
134
+ print(f'Defaulting to {log_dir}.', file=sys.stderr)
135
+
136
+ log_file = os.path.join(log_dir, log_name) + '.log'
137
+
138
+ # Create file handler for logging to a file (log all five levels)
139
+ self.file_handler = logging.FileHandler(log_file)
140
+ self.file_handler.setLevel(logging.DEBUG)
141
+ self.file_handler.setFormatter(formatter)
142
+ self.addHandler(self.file_handler)
143
+
144
+ def has_console_handler(self):
145
+ return len([h for h in self.handlers if type(h) == logging.StreamHandler]) > 0
146
+
147
+ def has_file_handler(self):
148
+ return len([h for h in self.handlers if isinstance(h, logging.FileHandler)]) > 0
149
+
150
+ def disable_console_output(self):
151
+ if not self.has_console_handler():
152
+ return
153
+ self.removeHandler(self.stdout_handler)
154
+
155
+ def enable_console_output(self):
156
+ if self.has_console_handler():
157
+ return
158
+ self.addHandler(self.stdout_handler)
159
+
160
+ def disable_file_output(self):
161
+ if not self.has_file_handler():
162
+ return
163
+ self.removeHandler(self.file_handler)
164
+
165
+ def enable_file_output(self):
166
+ if self.has_file_handler():
167
+ return
168
+ self.addHandler(self.file_handler)
169
+
170
+ def framework(self, msg, *args, **kwargs):
171
+ """Logging method for the FRAMEWORK level. The `msg` gets logged both to stdout and to file
172
+ (if a file handler is present), irrespective of verbosity settings."""
173
+ return super().info(msg, *args, **kwargs)
174
+
175
+ def _custom_log(self, func, msg, *args, **kwargs):
176
+ """Helper method for logging DEBUG through CRITICAL messages by calling the appropriate
177
+ `func()` from the base class."""
178
+ # Log normally if verbosity is on
179
+ if self.verbose:
180
+ return func(msg, *args, **kwargs)
181
+
182
+ # If verbosity is off and there is no file handler, there is nothing left to do
183
+ if not self.has_file_handler():
184
+ return
185
+
186
+ # If verbosity is off and a file handler is present, then disable stdout logging, log, and
187
+ # finally reenable stdout logging
188
+ self.disable_console_output()
189
+ func(msg, *args, **kwargs)
190
+ self.enable_console_output()
191
+
192
+ def getSeesionId():
193
+ # print("request_ids186=========",request_ids)
194
+ request_id = request_id_var.get()
195
+ # print("request_id=========",request_id)
196
+
197
+
198
+
199
+ return request_id
200
+
201
+
202
+
203
+ def debug(self, msg, *args, **kwargs ):
204
+ self._custom_log(super().debug, msg,extra = {'user_id':CustomLogger.getSeesionId()}, *args, **kwargs)
205
+
206
+ def info(self, msg, *args, **kwargs):
207
+ self._custom_log(super().info, msg,extra = {'user_id':CustomLogger.getSeesionId()}, *args, **kwargs)
208
+
209
+ def warning(self, msg,user_id=None, *args, **kwargs):
210
+ self._custom_log(super().warning, msg,extra = {'user_id':CustomLogger.getSeesionId()}, *args, **kwargs)
211
+
212
+ def error(self, msg,user_id=None, *args, **kwargs):
213
+ self._custom_log(super().error, msg,extra = {'user_id':CustomLogger.getSeesionId()}, *args, **kwargs)
214
+
215
+ def critical(self, msg,user_id=None, *args, **kwargs):
216
+ self._custom_log(super().critical, msg,extra = {'user_id':CustomLogger.getSeesionId()}, *args, **kwargs)
217
+
218
+
219
+ if __name__ == "__main__":
220
+ logger= CustomLogger()
221
+
src/privacy/constants/__init__.py ADDED
File without changes
src/privacy/constants/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (232 Bytes). View file
 
src/privacy/constants/__pycache__/local_constants.cpython-311.pyc ADDED
Binary file (704 Bytes). View file
 
src/privacy/constants/local_constants.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ """
12
+ fileName: local_constants.py
13
+ description: Local constants for usecase module
14
+ """
15
+
16
+ DELTED_SUCCESS_MESSAGE="Successfully deleted the usecase :"
17
+ USECASE_ALREADY_EXISTS= "Usecase with name PLACEHOLDER_TEXT already exists"
18
+ USECASE_NOT_FOUND_ERROR="Usecase id PLACEHOLDER_TEXT Not Found"
19
+ USECASE_NAME_VALIDATION_ERROR="Usecase name should not be empty"
20
+ SPACE_DELIMITER=" "
21
+ PLACEHOLDER_TEXT="PLACEHOLDER_TEXT"
src/privacy/dao/AccDataGrpMappingDb.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+ class AccDataGrpDb:
30
+ mycol = mydb["AccDataGrp"]
31
+ def findOne(id):
32
+ values=AccDataGrpDb.mycol.find({"_id":id},{})[0]
33
+ # print(values)
34
+ values=AttributeDict(values)
35
+ return values
36
+ def findall(query):
37
+ value_list=[]
38
+ values=AccDataGrpDb.mycol.find(query,{})
39
+ for v in values:
40
+
41
+ v=AttributeDict(v)
42
+ value_list.append(v)
43
+ return value_list
44
+ def create(value):
45
+ value=AttributeDict(value)
46
+ localTime = time.time()
47
+ mydoc = {
48
+ "_id":localTime,
49
+ "accMasterId":value.Aid,
50
+ "dataRecogGrpId":value.Did,
51
+ "isActive":"Y",
52
+ "isHashify":False,
53
+ "isCreated":"Not Started",
54
+ "CreatedDateTime": datetime.datetime.now(),
55
+ "LastUpdatedDateTime": datetime.datetime.now(),
56
+ }
57
+ PtrnRecogCreatedData = AccDataGrpDb.mycol.insert_one(mydoc)
58
+ return PtrnRecogCreatedData.acknowledged
59
+
60
+ def update(query,value:dict):
61
+
62
+ newvalues = { "$set": value }
63
+
64
+ PtrnRecogUpdatedData=AccDataGrpDb.mycol.update_one(query,newvalues)
65
+ log.debug(str(newvalues))
66
+ return PtrnRecogUpdatedData.acknowledged
67
+
68
+ def delete(id):
69
+ return AccDataGrpDb.mycol.delete_many({"dataRecogGrpId":id}).acknowledged
70
+ # DocProcDtl.mycol.delete_many({})
71
+ # Docpagedtl.mycol.delete_many({})
72
+ def deleteMany(query):
73
+ return AccDataGrpDb.mycol.delete_many(query).acknowledged
74
+
75
+
src/privacy/dao/AccMasterDb.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+ class AccMasterDb:
30
+ mycol = mydb["AccMaster"]
31
+ def findOne(id):
32
+ values=AccMasterDb.mycol.find({"_id":id},{})[0]
33
+ # print(values)
34
+ values=AttributeDict(values)
35
+ return values
36
+ def findall(query):
37
+ value_list=[]
38
+ values=AccMasterDb.mycol.find(query,{})
39
+ for v in values:
40
+
41
+ v=AttributeDict(v)
42
+ value_list.append(v)
43
+ return value_list
44
+ def create(value):
45
+ value=AttributeDict(value)
46
+ localTime = time.time()
47
+ mydoc = {
48
+ "_id":localTime,
49
+ "accMasterId":localTime,
50
+ "portfolio":value.AName,
51
+ "account":value.SName,
52
+ "ThresholdScore":0.85,
53
+ "isActive":"Y",
54
+ "isCreated":"Not Started",
55
+ "CreatedDateTime": datetime.datetime.now(),
56
+ "LastUpdatedDateTime": datetime.datetime.now(),
57
+ }
58
+ PtrnRecogCreatedData = AccMasterDb.mycol.insert_one(mydoc)
59
+ return PtrnRecogCreatedData.inserted_id
60
+
61
+ def update(id,value:dict):
62
+
63
+ newvalues = { "$set": value }
64
+ PtrnRecogUpdatedData=AccMasterDb.mycol.update_one({"_id":id},newvalues)
65
+ log.debug(str(newvalues))
66
+ return PtrnRecogUpdatedData.acknowledged
67
+
68
+ def delete(id):
69
+ return AccMasterDb.mycol.delete_many({"_id":id}).acknowledged
70
+ # DocProcDtl.mycol.delete_many({})
71
+ # Docpagedtl.mycol.delete_many({})
72
+
73
+
src/privacy/dao/AccPtrnMappingDb.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+ class AccPtrnDb:
30
+ mycol = mydb["AccPtrn"]
31
+ def findOne(id):
32
+ values=AccPtrnDb.mycol.find({"_id":id},{})[0]
33
+ # print(values)
34
+ values=AttributeDict(values)
35
+ return values
36
+ def findall(query):
37
+ value_list=[]
38
+ values=AccPtrnDb.mycol.find(query,{})
39
+ for v in values:
40
+
41
+ v=AttributeDict(v)
42
+ value_list.append(v)
43
+ return value_list
44
+ def create(value):
45
+ value=AttributeDict(value)
46
+ localTime = time.time()
47
+ mydoc = {
48
+ "_id":localTime,
49
+ "accMasterId":value.Aid,
50
+ "ptrnRecId":value.Pid,
51
+ "isActive":"Y",
52
+ "isCreated":"Not Started",
53
+ "CreatedDateTime": datetime.datetime.now(),
54
+ "LastUpdatedDateTime": datetime.datetime.now(),
55
+ }
56
+ PtrnRecogCreatedData = AccPtrnDb.mycol.insert_one(mydoc)
57
+ return PtrnRecogCreatedData.inserted_id
58
+
59
+ def update(id,value:dict):
60
+
61
+ newvalues = { "$set": value }
62
+ PtrnRecogUpdatedData=AccPtrnDb.mycol.update_one({"_id":id},newvalues)
63
+ log.debug(str(newvalues))
64
+ return PtrnRecogUpdatedData.acknowledged
65
+
66
+ def delete(id):
67
+ AccPtrnDb.mycol.delete_many({"_id":id})
68
+ # DocProcDtl.mycol.delete_many({})
69
+ # Docpagedtl.mycol.delete_many({})
70
+
71
+
src/privacy/dao/DataRecogdb.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+
30
+ class RecogDb:
31
+ mycol = mydb["Recog"]
32
+ def findOne(id):
33
+ values=RecogDb.mycol.find({"_id":id},{})[0]
34
+ # print(values)
35
+ values=AttributeDict(values)
36
+ return values
37
+ def findall(query):
38
+ value_list=[]
39
+ values=RecogDb.mycol.find(query,{})
40
+ for v in values:
41
+
42
+ v=AttributeDict(v)
43
+ value_list.append(v)
44
+ return value_list
45
+ def create(value):
46
+ value=AttributeDict(value)
47
+ localTime = time.time()
48
+ mydoc = {
49
+ "_id":localTime,
50
+ "RecogId":localTime,
51
+ "RecogName":value.Name,
52
+ "supported_entity":value.entity,
53
+ "RecogType":value.type,
54
+ "Score":value.score,
55
+ "Context":value.context,
56
+ "isEditable":value.edit,
57
+ "isPreDefined":value.define,
58
+ "isActive":"Y",
59
+ "isCreated":"Not Started",
60
+ "CreatedDateTime": datetime.datetime.now(),
61
+ "LastUpdatedDateTime": datetime.datetime.now(),
62
+ }
63
+ PtrnRecogCreatedData = RecogDb.mycol.insert_one(mydoc)
64
+ return PtrnRecogCreatedData.inserted_id
65
+
66
+ def update(id,value:dict):
67
+
68
+ newvalues = { "$set": value }
69
+ PtrnRecogUpdatedData=RecogDb.mycol.update_one({"_id":id},newvalues)
70
+ log.debug(str(newvalues))
71
+ return PtrnRecogUpdatedData.acknowledged
72
+
73
+ def delete(id):
74
+ RecogDb.mycol.delete_many({"_id":id})
75
+ # DocProcDtl.mycol.delete_many({})
76
+ # Docpagedtl.mycol.delete_many({})
77
+
78
+
src/privacy/dao/DatabaseConnection.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+
12
+ import os
13
+ import pymongo
14
+
15
+ from dotenv import load_dotenv
16
+ from privacy.config.logger import CustomLogger
17
+ import sys
18
+ load_dotenv()
19
+
20
+ log = CustomLogger()
21
+
22
+
23
+ class DB:
24
+ def connect():
25
+ try:
26
+ myclient = pymongo.MongoClient(os.getenv("MONGO_PATH"))
27
+ mydb = myclient[os.getenv("DB_NAME")]
28
+ return mydb
29
+ except Exception as e:
30
+ log.info(str(e))
31
+ sys.exit()
32
+
src/privacy/dao/EntityDb.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+ class EntityDb:
30
+ mycol = mydb["Entity"]
31
+ def findOne(id):
32
+ values=EntityDb.mycol.find({"_id":id},{})[0]
33
+ # print(values)
34
+ values=AttributeDict(values)
35
+ return values
36
+ def findall(query):
37
+ value_list=[]
38
+ values=EntityDb.mycol.find(query,{})
39
+ for v in values:
40
+
41
+ v=AttributeDict(v)
42
+ value_list.append(v)
43
+ return value_list
44
+ def create(value):
45
+ value=AttributeDict(value)
46
+ localTime = time.time()
47
+ mydoc = {
48
+ "_id":localTime,
49
+ "EntityId":localTime,
50
+ "EntityName":value.Name,
51
+ "RecogId":value.dgid,
52
+ }
53
+ PtrnRecogCreatedData = EntityDb.mycol.insert_one(mydoc)
54
+ return PtrnRecogCreatedData.acknowledged
55
+
56
+ def update(id,value:dict):
57
+
58
+ newvalues = { "$set": value }
59
+ PtrnRecogUpdatedData=EntityDb.mycol.update_one({"_id":id},newvalues)
60
+ log.debug(str(newvalues))
61
+ return PtrnRecogUpdatedData.acknowledged
62
+
63
+ def delete(id):
64
+ x=EntityDb.mycol.delete_many({"_id":id})
65
+ return x.acknowledged
66
+ # DocProcDtl.mycol.delete_many({})
67
+ # Docpagedtl.mycol.delete_many({})
68
+ def deleteMany(query):
69
+ x=EntityDb.mycol.delete_many(query)
70
+ return x.acknowledged
src/privacy/dao/TelemetryFlagDb.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import pymongo
12
+ import datetime,time
13
+ from privacy.dao.DatabaseConnection import DB
14
+ from dotenv import load_dotenv
15
+ from privacy.config.logger import CustomLogger
16
+
17
+ load_dotenv()
18
+ log = CustomLogger()
19
+
20
+ class AttributeDict(dict):
21
+ __getattr__ = dict.__getitem__
22
+ __setattr__ = dict.__setitem__
23
+ __delattr__ = dict.__delitem__
24
+
25
+
26
+ mydb=DB.connect()
27
+
28
+
29
+
30
+ class TelemetryFlag:
31
+ mycol = mydb["TelemetryFlag"]
32
+ def findOne(id):
33
+ values=TelemetryFlag.mycol.find({"_id":id},{})[0]
34
+ # print(values)
35
+ values=AttributeDict(values)
36
+ return values
37
+ def findall(query):
38
+ value_list=[]
39
+ values=TelemetryFlag.mycol.find(query,{})
40
+ for v in values:
41
+
42
+ v=AttributeDict(v)
43
+ value_list.append(v)
44
+ return value_list
45
+ def create(value):
46
+ value=AttributeDict(value)
47
+ localTime = time.time()
48
+ mydoc = {
49
+ "_id":localTime,
50
+ "Module":value.module,
51
+ "TelemetryFlag":False,
52
+ "CreatedDateTime": datetime.datetime.now(),
53
+ "LastUpdatedDateTime": datetime.datetime.now(),
54
+ }
55
+ PtrnRecogCreatedData = TelemetryFlag.mycol.insert_one(mydoc)
56
+ return PtrnRecogCreatedData.inserted_id
57
+
58
+ def update(id,value:dict):
59
+
60
+ newvalues = { "$set": value }
61
+ PtrnRecogUpdatedData=TelemetryFlag.mycol.update_one({"_id":id},newvalues)
62
+ log.debug(str(newvalues))
63
+ return PtrnRecogUpdatedData.acknowledged
64
+
65
+ def delete(id):
66
+ TelemetryFlag.mycol.delete_many({"_id":id})
67
+ # DocProcDtl.mycol.delete_many({})
68
+ # Docpagedtl.mycol.delete_many({})
69
+
70
+
src/privacy/dao/__init__.py ADDED
File without changes
src/privacy/dao/privacy/DatabaseConnection.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ © <2023> Infosys Limited, Bangalore, India. All Rights Reserved.
3
+ Version:
4
+ Except for any free or open source software components embedded in this Infosys proprietary software program (“Program”), this Program is protected by copyright laws, international treaties and other pending or existing intellectual property rights in India, the United States and other countries. Except as expressly permitted, any unauthorized reproduction, storage, transmission in any form or by any means (including without limitation electronic, mechanical, printing, photocopying, recording or otherwise), or any distribution of this Program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under the law.
5
+ '''
6
+
7
+ import os
8
+ import pymongo
9
+
10
+ from dotenv import load_dotenv
11
+ from privacy.config.logger import CustomLogger
12
+ import sys
13
+ load_dotenv()
14
+
15
+ log = CustomLogger()
16
+
17
+
18
+ class DB:
19
+ def connect():
20
+ try:
21
+ myclient = pymongo.MongoClient(os.getenv("MONGO_PATH"))
22
+ mydb = myclient[os.getenv("PRIVACY_DB_NAME")]
23
+ return mydb
24
+ except Exception as e:
25
+ log.info(str(e))
26
+ sys.exit()
27
+
src/privacy/dao/privacy/PrivacyException.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ © <2023> Infosys Limited, Bangalore, India. All Rights Reserved.
3
+ Version:
4
+ Except for any free or open source software components embedded in this Infosys proprietary software program (“Program”), this Program is protected by copyright laws, international treaties and other pending or existing intellectual property rights in India, the United States and other countries. Except as expressly permitted, any unauthorized reproduction, storage, transmission in any form or by any means (including without limitation electronic, mechanical, printing, photocopying, recording or otherwise), or any distribution of this Program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under the law.
5
+ '''
6
+ import pymongo
7
+ import datetime,time
8
+ from privacy.dao.privacy.DatabaseConnection import DB
9
+ from dotenv import load_dotenv
10
+ from privacy.config.logger import CustomLogger
11
+
12
+ load_dotenv()
13
+ log = CustomLogger()
14
+
15
+ class AttributeDict(dict):
16
+ __getattr__ = dict.__getitem__
17
+ __setattr__ = dict.__setitem__
18
+ __delattr__ = dict.__delitem__
19
+
20
+
21
+ mydb=DB.connect()
22
+
23
+
24
+
25
+ class ExceptionDb:
26
+ mycol = mydb["PrivacyException"]
27
+ def findOne(id):
28
+ values=ExceptionDb.mycol.find({"_id":id},{})[0]
29
+ # print(values)
30
+ values=AttributeDict(values)
31
+ return values
32
+ def findall(query):
33
+ value_list=[]
34
+ values=ExceptionDb.mycol.find(query,{})
35
+ for v in values:
36
+
37
+ v=AttributeDict(v)
38
+ value_list.append(v)
39
+ return value_list
40
+ def create(value):
41
+ value=AttributeDict(value)
42
+ localTime = time.time()
43
+ mydoc = {
44
+ "_id":localTime,
45
+ "ExceptionId":localTime,
46
+ "UUID":value.UUID,
47
+ "function":value.function,
48
+ "msg":value.msg,
49
+ "description":value.description,
50
+ "CreatedDateTime": datetime.datetime.now(),
51
+ }
52
+ PtrnRecogCreatedData = ExceptionDb.mycol.insert_one(mydoc)
53
+ return PtrnRecogCreatedData.inserted_id
54
+
55
+ def update(id,value:dict):
56
+
57
+ newvalues = { "$set": value }
58
+ PtrnRecogUpdatedData=ExceptionDb.mycol.update_one({"_id":id},newvalues)
59
+ log.debug(str(newvalues))
60
+ return PtrnRecogUpdatedData.acknowledged
61
+
62
+ def delete(id):
63
+ ExceptionDb.mycol.delete_many({"_id":id})
64
+ # DocProcDtl.mycol.delete_many({})
65
+ # Docpagedtl.mycol.delete_many({})
66
+
67
+
src/privacy/dao/privacy/TelemetryDb.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ © <2023> Infosys Limited, Bangalore, India. All Rights Reserved.
3
+ Version:
4
+ Except for any free or open source software components embedded in this Infosys proprietary software program (“Program”), this Program is protected by copyright laws, international treaties and other pending or existing intellectual property rights in India, the United States and other countries. Except as expressly permitted, any unauthorized reproduction, storage, transmission in any form or by any means (including without limitation electronic, mechanical, printing, photocopying, recording or otherwise), or any distribution of this Program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under the law.
5
+ '''
6
+ import pymongo
7
+ import datetime,time
8
+ from privacy.dao.privacy.DatabaseConnection import DB
9
+ from dotenv import load_dotenv
10
+ from privacy.config.logger import CustomLogger
11
+
12
+ load_dotenv()
13
+ log = CustomLogger()
14
+
15
+ class AttributeDict(dict):
16
+ __getattr__ = dict.__getitem__
17
+ __setattr__ = dict.__setitem__
18
+ __delattr__ = dict.__delitem__
19
+
20
+
21
+ mydb=DB.connect()
22
+
23
+
24
+
25
+ class TelemetryDb:
26
+ mycol = mydb["PrivacyTelemetry"]
27
+ def findOne(id):
28
+ values=TelemetryDb.mycol.find({"_id":id},{})[0]
29
+ # print(values)
30
+ values=AttributeDict(values)
31
+ return values
32
+ def findall(query):
33
+ value_list=[]
34
+ values=TelemetryDb.mycol.find(query,{})
35
+ for v in values:
36
+ v=AttributeDict(v)
37
+ value_list.append(v)
38
+ return value_list
39
+ def create(value):
40
+ log.debug("Create telemetry data")
41
+ value=AttributeDict(value)
42
+ localTime = time.time()
43
+ mydoc = {
44
+ "_id":localTime,
45
+ "uniqueid":value.uniqueid,
46
+ "tenant":value.tenant,
47
+ "apiname":value.apiname,
48
+ "user":value.user,
49
+ "lotNumber": value.lotNumber,
50
+ # "exclusionList":value.exclusionList,
51
+ "date": value.date,
52
+ "request":value.request,
53
+ "response":value.response,
54
+ }
55
+ PtrnRecogCreatedData = TelemetryDb.mycol.insert_one(mydoc)
56
+ return PtrnRecogCreatedData.inserted_id
57
+
58
+ def update(id,value:dict):
59
+
60
+ newvalues = { "$set": value }
61
+ PtrnRecogUpdatedData=TelemetryDb.mycol.update_one({"_id":id},newvalues)
62
+ log.debug(str(newvalues))
63
+ return PtrnRecogUpdatedData.acknowledged
64
+
65
+ def delete(id):
66
+ TelemetryDb.mycol.delete_many({"_id":id})
67
+ # DocProcDtl.mycol.delete_many({})
68
+ # Docpagedtl.mycol.delete_many({})
69
+
70
+
src/privacy/dao/temp.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ pydantic
3
+ uvicorn
4
+ certifi
5
+ FastAPI-SQLAlchemy
6
+ pip
7
+ PyYAML
8
+ pandas
9
+ python-multipart
10
+ pymongo
11
+ python-dotenv
12
+ requests
13
+ requests-file
14
+ setuptools
15
+ SQLAlchemy
16
+ starlette
17
+ typer
18
+ typing_extensions
19
+ urllib3
20
+ wasabi
21
+ #https://huggingface.co/spacy/en_core_web_lg/resolve/main/en_core_web_lg-any-py3-none-any.whl
22
+ #../lib/presidio_analyzer-4.0.6-py3-none-any.whl
23
+ ../lib/aicloudlibs-0.1.0-py3-none-any.whl
24
+ #../lib/en_core_web_lg-any-py3-none-any.whl
src/privacy/exception/__init__.py ADDED
File without changes
src/privacy/exception/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (232 Bytes). View file
 
src/privacy/exception/__pycache__/exception.cpython-311.pyc ADDED
Binary file (2.99 kB). View file
 
src/privacy/exception/exception.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ """
12
+ fileName: exception.py
13
+ description: handles usecase module specific exception
14
+ """
15
+
16
+ import sys, traceback
17
+
18
+ from privacy.constants.local_constants import SPACE_DELIMITER,PLACEHOLDER_TEXT,USECASE_ALREADY_EXISTS,USECASE_NOT_FOUND_ERROR,USECASE_NAME_VALIDATION_ERROR
19
+
20
+ from aicloudlibs.constants import constants as global_constants
21
+ from abc import ABC
22
+
23
+
24
+ class PrivacyException(Exception, ABC):
25
+ """
26
+ dscription: Abstract base class of UsecaseException.
27
+ """
28
+
29
+ def __init__(self, detail: str) -> None:
30
+ self.status_code = global_constants.HTTP_STATUS_BAD_REQUEST
31
+ super().__init__(detail)
32
+
33
+
34
+ class PrivacyNotFoundError(PrivacyException):
35
+ """
36
+ description: UsecaseNotFoundError thrown by usecase service
37
+ when the requested usecase details not found for a specific user.
38
+ """
39
+ def __init__(self,name):
40
+ self.status_code = global_constants.HTTP_STATUS_NOT_FOUND
41
+ self.detail = USECASE_NOT_FOUND_ERROR.replace(PLACEHOLDER_TEXT,name)
42
+
43
+ class PrivacyNameNotEmptyError(PrivacyException):
44
+ """
45
+ description: UsecaseNameNotEmptyError thrown by create usecase service
46
+ when the requested usecase details not having usecase name.
47
+ """
48
+ def __init__(self,name):
49
+ self.status_code = global_constants.HTTP_STATUS_409_CODE
50
+ self.detail = USECASE_NAME_VALIDATION_ERROR
src/privacy/mappers/__init__.py ADDED
File without changes
src/privacy/mappers/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (230 Bytes). View file
 
src/privacy/mappers/__pycache__/mappers.cpython-311.pyc ADDED
Binary file (7.57 kB). View file
 
src/privacy/mappers/mappers.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ """
12
+ fileName: mappers.py
13
+ description: A Pydantic model object for usecase entity model
14
+ which maps the data model to the usecase entity schema
15
+ """
16
+
17
+ from pydantic import BaseModel, Field
18
+ from datetime import datetime
19
+ from typing import Optional,Union, List
20
+
21
+ """
22
+ description: piiEntity
23
+ params:
24
+ """
25
+
26
+
27
+ class PIIEntity(BaseModel):
28
+ type: Optional[str] = Field(example="US_SSN")
29
+ beginOffset: Optional[int] = Field(example=19)
30
+ endOffset: Optional[int] = Field(example=28)
31
+ score:Optional[float]=Field(example=1.1)
32
+ responseText:Optional[str]=Field(example="012884567")
33
+
34
+ class Config:
35
+ orm_mode = True
36
+
37
+ class PIIItems(BaseModel):
38
+ start: Optional[int] = Field(example=19)
39
+ end: Optional[int] = Field(example=28)
40
+ entity_type: Optional[str] = Field(example="US_SSN")
41
+ text:Optional[str]=Field(example="John Smith's SSN is 012884567")
42
+ operator:Optional[str]= Field(example="encrypt")
43
+
44
+ class Config:
45
+ orm_mode = True
46
+
47
+ class PIIImageEntity(BaseModel):
48
+ type: str = Field(example="US_SSN")
49
+
50
+ class Config:
51
+ orm_mode = True
52
+
53
+ class PIIAnalyzeRequest(BaseModel):
54
+ inputText: str = Field(example="John Smith's SSN is 012884567")
55
+ # entity_type: Optional[str] = Field(example="COMPANY_NAME")
56
+ portfolio:Optional[str] = Field(example="string")
57
+ account:Optional[str] = Field(example="string")
58
+ exclusionList:Optional[str] = Field(example="Karan,Infosys")
59
+ user: Optional[str] = Field(None)
60
+ lotNumber:Optional[str] = Field(None)
61
+
62
+ class PIIEncryptResponse(BaseModel):
63
+ text: str = Field(example="John Smith's SSN is 012884567")
64
+ items: List[PIIItems]
65
+
66
+ class Config:
67
+ orm_mode = True
68
+
69
+ class PIIDecryptRequest(BaseModel):
70
+ text: str = Field(example="John Smith's SSN is 012884567")
71
+ items: List[PIIItems]
72
+
73
+ class PIIAnalyzeResponse(BaseModel):
74
+ PIIEntities: List[PIIEntity]
75
+
76
+ class Config:
77
+ orm_mode = True
78
+
79
+
80
+ class PIIAnonymizeRequest(BaseModel):
81
+ inputText: str = Field(example="John Smith's SSN is 012884567")
82
+ portfolio:Optional[str] = Field(example="string")
83
+ account:Optional[str] = Field(example="string")
84
+ exclusionList:Optional[str] = Field(example="Karan,Infosys")
85
+ piiEntitiesToBeRedacted: Optional[list] = Field(example=["US_SSN"])
86
+ redactionType: Optional[str] = Field(example='replace')
87
+ user: Optional[str] = Field(example = None)
88
+ lotNumber:Optional[str] = Field(example = None)
89
+ fakeData: Optional[bool] = Field(example = False)
90
+
91
+
92
+
93
+ class PIIAnonymizeResponse(BaseModel):
94
+ anonymizedText: str = Field(example="John Smith's SSN is <US_SSN>")
95
+
96
+ class Config:
97
+ orm_mode = True
98
+
99
+ class PIIDecryptResponse(BaseModel):
100
+ decryptedText: str = Field(example="John Smith's SSN is <US_SSN>")
101
+
102
+ class Config:
103
+ orm_mode = True
104
+
105
+ #class Image
106
+ class PIIImageAnalyzeRequest(BaseModel):
107
+ class Config:
108
+ orm_mode = True
109
+
110
+ class PIIImageAnonymizeResponse(BaseModel):
111
+ base64text: str=Field(example="kshdbfbfwbedhbaskjbakbsakjnalhbsfsfvslkjdnlkjdsnkdsbflkjsbdsklakbkdb")
112
+
113
+ class Config:
114
+ orm_mode = True
115
+
116
+ class PIIImageEntity(BaseModel):
117
+ type: str = Field(example="US_SSN")
118
+
119
+ class Config:
120
+ orm_mode = True
121
+
122
+ class PIIImageAnalyzeResponse(BaseModel):
123
+ PIIEntities: List[PIIImageEntity]
124
+
125
+ class Config:
126
+ orm_mode = True
127
+
128
+ class PIIMultipleImageAnalyzeResponse(BaseModel):
129
+ PIIEntities: List[List[PIIImageEntity]]
130
+
131
+ class Config:
132
+ orm_mode = True
133
+
134
+
135
+
136
+ class PIIPrivacyShieldRequest(BaseModel):
137
+ inputText: str = Field(example="John Smith's SSN is 012884567")
138
+ # entity_type: Optional[str] = Field(example="COMPANY_NAME")
139
+ portfolio:Optional[str] = Field(example="string")
140
+ account:Optional[str] = Field(example="string")
141
+
142
+
143
+
144
+
145
+
146
+ class PrivacyShield(BaseModel):
147
+ entitiesRecognised:list = Field(example=["US_SSN"])
148
+ entitiesConfigured :list = Field(example=["US_SSN"])
149
+ result:str =""
150
+
151
+ class PIIPrivacyShieldResponse(BaseModel):
152
+ privacyCheck: List[PrivacyShield]
153
+
154
+ class Config:
155
+ orm_mode = True
156
+
157
+
158
+
159
+ class LogoHidingResponse(BaseModel):
160
+ base64text: str=Field(example="kshdbfbfwbedhbaskjbakbsakjnalhbsfsfvslkjdnlkjdsnkdsbflkjsbdsklakbkdb")
161
+
162
+ class Config:
163
+ orm_mode = True
164
+
165
+ class Telemetry(BaseModel):
166
+ Module:str= Field(example = "Privacy")
167
+ TelemetryFlagValue : bool = Field(example=True)
168
+
169
+
170
+ class TelemetryResponse(BaseModel):
171
+ result : List[Telemetry]
172
+
173
+ class Config:
174
+ orm_mode = True
175
+
176
+ class PIICodeDetectRequest(BaseModel):
177
+ inputText: str = Field(example="John Smith's SSN is 012884567")
src/privacy/routing/__init__.py ADDED
File without changes
src/privacy/routing/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (230 Bytes). View file
 
src/privacy/routing/__pycache__/privacy_router.cpython-311.pyc ADDED
Binary file (11 kB). View file
 
src/privacy/routing/privacy_router.py ADDED
@@ -0,0 +1,1747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ from io import BytesIO
12
+ from tempfile import NamedTemporaryFile
13
+ import threading
14
+ import time
15
+ import uuid
16
+
17
+ import requests
18
+ from privacy.util.code_detect.ner.pii_inference.netcustom import code_detect_ner
19
+ from privacy.util.code_detect.ner.CodePIINER import codeNer
20
+ # from privacy.dao.TelemetryFlagDb import TelemetryFlag
21
+ from fastapi import Depends, Query,Request,APIRouter, HTTPException, WebSocket,websockets,FastAPI,Cookie,Body
22
+ from typing import List, Union
23
+
24
+ from privacy.service.privacytelemetryservice import PrivacyTelemetryRequest
25
+ from privacy.service.Video_service import *
26
+
27
+ from fastapi.params import Form
28
+ from privacy.mappers.mappers import *
29
+ #from privacy.mappers.mappers import PIIEntity, PIIAnalyzeRequest, PIIAnonymizeResponse, PIIAnonymizeRequest,PIIAnalyzeResponse,PIIImageAnonymizeResponse,PIIImageAnalyzeResponse,PIIImageAnalyzeRequest
30
+
31
+
32
+ from privacy.service.Video_service import VideoService
33
+ # from privacy.service.logo_service import Logo
34
+ from privacy.service.code_detect_service import *
35
+ from privacy.service.excel_service import Excel
36
+
37
+ from privacy.exception.exception import PrivacyException
38
+ from privacy.config.logger import CustomLogger
39
+
40
+ from fastapi import FastAPI, UploadFile,File
41
+ from fastapi.responses import FileResponse
42
+ from datetime import date
43
+ import concurrent.futures
44
+ from fastapi import Request
45
+ from fastapi.responses import StreamingResponse
46
+ from privacy.util.code_detect.ner.pii_inference.netcustom import *
47
+ # from privacy.util.face_detect.mask_detect_video import mask_video
48
+ import logging
49
+ # from privacy.code_generator.codegeneration import create_new_recognizer_file,modify_recognizer_registry,modify_init_py,run_wheel_creation_commands, copy_wheel_file,test
50
+ # from privacy.dao.privacy.PrivacyException import ExceptionDb
51
+ # from privacy.dao.privacy.TelemetryDb import TelemetryDb
52
+ from privacy.service.api_req import *
53
+ from privacy.service.__init__ import *
54
+ from privacy.service.textPrivacy import TextPrivacy,Shield
55
+ from privacy.service.imagePrivacy import ImagePrivacy
56
+ from privacy.service.dicomPrivacy import DICOMPrivacy
57
+ import cv2
58
+ import numpy as np
59
+ router = APIRouter()
60
+ # user_id=1234
61
+ log=CustomLogger()
62
+ app = FastAPI()
63
+
64
+ fileRouter=APIRouter()
65
+ # logger = UserLogger()
66
+
67
+ import tracemalloc
68
+ from transformers import AutoModelForTokenClassification, AutoTokenizer
69
+ #@router.post('/privacy/text/analyze', response_model= PIIAnalyzeResponse)
70
+ today = date.today()
71
+ from datetime import datetime
72
+ import asyncio
73
+ from dotenv import load_dotenv
74
+ load_dotenv()
75
+ # import gc
76
+ import os
77
+ from uuid import UUID, uuid4
78
+ # from fastapi_sessions.backends.implementations import InMemoryBackend
79
+ # from fastapi_sessions.frontends.implementations import SessionCookie, CookieParameters
80
+ # from request_id_store import request_ids
81
+ from privacy.config.logger import request_id_var
82
+ import traceback
83
+ from fastapi import APIRouter, HTTPException, Request, Depends
84
+ from pydantic import BaseModel
85
+ from fastapi.responses import JSONResponse
86
+ from privacy.util.auth.auth_client_id import get_auth_client_id
87
+ from privacy.util.auth.auth_jwt import get_auth_jwt
88
+ from privacy.util.auth.auth_none import get_auth_none
89
+
90
+ # from fastapi.se
91
+
92
+ # from fastapi_session import get_session
93
+ # returns current date and time
94
+ now = datetime.now()
95
+ # from memory_profiler import profile
96
+ # telFlagData = TelemetryFlag.findall({})[0]
97
+ # tel_Falg = telFlagData["TelemetryFlag"]
98
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})
99
+ # print("Teldata==",telFlagData)
100
+ # if(len(telFlagData) == 0):
101
+ # telData = TelemetryFlag.create({"module":"Privacy"})
102
+ # print("telData===",telData)
103
+ magMap = {"True": True, "False": False,"true": True, "false": False}
104
+ tel_Falg=os.getenv("TELE_FLAG")
105
+ tel_Falg=magMap[tel_Falg]
106
+ # tel_Falg = os.getenv("TELE_FLAG", "False") # Default to "False" if TELE_FLAG is not set
107
+ # tel_Falg = magMap.get(tel_Falg, False) # Use .get() to safely access the dictionary and default to False if the key doesn't exist
108
+ # print("===============",tel_Falg,type(tel_Falg))
109
+ privacytelemetryurl = os.getenv("PRIVACY_TELEMETRY_URL")
110
+ privacyerrorteleurl = os.getenv("PRIVACY_ERROR_URL")
111
+
112
+ # print("tel_falg===",tel_Falg)
113
+ # Load the model and tokenizer for CODEFILE API
114
+ local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
115
+ model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
116
+ tokenizer = AutoTokenizer.from_pretrained(local_model_directory, model_max_length=10000)
117
+
118
+
119
+
120
+ class NoAccountException(Exception):
121
+ pass
122
+
123
+ class NoAdminConnException(Exception):
124
+ pass
125
+
126
+
127
+
128
+ ## FUNCTION FOR FAIL_SAFE TELEMETRY
129
+ def send_telemetry_request(privacy_telemetry_request):
130
+ id = uuid.uuid4().hex
131
+ request_id_var.set("telemetry")
132
+
133
+ try:
134
+ # print("==",privacy_telemetry_request)
135
+ log.debug("teleReq="+str(privacy_telemetry_request))
136
+
137
+ response = requests.post(privacytelemetryurl, json=privacy_telemetry_request)
138
+ # print/("===,",response)
139
+ response.raise_for_status()
140
+ response_data = response.json()
141
+ log.debug("tele data response: "+ str(response))
142
+ # print(response_data)
143
+ except Exception as e:
144
+ log.error(str(e))
145
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"send_telemetry_requestFunction","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
146
+ raise HTTPException(
147
+ status_code=500,
148
+ detail="Please check with administration!!",
149
+ headers={"X-Error": "Please check with administration!!"})
150
+
151
+
152
+ class Telemetry:
153
+ def error_telemetry_request(errobj,id):
154
+ request_id_var.set(id)
155
+
156
+ try:
157
+ # print("==",privacy_telemetry_request)
158
+ log.debug("teleReq="+str(errobj))
159
+ if(tel_Falg):
160
+
161
+ response = requests.post(privacyerrorteleurl, json=errobj)
162
+ # print("===,",response)
163
+ response.raise_for_status()
164
+ response_data = response.json()
165
+ log.debug("tele error response: "+ str(response))
166
+ # print(response_data)
167
+ except Exception as e:
168
+ log.error(str(e))
169
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"send_telemetry_requestFunction","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
170
+ raise HTTPException(
171
+ status_code=500,
172
+ detail="Please check with administration!!",
173
+ headers={"X-Error": "Please check with administration!!"})
174
+
175
+
176
+
177
+ # Authentication
178
+
179
+ auth_type = os.environ.get("AUTH_TYPE")
180
+
181
+ if auth_type == "azure":
182
+ auth = get_auth_client_id()
183
+ elif auth_type == "jwt":
184
+ auth = get_auth_jwt()
185
+
186
+ elif auth_type == 'none':
187
+ auth = get_auth_none()
188
+ else:
189
+ raise HTTPException(status_code=500, detail="Invalid authentication type configured")
190
+
191
+
192
+ router = APIRouter()
193
+
194
+
195
+ @router.post('/privacy/text/analyze', response_model= PIIAnalyzeResponse)
196
+ # @profile
197
+ def analyze(payload: PIIAnalyzeRequest,auth= Depends(auth)):
198
+
199
+ # gc.collect()
200
+ id = uuid.uuid4().hex
201
+ request_id_var.set(id)
202
+ log.info("Entered into analyze routing method" )
203
+
204
+ try:
205
+ log.debug("request payload: "+ str(payload))
206
+ startTime = time.time()
207
+ log.debug("Entered into analyze function")
208
+ tracemalloc.start()
209
+ # raise Exception()
210
+ response = TextPrivacy.analyze(payload)
211
+ ApiCall.delAdminList()
212
+ tracemalloc.stop()
213
+ log.debug("Returned from analyze function")
214
+ endTime = time.time()
215
+ totalTime = endTime - startTime
216
+
217
+ log.info("Total Time taken "+str(totalTime))
218
+ if(response==None):
219
+ # print("Inside Raise Exception")
220
+ # return "Portfolio/Account Is Incorrect"
221
+ raise NoAccountException
222
+ # print("---",response.admin)
223
+ if(response==404):
224
+ raise NoAdminConnException
225
+ # raise HTTPException(
226
+ # status_code=430,
227
+ # detail="Portfolio/Account Is Incorrect",
228
+ # headers={"X-Error": "There goes my error"},
229
+
230
+ # )
231
+
232
+ log.debug("response : "+ str(response))
233
+ log.info("exit create from analyze routing method")
234
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
235
+ # tel_Falg = telFlagData["TelemetryFlag"]
236
+ log.debug("TelFlag==="+ str(tel_Falg))
237
+ # TelemetryDb.create({"UUID":id,"tenant":"privacy","apiName":analyze.__name__,"portfolio":payload.portfolio,"accountName":payload.account,"exclusion_list":payload.exclusionList,"entityrecognised":"Text"})
238
+ if(tel_Falg == True):
239
+ responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
240
+ requestList = payload.__dict__
241
+ requestObj = {
242
+ "portfolio_name": payload.portfolio if payload.portfolio is not None else "None",
243
+ "account_name": payload.account if payload.account is not None else "None",
244
+ "inputText": requestList["inputText"],
245
+ "exclusion_list": requestList["exclusionList"].split(',') if requestList["exclusionList"] is not None else [],
246
+ }
247
+ # lotNumber = 0 # Initialize lotNumber with a default value
248
+ # if payload.lotNumber is not None:
249
+ # lotNumber = payload.lotNumber
250
+
251
+ telemetryPayload = {
252
+ "uniqueid": id,
253
+ "tenant": "privacy",
254
+ "apiname": analyze.__name__,
255
+ "user": payload.user if payload.user is not None else "None",
256
+ "date":now.isoformat(),
257
+ "lotNumber": payload.lotNumber if payload.lotNumber is not None else "None",
258
+ # "exclusionList": payload.exclusionList,
259
+ "request": requestObj,
260
+ "response": responseList
261
+ }
262
+ # TelemetryDb.create(telemetryPayload)
263
+
264
+ # Trigger the API call asynchronously using a separate thread
265
+ with concurrent.futures.ThreadPoolExecutor() as executor:
266
+ executor.submit(send_telemetry_request, telemetryPayload)
267
+ log.info("******TELEMETRY REQUEST COMPLETED********")
268
+ # responseprivacytelemetry = requests.post(privacytelemetryurl, json=privacy_telemetry_request.__dict__)
269
+ # gc.collect()
270
+ return response
271
+ except PrivacyException as cie:
272
+ log.debug("Exception for analyze")
273
+ log.error(cie.__dict__)
274
+
275
+ er=[{"UUID":request_id_var.get(),"function":"textAnalyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
276
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
277
+ logobj = {"uniqueid":id,"error":er}
278
+ #
279
+ if len(er)!=0:
280
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
281
+ thread.start()
282
+ if request_id_var.get() in error_dict:
283
+ del error_dict[id]
284
+ # ExceptionDb.create({"UUID":id,"function":"textAnalyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
285
+ # print(cie)
286
+ # print(cie.__dict__)
287
+ log.error(cie, exc_info=True)
288
+ log.info("exit create from analyze routing method")
289
+ raise HTTPException(**cie.__dict__)
290
+ except NoAccountException:
291
+ raise HTTPException(
292
+ status_code=430,
293
+ detail="Portfolio/Account Is Incorrect",
294
+ headers={"X-Error": "There goes my error"},
295
+ )
296
+ except NoAdminConnException:
297
+ raise HTTPException(
298
+ status_code=435,
299
+ detail=" Accounts and Portfolio not available with the Subscription!!",
300
+ headers={"X-Error": "Admin Connection is not established,"},
301
+ )
302
+ except Exception as e:
303
+ log.error(str(e))
304
+ # print(error_dict)
305
+ er=[{"UUID":request_id_var.get(),"function":"textAnalyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
306
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
307
+ logobj = {"uniqueid":id,"error":er}
308
+ #
309
+ if len(er)!=0:
310
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
311
+ thread.start()
312
+ if request_id_var.get() in error_dict:
313
+ del error_dict[id]
314
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnalyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
315
+ raise HTTPException(
316
+ status_code=500,
317
+ detail="Please check with administration!!",
318
+ headers={"X-Error": "Please check with administration!!"})
319
+
320
+ @router.post('/privacy/text/anonymize', response_model= PIIAnonymizeResponse)
321
+ def anonymize(payload: PIIAnonymizeRequest,auth= Depends(auth)):
322
+
323
+ id = uuid.uuid4().hex
324
+ request_id_var.set(id)
325
+
326
+ log.info("Entered create into anonymize routing method")
327
+ try:
328
+ # log.info("Entered create usecase routing method" )
329
+ log.debug("request payload: "+ str(payload))
330
+ startTime = time.time()
331
+ log.debug("Entered into anonymize function")
332
+ response = TextPrivacy.anonymize(payload)
333
+ ApiCall.delAdminList()
334
+ log.debug("Returned from anonymize function")
335
+ endTime = time.time()
336
+ totalTime = endTime - startTime
337
+ log.info("Total Time taken "+str(totalTime))
338
+ if(response==None):
339
+ raise NoAccountException
340
+ if(response==404):
341
+ raise NoAdminConnException
342
+ # raise HTTPException(
343
+ # status_code=430,
344
+ # detail="Portfolio/Account Is Incorrect",
345
+ # headers={"X-Error": "There goes my error"},
346
+ # )
347
+ # log.info("after invoking create usecase service ")
348
+ log.debug("response : "+ str(response))
349
+ log.info("exit create from anonymize routing method")
350
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
351
+ # tel_Falg = telFlagData["TelemetryFlag"]
352
+ # log.debug("Tel Flag==="+ str(tel_Falg))
353
+ if(tel_Falg == True):
354
+ log.debug("Inside Telemetry Flag")
355
+ requestList = payload.__dict__
356
+ requestObj = {
357
+ "portfolio_name": payload.portfolio if payload.portfolio is not None else "None",
358
+ "account_name": payload.account if payload.account is not None else "None",
359
+ "inputText": requestList["inputText"],
360
+ "exclusion_list": requestList["exclusionList"].split(',') if requestList["exclusionList"] is not None else [],
361
+ }
362
+ responseObj = {
363
+ "type": "None",
364
+ "beginOffset": 0,
365
+ "endOffset": 0,
366
+ "score": 0,
367
+ "responseText": response.anonymizedText
368
+ }
369
+ # lotNumber = 0 # Initialize lotNumber with a default value
370
+ # if payload.lotNumber is not None:
371
+ # lotNumber = payload.lotNumber
372
+ telemetryPayload = {
373
+ "uniqueid": id,
374
+ "tenant": "privacy",
375
+ "apiname": anonymize.__name__,
376
+ "user": payload.user if payload.user is not None else "None",
377
+ "date":now.isoformat(),
378
+ "lotNumber": payload.lotNumber if payload.lotNumber is not None else "None",
379
+ # "exclusionList": payload.exclusionList,
380
+ "request": requestObj,
381
+ "response": [responseObj]
382
+ }
383
+ # TelemetryDb.create(telemetryPayload)
384
+
385
+
386
+ # Trigger the API call asynchronously using a separate thread
387
+
388
+ with concurrent.futures.ThreadPoolExecutor() as executor:
389
+ executor.submit(send_telemetry_request, telemetryPayload)
390
+ log.info("******TELEMETRY REQUEST COMPLETED********")
391
+ return response
392
+ except PrivacyException as cie:
393
+ log.error("Exception for anonymize")
394
+ log.error(cie.__dict__)
395
+ er=[{"UUID":id,"function":"textAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
396
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
397
+ logobj = {"uniqueid":id,"error":er}
398
+ #
399
+ if len(er)!=0:
400
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
401
+ thread.start()
402
+ if request_id_var.get() in error_dict:
403
+ del error_dict[id]
404
+ log.error(cie, exc_info=True)
405
+ log.info("exit create from anonymize routing method")
406
+ raise HTTPException(**cie.__dict__)
407
+ except NoAccountException:
408
+ raise HTTPException(
409
+ status_code=430,
410
+ detail="Portfolio/Account Is Incorrect",
411
+ headers={"X-Error": "There goes my error"},
412
+ )
413
+ except NoAdminConnException:
414
+ raise HTTPException(
415
+ status_code=435,
416
+ detail=" Accounts and Portfolio not available with the Subscription!!",
417
+ headers={"X-Error": "Admin Connection is not established,"},
418
+ )
419
+ except Exception as e:
420
+ log.error(str(e))
421
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
422
+ er=[{"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
423
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
424
+ logobj = {"uniqueid":id,"error":er}
425
+ #
426
+ if len(er)!=0:
427
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
428
+ thread.start()
429
+ if request_id_var.get() in error_dict:
430
+ del error_dict[id]
431
+ raise HTTPException(
432
+ status_code=500,
433
+ detail="Please check with administration!!",
434
+ headers={"X-Error": "Please check with administration!!"})
435
+
436
+ @router.post('/privacy/text/encrpyt',response_model=PIIEncryptResponse)
437
+ def encrypt(payload: PIIAnonymizeRequest,auth= Depends(auth)):
438
+ id = uuid.uuid4().hex
439
+ request_id_var.set(id)
440
+
441
+ log.info("Entered create into encrypt routing method")
442
+ try:
443
+ log.debug("request payload: "+ str(payload))
444
+ startTime = time.time()
445
+ log.debug("Entered into encrypt function")
446
+ response = TextPrivacy.encrypt(payload)
447
+ log.debug("Returned from encrypt function")
448
+ endTime = time.time()
449
+ totalTime = endTime - startTime
450
+ print("response=======",response)
451
+ log.info("Total Time taken "+str(totalTime))
452
+
453
+ if(response==None):
454
+ raise NoAccountException
455
+
456
+ # log.debug("response : "+ str(response))
457
+ log.info("exit create from encrypt routing method")
458
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
459
+ # tel_Falg = telFlagData["TelemetryFlag"]
460
+ # log.debug("Tel Flag==="+ str(tel_Falg))
461
+ if(tel_Falg == True):
462
+ log.debug("Inside Telemetry Flag")
463
+ requestList = payload.__dict__
464
+ requestObj = {
465
+ "portfolio_name": payload.portfolio if payload.portfolio is not None else "None",
466
+ "account_name": payload.account if payload.account is not None else "None",
467
+ "inputText": requestList["inputText"],
468
+ "exclusion_list": requestList["exclusionList"].split(',') if requestList["exclusionList"] is not None else [],
469
+ }
470
+ responseObj = {
471
+ "type": "None",
472
+ "beginOffset": 0,
473
+ "endOffset": 0,
474
+ "score": 0,
475
+ "responseText": response.text
476
+ }
477
+ # lotNumber = 0 # Initialize lotNumber with a default value
478
+ # if payload.lotNumber is not None:
479
+ # lotNumber = payload.lotNumber
480
+ telemetryPayload = {
481
+ "uniqueid": id,
482
+ "tenant": "privacy",
483
+ "apiname": anonymize.__name__,
484
+ "user": payload.user if payload.user is not None else "None",
485
+ "date":now.isoformat(),
486
+ "lotNumber": payload.lotNumber if payload.lotNumber is not None else "None",
487
+ # "exclusionList": payload.exclusionList,
488
+ "request": requestObj,
489
+ "response": [responseObj]
490
+ }
491
+ # TelemetryDb.create(telemetryPayload)
492
+
493
+
494
+ # Trigger the API call asynchronously using a separate thread
495
+
496
+ with concurrent.futures.ThreadPoolExecutor() as executor:
497
+ executor.submit(send_telemetry_request, telemetryPayload)
498
+ log.info("******TELEMETRY REQUEST COMPLETED********")
499
+ return response
500
+
501
+ except PrivacyException as cie:
502
+ log.error("Exception for encrypt")
503
+ log.error(cie.__dict__)
504
+ er=[{"UUID":id,"function":"textEncryptRouter","msg":cie.__dict__,"description":cie.__dict__}]
505
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
506
+ logobj = {"uniqueid":id,"error":er}
507
+ #
508
+ if len(er)!=0:
509
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
510
+ thread.start()
511
+ if request_id_var.get() in error_dict:
512
+ del error_dict[id]
513
+ log.error(cie, exc_info=True)
514
+ log.info("exit create from encrypt routing method")
515
+ raise HTTPException(**cie.__dict__)
516
+ except NoAccountException:
517
+ raise HTTPException(
518
+ status_code=430,
519
+ detail="Portfolio/Account Is Incorrect",
520
+ headers={"X-Error": "There goes my error"},
521
+ )
522
+ except Exception as e:
523
+ log.error(str(e))
524
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
525
+ er=[{"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
526
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
527
+ logobj = {"uniqueid":id,"error":er}
528
+ if len(er)!=0:
529
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
530
+ thread.start()
531
+ if request_id_var.get() in error_dict:
532
+ del error_dict[id]
533
+ raise HTTPException(
534
+ status_code=500,
535
+ detail="Please check with administration!!",
536
+ headers={"X-Error": "Please check with administration!!"})
537
+
538
+ @router.post('/privacy/text/decrpyt',response_model= PIIDecryptResponse)
539
+ def decrypt(payload: PIIDecryptRequest,auth= Depends(auth)):
540
+ id = uuid.uuid4().hex
541
+ request_id_var.set(id)
542
+ log.info("Entered create into decrypt routing method")
543
+ try:
544
+ log.debug("request payload: "+ str(payload))
545
+ startTime = time.time()
546
+ log.debug("Entered into decrypt function")
547
+ response = TextPrivacy.decryption(payload)
548
+ log.debug("Returned from decrypt function")
549
+ endTime = time.time()
550
+ totalTime = endTime - startTime
551
+ log.info("Total Time taken "+str(totalTime))
552
+ return response
553
+ except PrivacyException as cie:
554
+ log.error("Exception for decrypt")
555
+ log.error(cie.__dict__)
556
+ er=[{"UUID":id,"function":"textDecryptRouter","msg":cie.__dict__,"description":cie.__dict__}]
557
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
558
+ logobj = {"uniqueid":id,"error":er}
559
+ #
560
+ if len(er)!=0:
561
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
562
+ thread.start()
563
+ if request_id_var.get() in error_dict:
564
+ del error_dict[id]
565
+ log.error(cie, exc_info=True)
566
+ log.info("exit create from decrypt routing method")
567
+ raise HTTPException(**cie.__dict__)
568
+ except NoAccountException:
569
+ raise HTTPException(
570
+ status_code=430,
571
+ detail="Portfolio/Account Is Incorrect",
572
+ headers={"X-Error": "There goes my error"},
573
+ )
574
+ except Exception as e:
575
+ log.error(str(e))
576
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
577
+ er=[{"UUID":request_id_var.get(),"function":"textAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
578
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
579
+ logobj = {"uniqueid":id,"error":er}
580
+ if len(er)!=0:
581
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
582
+ thread.start()
583
+ if request_id_var.get() in error_dict:
584
+ del error_dict[id]
585
+ raise HTTPException(
586
+ status_code=500,
587
+ detail="Please check with administration!!",
588
+ headers={"X-Error": "Please check with administration!!"})
589
+
590
+ @router.post('/privacy/image/analyze', response_model= PIIImageAnalyzeResponse)
591
+ def image_analyze(ocr: str = Query('Tesseract', enum=['Tesseract',"EasyOcr","ComputerVision"]),magnification:str=Form(...),rotationFlag:str=Form(...),image: UploadFile = File(...),portfolio:Optional[str]=Form(None),account:Optional[str]=Form(None),exclusionList:Optional[str]=Form(None),auth= Depends(auth)):
592
+ id = uuid.uuid4().hex
593
+ request_id_var.set(id)
594
+ log.info("Entered create into image_analyze routing method")
595
+ try:
596
+
597
+ payload={"easyocr":ocr,"mag_ratio":magMap[magnification],"rotationFlag":magMap[rotationFlag],"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
598
+ log.debug("Requested payload" + str(payload))
599
+ startTime = time.time()
600
+ log.debug("Entered into image_analyze function")
601
+ response = ImagePrivacy.image_analyze(payload)
602
+ ApiCall.delAdminList()
603
+ log.debug("Returned from image_analyze function")
604
+ endTime = time.time()
605
+ totalTime = endTime - startTime
606
+ log.info("Total Time taken "+str(totalTime))
607
+ if(response==None):
608
+ raise NoAccountException
609
+ if(response==404):
610
+ raise NoAdminConnException
611
+ # raise HTTPException(
612
+ # status_code=430,
613
+ # detail="Portfolio/Account Is Incorrect",
614
+ # headers={"X-Error": "There goes my error"},
615
+ # )
616
+
617
+ log.info("exit create from image_analyze routing method")
618
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
619
+ # tel_Falg = telFlagData["TelemetryFlag"]
620
+ log.debug("tel_Flag==="+str(tel_Falg))
621
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
622
+ # requestList = payload.__dict__
623
+ if(tel_Falg == True):
624
+ log.debug("Inside Telemetry Flag")
625
+ # telemetryPayload = {
626
+ # "uniqueid": id,
627
+ # "tenant": "privacy",
628
+ # "apiName": image_analyze.__name__,
629
+ # # "portfolio": portfolio,
630
+ # # "accountName": account,
631
+ # # "exclusion_list": exclusionList,
632
+ # "request": requestList,
633
+ # "response": responseList
634
+ # }
635
+ # TelemetryDb.create(telemetryPayload)
636
+
637
+ # Trigger the API call asynchronously using a separate thread
638
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
639
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
640
+ log.info("******TELEMETRY REQUEST COMPLETED********")
641
+ return response
642
+
643
+ except PrivacyException as cie:
644
+ log.error("Exception for image_analyze")
645
+ log.error(cie.__dict__)
646
+ # ExceptionDb.create({"UUID":id,"function":"imageAnalyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
647
+ er=[{"UUID":request_id_var.get(),"function":"imageAnalyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
648
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
649
+ logobj = {"uniqueid":id,"error":er}
650
+
651
+ if len(er)!=0:
652
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
653
+ thread.start()
654
+ if request_id_var.get() in error_dict:
655
+ del error_dict[id]
656
+ log.error(cie, exc_info=True)
657
+ log.info("exit create from image_analyze routing method")
658
+ raise HTTPException(**cie.__dict__)
659
+ except NoAccountException:
660
+ raise HTTPException(
661
+ status_code=430,
662
+ detail="Portfolio/Account Is Incorrect",
663
+ headers={"X-Error": "There goes my error"},
664
+ )
665
+ except NoAdminConnException:
666
+ raise HTTPException(
667
+ status_code=435,
668
+ detail=" Accounts and Portfolio not available with the Subscription!!",
669
+ headers={"X-Error": "Admin Connection is not established,"},
670
+ )
671
+ except Exception as e:
672
+ log.error(str(e))
673
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"imageAnalyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
674
+ er=[{"UUID":request_id_var.get(),"function":"imageAnalyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
675
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
676
+ logobj = {"uniqueid":id,"error":er}
677
+
678
+ if len(er)!=0:
679
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
680
+ thread.start()
681
+ if request_id_var.get() in error_dict:
682
+ del error_dict[id]
683
+ raise HTTPException(
684
+ status_code=500,
685
+ detail="Please check with administration!!",
686
+ headers={"X-Error": "Please check with administration!!"})
687
+
688
+ @router.post('/privacy/image/anonymize')
689
+ def image_anonymize(ocr: str = Query('Tesseract', enum=['Tesseract',"EasyOcr","ComputerVision"]),magnification:str=Form(...),rotationFlag:str=Form(...),image: UploadFile = File(...),portfolio:Optional[str]=Form(None),account:Optional[str]=Form(None),exclusionList:Optional[str]=Form(None),auth= Depends(auth)):
690
+ id = uuid.uuid4().hex
691
+ request_id_var.set(id)
692
+ log.info("Entered create into image_anonymize routing method" )
693
+ try:
694
+
695
+ payload={"easyocr":ocr,"mag_ratio":magMap[magnification],"rotationFlag":magMap[rotationFlag],"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
696
+ log.debug("Payload:"+str(payload))
697
+ startTime = time.time()
698
+ log.debug("Entered into image_anonymize function")
699
+ response = ImagePrivacy.image_anonymize(payload)
700
+ ApiCall.delAdminList()
701
+ log.debug("Returned from image_anonymize function")
702
+ endTime = time.time()
703
+ totalTime = endTime - startTime
704
+ log.info("Total Time taken "+str(totalTime))
705
+ if(response==None):
706
+ raise NoAccountException
707
+ if(response==404):
708
+ raise NoAdminConnException
709
+ # raise HTTPException(
710
+ # status_code=430,
711
+ # detail="Portfolio/Account Is Incorrect",
712
+ # headers={"X-Error": "There goes my error"},
713
+ # )
714
+
715
+
716
+ log.info("exit create from image_anonymize routing method")
717
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
718
+ # tel_Falg = telFlagData["TelemetryFlag"]
719
+ log.debug("tel_Flag==="+str(tel_Falg))
720
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
721
+ # requestList = payload.__dict__
722
+ if(tel_Falg == True):
723
+ log.debug("Inside Telemetry Flag")
724
+ # telemetryPayload = {
725
+ # "uniqueid": id,
726
+ # "tenant": "privacy",
727
+ # "apiName": image_anonymize.__name__,
728
+ # # "portfolio": portfolio,
729
+ # # "accountName": account,
730
+ # # "exclusion_list": exclusionList,
731
+ # "request": requestList,
732
+ # "response": responseList
733
+ # }
734
+ # TelemetryDb.create(telemetryPayload)
735
+
736
+ # Trigger the API call asynchronously using a separate thread
737
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
738
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
739
+ log.info("******TELEMETRY REQUEST COMPLETED********")
740
+ return response
741
+
742
+ except PrivacyException as cie:
743
+ log.error("Exception for image_anonymize")
744
+ log.error(cie.__dict__)
745
+ # ExceptionDb.create({"UUID":id,"function":"imageAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
746
+ er=[{"UUID":request_id_var.get(),"function":"imageAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
747
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
748
+ logobj = {"uniqueid":id,"error":er}
749
+
750
+ if len(er)!=0:
751
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
752
+ thread.start()
753
+ if request_id_var.get() in error_dict:
754
+ del error_dict[id]
755
+ log.error(cie, exc_info=True)
756
+ log.info("exit create usecase routing method")
757
+ raise HTTPException(**cie.__dict__)
758
+ except NoAccountException:
759
+ raise HTTPException(
760
+ status_code=430,
761
+ detail="Portfolio/Account Is Incorrect",
762
+ headers={"X-Error": "There goes my error"},
763
+ )
764
+ except NoAdminConnException:
765
+ raise HTTPException(
766
+ status_code=435,
767
+ detail=" Accounts and Portfolio not available with the Subscription!!",
768
+ headers={"X-Error": "Admin Connection is not established,"},
769
+ )
770
+ except Exception as e:
771
+ log.error(str(e))
772
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"imageAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
773
+ er=[{"UUID":request_id_var.get(),"function":"imageAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
774
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
775
+ logobj = {"uniqueid":id,"error":er}
776
+
777
+ if len(er)!=0:
778
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
779
+ thread.start()
780
+ if request_id_var.get() in error_dict:
781
+ del error_dict[id]
782
+ raise HTTPException(
783
+ status_code=500,
784
+ detail="Please check with administration!!",
785
+ headers={"X-Error": "Please check with administration!!"})
786
+
787
+ @router.post('/privacy/image/masking')
788
+ async def image_mask(media: UploadFile = File(...), template: UploadFile = File(...),auth= Depends(auth)):
789
+ try:
790
+ # log.info("before invoking create usecase service ")
791
+ main_image_content = await media.read()
792
+ nparr = np.fromstring(main_image_content, np.uint8)
793
+ main_image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
794
+
795
+ template_image_content = await template.read()
796
+ nparr = np.fromstring(template_image_content, np.uint8)
797
+ template_image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
798
+ if template_image.shape[0] > main_image.shape[0] or template_image.shape[1] > main_image.shape[1]:
799
+ raise HTTPException(status_code=400, detail ="Mask image must be smaller or equal in size to the main image")
800
+ response = await ImagePrivacy.image_masking(main_image,template_image)
801
+ # log.info("after invoking image masking service")
802
+ is_success, buffer = cv2.imencode(".png", response)
803
+
804
+ # Create a StreamingResponse from the image buffer
805
+ return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/png")
806
+ except PrivacyException as cie:
807
+ log.error(cie.__dict__)
808
+ log.info("exit create usecase routing method")
809
+ raise HTTPException(**cie.__dict__)
810
+ # @router.post('/privacy/pii/image/anonymize/zip') #########@#@@#@#$@
811
+ # def image_anonymize(payload: UploadFile):
812
+ # try:
813
+ # log.info("Entered create usecase routing method" )
814
+ # response = service.zipimage_anonymize(payload)
815
+ # if(response==None):
816
+ # raise HTTPException(
817
+ # status_code=430,
818
+ # detail="Portfolio/Account Is Incorrect",
819
+ # headers={"X-Error": "There goes my error"},
820
+ # )
821
+ # log.info("after invoking create usecase service ")
822
+
823
+ # log.info("exit create usecase routing method")
824
+ # return response
825
+
826
+ # except PrivacyException as cie:
827
+ # log.error(cie.__dict__)
828
+ # log.info("exit create usecase routing method")
829
+ # raise HTTPException(**cie.__dict__)
830
+
831
+
832
+ # @router.post('/privacy/pii/image/anonymize/multiple')
833
+ # def image_anonymize(payload: List[UploadFile] = File(...)):
834
+ # try:
835
+ # log.info("Entered create usecase routing method" )
836
+ # response=[]
837
+ # for image in payload:
838
+ # response.append(service.image_anonymize(image))
839
+
840
+ # log.info("after invoking create usecase service ")
841
+
842
+ # log.info("exit create usecase routing method")
843
+ # return response
844
+
845
+ # except PrivacyException as cie:
846
+ # log.error(cie.__dict__)
847
+ # log.info("exit create usecase routing method")
848
+ # raise HTTPException(**cie.__dict__)
849
+
850
+ # @router.post('/privacy/pii/image/analyze/multiple')#,response_model=PIIMultipleImageAnalyzeResponse)
851
+ # def image_analyze(payload: List[UploadFile] = File(...)):
852
+ # try:
853
+ # log.info("Entered create usecase routing method" )
854
+ # response=[]
855
+ # for image in payload:
856
+ # response.append(service.temp(image))
857
+
858
+ # log.info("after invoking create usecase service ")
859
+
860
+ # log.info("exit create usecase routing method")
861
+ # return response
862
+
863
+ # except PrivacyException as cie:
864
+ # log.error(cie.__dict__)
865
+ # log.info("exit create usecase routing method")
866
+ # raise HTTPException(**cie.__dict__)
867
+
868
+
869
+ @router.post('/privacy/image/verify')
870
+ def image_verify(image: UploadFile = File(...),portfolio:Optional[str]=Form(None),account:Optional[str]=Form(None),exclusionList:Optional[str]=Form(None),auth= Depends(auth)):
871
+ id = uuid.uuid4().hex
872
+ request_id_var.set(id)
873
+ log.info("Entered create into image_verify routing method" )
874
+ try:
875
+ payload={"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
876
+ log.debug("request payload: "+str(payload))
877
+ startTime = time.time()
878
+ log.debug("Entered into image_verify function")
879
+ response = ImagePrivacy.image_verify(payload)
880
+ ApiCall.delAdminList()
881
+ log.debug("Returned from image_verify function")
882
+ endTime = time.time()
883
+ totalTime = endTime - startTime
884
+ log.info("Total Time taken "+str(totalTime))
885
+ if(response==None):
886
+ raise NoAccountException
887
+ if(response==404):
888
+ raise NoAdminConnException
889
+ # raise HTTPException(
890
+ # status_code=430,
891
+ # detail="Portfolio/Account Is Incorrect",
892
+ # headers={"X-Error": "There goes my error"},
893
+ # )
894
+
895
+
896
+ log.info("exit create from image_verify routing method")
897
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
898
+ # tel_Falg = telFlagData["TelemetryFlag"]
899
+ log.debug("tel_Flag==="+ str(tel_Falg))
900
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
901
+ if(tel_Falg == True):
902
+ log.debug("Inside Telemetry Flag")
903
+ # telemetryPayload = {
904
+ # "uniqueid": id,
905
+ # "tenant": "privacy",
906
+ # "apiName": image_verify.__name__,
907
+ # # "portfolio": portfolio,
908
+ # # "accountName": account,
909
+ # # "exclusion_list": exclusionList,
910
+ # "request": payload,
911
+ # "response": response
912
+ # }
913
+ # TelemetryDb.create(telemetryPayload)
914
+
915
+ # Trigger the API call asynchronously using a separate thread
916
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
917
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
918
+ log.info("******TELEMETRY REQUEST COMPLETED********")
919
+ return response
920
+
921
+ except PrivacyException as cie:
922
+ log.error("Exception for image_verify")
923
+ log.error(cie.__dict__)
924
+ # ExceptionDb.create({"UUID":id,"function":"imageVerifyRouter","msg":cie.__dict__,"description":cie.__dict__})
925
+ er=[{"UUID":request_id_var.get(),"function":"imageVerifyRouter","msg":cie.__dict__,"description":cie.__dict__}]
926
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
927
+ logobj = {"uniqueid":id,"error":er}
928
+
929
+ if len(er)!=0:
930
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
931
+ thread.start()
932
+ if request_id_var.get() in error_dict:
933
+ del error_dict[id]
934
+ log.error(cie, exc_info=True)
935
+ log.info("exit create from image_verify routing method")
936
+ raise HTTPException(**cie.__dict__)
937
+ except NoAccountException:
938
+ raise HTTPException(
939
+ status_code=430,
940
+ detail="Portfolio/Account Is Incorrect",
941
+ headers={"X-Error": "There goes my error"},
942
+ )
943
+ except NoAdminConnException:
944
+ raise HTTPException(
945
+ status_code=435,
946
+ detail=" Accounts and Portfolio not available with the Subscription!!",
947
+ headers={"X-Error": "Admin Connection is not established,"},
948
+ )
949
+ except Exception as e:
950
+ log.error(str(e))
951
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"imageVerifyRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
952
+ er=[{"UUID":request_id_var.get(),"function":"imageVerifyRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
953
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
954
+ logobj = {"uniqueid":id,"error":er}
955
+
956
+ if len(er)!=0:
957
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
958
+ thread.start()
959
+ if request_id_var.get() in error_dict:
960
+ del error_dict[id]
961
+ raise HTTPException(
962
+ status_code=500,
963
+ detail="Please check with administration!!",
964
+ headers={"X-Error": "Please check with administration!!"})
965
+
966
+
967
+ @router.post('/privacy/image/hashify')
968
+ def image_hashify(ocr: str = Query('Tesseract', enum=['Tesseract',"EasyOcr","ComputerVision"]),magnification:str=Form(...),rotationFlag:str=Form(...),image: UploadFile = File(...),portfolio:Optional[str]=Form(None),account:Optional[str]=Form(None),exclusionList:Optional[str]=Form(None),auth= Depends(auth)):
969
+ id = uuid.uuid4().hex
970
+ request_id_var.set(id)
971
+ log.info("Entered create into imageEncryption routing method" )
972
+ try:
973
+ payload={"easyocr":ocr,"mag_ratio":magMap[magnification],"rotationFlag":magMap[rotationFlag],"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
974
+ log.debug("request payload: "+str(payload))
975
+ startTime = time.time()
976
+ log.debug("Entered into imageEncryption function")
977
+ response = ImagePrivacy.imageEncryption(payload)
978
+ ApiCall.delAdminList()
979
+ log.debug("Returned from imageEncryption function")
980
+ endTime = time.time()
981
+ totalTime = endTime - startTime
982
+ log.info("Total Time taken "+str(totalTime))
983
+ if(response==None):
984
+ raise NoAccountException
985
+ if(response==404):
986
+ raise NoAdminConnException
987
+ # raise HTTPException(
988
+ # status_code=430,
989
+ # detail="Portfolio/Account Is Incorrect",
990
+ # headers={"X-Error": "There goes my error"},
991
+ # )
992
+ log.info("exit create from into imageEncryption routing method")
993
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
994
+ # tel_Falg = telFlagData["TelemetryFlag"]
995
+ log.debug("tel_Flag==="+str(tel_Falg))
996
+ # requestList = payload.__dict__
997
+ if(tel_Falg == True):
998
+ log.debug("Inside Telemetry Flag")
999
+ # telemetryPayload = {
1000
+ # "uniqueid": id,
1001
+ # "tenant": "privacy",
1002
+ # "apiName": image_verify.__name__,
1003
+ # # "portfolio": portfolio,
1004
+ # # "accountName": account,
1005
+ # # "exclusion_list": exclusionList,
1006
+ # "request": requestList,
1007
+ # "response": response
1008
+ # }
1009
+ # TelemetryDb.create(telemetryPayload)
1010
+
1011
+ # Trigger the API call asynchronously using a separate thread
1012
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1013
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1014
+ log.info("******TELEMETRY REQUEST COMPLETED********")
1015
+ return response
1016
+
1017
+ except PrivacyException as cie:
1018
+ log.error("Exception for imageEncryption")
1019
+ log.error(cie.__dict__)
1020
+ # ExceptionDb.create({"UUID":id,"function":"imageHashifyRouter","msg":cie.__dict__,"description":cie.__dict__})
1021
+ er=[{"UUID":request_id_var.get(),"function":"imageHashifyRouter","msg":cie.__dict__,"description":cie.__dict__}]
1022
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1023
+ logobj = {"uniqueid":id,"error":er}
1024
+
1025
+ if len(er)!=0:
1026
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1027
+ thread.start()
1028
+ if request_id_var.get() in error_dict:
1029
+ del error_dict[id]
1030
+ log.error(cie, exc_info=True)
1031
+ log.info("exit create usecase routing method")
1032
+ raise HTTPException(**cie.__dict__)
1033
+ except NoAccountException:
1034
+ raise HTTPException(
1035
+ status_code=430,
1036
+ detail="Portfolio/Account Is Incorrect",
1037
+ headers={"X-Error": "There goes my error"},
1038
+ )
1039
+ except NoAdminConnException:
1040
+ raise HTTPException(
1041
+ status_code=435,
1042
+ detail=" Accounts and Portfolio not available with the Subscription!!",
1043
+ headers={"X-Error": "Admin Connection is not established,"},
1044
+ )
1045
+ except Exception as e:
1046
+ log.error(str(e))
1047
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"imageHashifyRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1048
+ er=[{"UUID":request_id_var.get(),"function":"imageHashifyRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1049
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1050
+ logobj = {"uniqueid":id,"error":er}
1051
+
1052
+ if len(er)!=0:
1053
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1054
+ thread.start()
1055
+ if request_id_var.get() in error_dict:
1056
+ del error_dict[id]
1057
+ raise HTTPException(
1058
+ status_code=500,
1059
+ detail="Please check with administration!!",
1060
+ headers={"X-Error": "Please check with administration!!"})
1061
+
1062
+
1063
+
1064
+ @router.post('/privacy/privacyShield', response_model= PIIPrivacyShieldResponse)
1065
+ def privacy_shield(payload: PIIPrivacyShieldRequest,auth= Depends(auth)):
1066
+ id = uuid.uuid4().hex
1067
+ request_id_var.set(id)
1068
+ log.info("Entered create into privacyShield routing method")
1069
+ try:
1070
+ # log.info("Entered create usecase routing method" )
1071
+ log.debug("request payload: "+ str(payload))
1072
+ startTime = time.time()
1073
+ log.debug("Entered into privacyShield function")
1074
+ response = Shield.privacyShield(payload)
1075
+ ApiCall.delAdminList()
1076
+ log.debug("Returned from privacyShield function")
1077
+ endTime = time.time()
1078
+ totalTime = endTime - startTime
1079
+ log.info("Total Time taken "+str(totalTime))
1080
+ if(response==None):
1081
+ raise NoAccountException
1082
+ if(response==404):
1083
+ raise NoAdminConnException
1084
+ # raise HTTPException(
1085
+ # status_code=430,
1086
+ # detail="Portfolio/Account Is Incorrect",
1087
+ # headers={"X-Error": "There goes my error"},
1088
+ # )
1089
+ # log.info("after invoking create usecase service ")
1090
+ log.debug("response : "+ str(response))
1091
+ log.info("exit create from privacyShield routing method")
1092
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1093
+ # tel_Falg = telFlagData["TelemetryFlag"]
1094
+ log.debug("tel_Flag==="+str(tel_Falg))
1095
+ # responseList = response.privacyCheck
1096
+ # requestList = payload.__dict__
1097
+ if(tel_Falg == True):
1098
+ log.debug("Inside Telemetry Flag")
1099
+ # telemetryPayload = {
1100
+ # "uniqueid": id,
1101
+ # "tenant": "privacy",
1102
+ # "apiName": "privacyshield",
1103
+ # # "portfolio": payload.portfolio,
1104
+ # # "accountName": payload.account,
1105
+ # # "exclusion_list": "None",
1106
+ # "request": requestList,
1107
+ # "response": responseList
1108
+ # }
1109
+ # TelemetryDb.create(telemetryPayload)
1110
+
1111
+ # Trigger the API call asynchronously using a separate thread
1112
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1113
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1114
+ log.info("******TELEMETRY REQUEST COMPLETED********")
1115
+ return response
1116
+ except PrivacyException as cie:
1117
+ log.error("Exception for privacyShield")
1118
+ log.error(cie.__dict__)
1119
+ # ExceptionDb.create({"UUID":id,"function":"privacyShield","msg":cie.__dict__,"description":cie.__dict__})
1120
+ er=[{"UUID":request_id_var.get(),"function":"privacyShield","msg":cie.__dict__,"description":cie.__dict__}]
1121
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1122
+ logobj = {"uniqueid":id,"error":er}
1123
+
1124
+ if len(er)!=0:
1125
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1126
+ thread.start()
1127
+ if request_id_var.get() in error_dict:
1128
+ del error_dict[id]
1129
+ log.error(cie, exc_info=True)
1130
+ log.info("exit create from privacyShield routing method")
1131
+ raise HTTPException(**cie.__dict__)
1132
+ except NoAccountException:
1133
+ raise HTTPException(
1134
+ status_code=430,
1135
+ detail="Portfolio/Account Is Incorrect",
1136
+ headers={"X-Error": "There goes my error"},
1137
+ )
1138
+ except NoAdminConnException:
1139
+ raise HTTPException(
1140
+ status_code=435,
1141
+ detail=" Accounts and Portfolio not available with the Subscription!!",
1142
+ headers={"X-Error": "Admin Connection is not established,"},
1143
+ )
1144
+ except Exception as e:
1145
+ log.error(str(e))
1146
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"privacyShield","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1147
+ er=[{"UUID":request_id_var.get(),"function":"privacyShield","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1148
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1149
+ logobj = {"uniqueid":id,"error":er}
1150
+
1151
+ if len(er)!=0:
1152
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1153
+ thread.start()
1154
+ if request_id_var.get() in error_dict:
1155
+ del error_dict[id]
1156
+ raise HTTPException(
1157
+ status_code=500,
1158
+ detail="Please check with administration!!",
1159
+ headers={"X-Error": "Please check with administration!!"})
1160
+
1161
+ # from privacy.service.dicom_service import DICOM
1162
+ # @router.get('/privacy/pii/dicom/anonymize')
1163
+ # def image_anonymize():
1164
+ # try:
1165
+ # log.info("Entered create usecase routing method" )
1166
+ # # payload={"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
1167
+ # # log.info(str(payload))
1168
+ # # response = service.image_anonymize(payload)
1169
+ # response=DICOM.dicomReader()
1170
+ # # print(response)
1171
+
1172
+ # # if(response==None):
1173
+ # # raise HTTPException(
1174
+ # # status_code=430,
1175
+ # # detail="Portfolio/Account Is Incorrect",
1176
+ # # headers={"X-Error": "There goes my error"},
1177
+ # # )
1178
+ # log.info("after invoking create usecase service ")
1179
+
1180
+ # log.info("exit create usecase routing method")
1181
+ # return response
1182
+
1183
+ # except PrivacyException as cie:
1184
+ # log.error(cie.__dict__)
1185
+ # log.info("exit create usecase routing method")
1186
+ # raise HTTPException(**cie.__dict__)
1187
+
1188
+
1189
+ @router.post('/privacy/dicom/anonymize')
1190
+ def dicom_anonymize(payload: UploadFile = File(...),auth= Depends(auth)):
1191
+ id = uuid.uuid4().hex
1192
+ request_id_var.set(id)
1193
+ log.info("Entered create into readDicom routing method" )
1194
+ try:
1195
+ # payload={"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
1196
+ startTime = time.time()
1197
+ log.debug("Entered into readDicom function")
1198
+ response =DICOMPrivacy.readDicom(payload)
1199
+ log.debug("Returned from readDicom function")
1200
+ endTime = time.time()
1201
+ totalTime = endTime - startTime
1202
+ log.info("Total Time taken "+str(totalTime))
1203
+ if(response==None):
1204
+ raise NoAccountException
1205
+ if(response==404):
1206
+ raise NoAdminConnException
1207
+ # raise HTTPException(
1208
+ # status_code=430,
1209
+ # detail="Portfolio/Account Is Incorrect",
1210
+ # headers={"X-Error": "There goes my error"},
1211
+ # )
1212
+
1213
+
1214
+ log.info("exit create from readDicom routing method")
1215
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1216
+ # tel_Falg = telFlagData["TelemetryFlag"]
1217
+ log.debug("tel_Flag==="+str(tel_Falg))
1218
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
1219
+ # requestList = payload.__dict__
1220
+ if(tel_Falg == True):
1221
+ log.debug("Inside Telemetry Flag")
1222
+ # telemetryPayload = {
1223
+ # "uniqueid": id,
1224
+ # "tenant": "privacy",
1225
+ # "apiName": "DICOMIMAGE",
1226
+ # # "portfolio": "None",
1227
+ # # "accountName": "None",
1228
+ # # "exclusion_list": "None",
1229
+ # "request": requestList,
1230
+ # "response": responseList
1231
+ # }
1232
+ # TelemetryDb.create(telemetryPayload)
1233
+
1234
+ # Trigger the API call asynchronously using a separate thread
1235
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1236
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1237
+ log.info("******TELEMETRY REQUEST COMPLETED********")
1238
+ return response
1239
+
1240
+ except PrivacyException as cie:
1241
+ log.error("Exception for readDicom")
1242
+ log.error(cie.__dict__)
1243
+ # ExceptionDb.create({"UUID":id,"function":"DICOMAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
1244
+ er=[{"UUID":request_id_var.get(),"function":"DICOMAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
1245
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1246
+ logobj = {"uniqueid":id,"error":er}
1247
+
1248
+ if len(er)!=0:
1249
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1250
+ thread.start()
1251
+ if request_id_var.get() in error_dict:
1252
+ del error_dict[id]
1253
+ log.error(cie, exc_info=True)
1254
+ log.info("exit create from readDicom routing method")
1255
+ raise HTTPException(**cie.__dict__)
1256
+ except NoAccountException:
1257
+ raise HTTPException(
1258
+ status_code=430,
1259
+ detail="Portfolio/Account Is Incorrect",
1260
+ headers={"X-Error": "There goes my error"},
1261
+ )
1262
+ except NoAdminConnException:
1263
+ raise HTTPException(
1264
+ status_code=435,
1265
+ detail=" Accounts and Portfolio not available with the Subscription!!",
1266
+ headers={"X-Error": "Admin Connection is not established,"},
1267
+ )
1268
+ except Exception as e:
1269
+ log.error(str(e))
1270
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"DICOMAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1271
+ er=[{"UUID":request_id_var.get(),"function":"DICOMAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1272
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1273
+ logobj = {"uniqueid":id,"error":er}
1274
+
1275
+ if len(er)!=0:
1276
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1277
+ thread.start()
1278
+ if request_id_var.get() in error_dict:
1279
+ del error_dict[id]
1280
+ raise HTTPException(
1281
+ status_code=500,
1282
+ detail="Please check with administration!!",
1283
+ headers={"X-Error": "Please check with administration!!"})
1284
+
1285
+ @fileRouter.post('/privacy-files/excel/anonymize')
1286
+ def logo_anonymize(excel: UploadFile = File(...),auth= Depends(auth)):
1287
+ id = uuid.uuid4().hex
1288
+ request_id_var.set(id)
1289
+ log.info("Entered create into excelanonymize routing method" )
1290
+ try:
1291
+ payload={"excel":excel}
1292
+ print("payload==",payload)
1293
+ # print("type==",excel.file.content_type)
1294
+ startTime = time.time()
1295
+ log.debug("Entered into excelanonymize function")
1296
+ response = Excel.excelanonymize(payload)
1297
+ log.debug("Returned from excelanonymize function")
1298
+ endTime = time.time()
1299
+ totalTime = endTime - startTime
1300
+ log.info("Total Time taken "+str(totalTime))
1301
+ if(response==None):
1302
+ raise NoAccountException
1303
+ if(response==404):
1304
+ raise NoAdminConnException
1305
+
1306
+ # raise HTTPException(
1307
+ # status_code=430,
1308
+ # detail="Portfolio/Account Is Incorrect",
1309
+ # headers={"X-Error": "There goes my error"},
1310
+ # )
1311
+
1312
+ log.info("exit create from excelanonymize routing method")
1313
+ log.debug("response===="+str(response))
1314
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1315
+ # tel_Falg = telFlagData["TelemetryFlag"]
1316
+ log.debug("tel_Flag==="+str(tel_Falg))
1317
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
1318
+ # requestList = payload.__dict__
1319
+ if(tel_Falg == True):
1320
+ log.debug("Inside Telemetry Flag")
1321
+ # telemetryPayload = {
1322
+ # "uniqueid": id,
1323
+ # "tenant": "privacy",
1324
+ # "apiName": "Excel_Anonymize",
1325
+ # # "portfolio": "None",
1326
+ # # "accountName": "None",
1327
+ # # "exclusion_list": "None",
1328
+ # "request": requestList,
1329
+ # "response": responseList
1330
+ # }
1331
+ # TelemetryDb.create(telemetryPayload)
1332
+
1333
+ # Trigger the API call asynchronously using a separate thread
1334
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1335
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1336
+ log.info("******TELEMETRY REQUEST COMPLETED********")
1337
+ return FileResponse(response,media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
1338
+ # return response
1339
+
1340
+ except PrivacyException as cie:
1341
+ log.error("Exception for excelanonymize")
1342
+ log.error(cie.__dict__)
1343
+ # ExceptionDb.create({"UUID":id,"function":"excelAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
1344
+ er=[{"UUID":request_id_var.get(),"function":"excelAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
1345
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1346
+ logobj = {"uniqueid":id,"error":er}
1347
+
1348
+ if len(er)!=0:
1349
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1350
+ thread.start()
1351
+ if request_id_var.get() in error_dict:
1352
+ del error_dict[id]
1353
+ log.error(cie, exc_info=True)
1354
+ log.info("exit create usecase routing method")
1355
+ raise HTTPException(**cie.__dict__)
1356
+ except NoAccountException:
1357
+ raise HTTPException(
1358
+ status_code=430,
1359
+ detail="Portfolio/Account Is Incorrect",
1360
+ headers={"X-Error": "There goes my error"},
1361
+ )
1362
+ except NoAdminConnException:
1363
+ raise HTTPException(
1364
+ status_code=435,
1365
+ detail=" Accounts and Portfolio not available with the Subscription!!",
1366
+ headers={"X-Error": "Admin Connection is not established,"},
1367
+ )
1368
+ except Exception as e:
1369
+ log.error(str(e))
1370
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"excelAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1371
+ er=[{"UUID":request_id_var.get(),"function":"excelAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1372
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1373
+ logobj = {"uniqueid":id,"error":er}
1374
+
1375
+ if len(er)!=0:
1376
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1377
+ thread.start()
1378
+ if request_id_var.get() in error_dict:
1379
+ del error_dict[id]
1380
+ raise HTTPException(
1381
+ status_code=500,
1382
+ detail="Please check with administration!!",
1383
+ headers={"X-Error": "Please check with administration!!"})
1384
+
1385
+ ## PAYLOAD CHANGED TO ACCEPT TEXT IN A STRUCTURED FORMAT AND GET RESPONSE FOR THE SAME
1386
+ from starlette.responses import PlainTextResponse
1387
+ @router.post('/privacy/code/anonymize',response_class=PlainTextResponse)
1388
+ async def code_redaction(payload_text: str = Body(..., media_type="text/plain", description="The code to be anonymized"),auth= Depends(auth)):
1389
+ id = uuid.uuid4().hex
1390
+ request_id_var.set(id)
1391
+ log.info("Entered create into textner routing method")
1392
+ try:
1393
+ log.debug("payload==" + str(payload_text))
1394
+
1395
+ startTime = time.time()
1396
+ log.debug("Entered into textner function")
1397
+ response = codeNer.codeText(payload_text,model, tokenizer)
1398
+ log.debug("Returned from textner function")
1399
+
1400
+ endTime = time.time()
1401
+ totalTime = endTime - startTime
1402
+ log.info("Total Time taken " + str(totalTime))
1403
+ log.debug("response" + str(response))
1404
+
1405
+ if response is None:
1406
+ raise NoAccountException
1407
+
1408
+ log.info("exit create from textner routing method")
1409
+ # Return the response as plain text, maintaining the format
1410
+ return PlainTextResponse(content=response)
1411
+ except PrivacyException as cie:
1412
+ log.error("Exception for code anonymize")
1413
+ raise cie
1414
+
1415
+ from io import BytesIO
1416
+
1417
+ @router.post('/privacy/codefile/anonymize')
1418
+ async def code_anonymize(code_file: UploadFile = File(...)):
1419
+ id = uuid.uuid4().hex
1420
+ request_id_var.set(id)
1421
+ log.info("Entered create into filener routing method" )
1422
+ try:
1423
+ # Read the file content from the UploadFile object
1424
+ code_content = await code_file.read()
1425
+ print("code_content==",code_content)
1426
+ # Perform code redaction
1427
+ startTime = time.time()
1428
+ log.debug("Entered into filener function")
1429
+ redacted_content, output_code_file = codeNer.codeFile(code_content, code_file.filename,model, tokenizer)
1430
+ log.debug("Returned from filener function")
1431
+ if isinstance(redacted_content, str):
1432
+ redacted_content = redacted_content.encode('utf-8')
1433
+ print(redacted_content,"REDACTED CONTENT")
1434
+ endTime = time.time()
1435
+ totalTime = endTime - startTime
1436
+ log.info("Total Time taken "+str(totalTime))
1437
+ headers = {
1438
+ "Content-Disposition": f"attachment; filename={output_code_file}",
1439
+ "Access-Control-Expose-Headers": "Content-Disposition"
1440
+ }
1441
+
1442
+ # Delete the uploaded file
1443
+ await code_file.close()
1444
+ # filepath = os.path.join('', code_file.filename)
1445
+ output_code_file = os.path.splitext(code_file.filename)[0] + "_redacted" + os.path.splitext(code_file.filename)[1]
1446
+ os.remove(output_code_file)
1447
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1448
+ # tel_Falg = telFlagData["TelemetryFlag"]
1449
+ # responseList = list(map(lambda obj: obj.__dict__, response.PIIEntities))
1450
+ # requestList = payload.__dict__
1451
+ if(tel_Falg == True):
1452
+ log.debug("Inside Telemetry Flag")
1453
+ # telemetryPayload = {
1454
+ # "uniqueid": id,
1455
+ # "tenant": "privacy",
1456
+ # "apiName": code_anonymize.__name__,
1457
+ # # "portfolio": "None",
1458
+ # # "accountName": "None",
1459
+ # # "exclusion_list": "None",
1460
+ # "request": requestList,
1461
+ # "response": responseList
1462
+ # }
1463
+ # TelemetryDb.create(telemetryPayload)
1464
+
1465
+ # Trigger the API call asynchronously using a separate thread
1466
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1467
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1468
+ log.info("******TELEMETRY REQUEST COMPLETED********")
1469
+
1470
+ # Return the redacted code content as a response with the correct filename
1471
+ return StreamingResponse(BytesIO(redacted_content), media_type="application/octet-stream", headers=headers)
1472
+ except PrivacyException as cie:
1473
+ log.error("Exception for filener")
1474
+ log.error(cie, exc_info=True)
1475
+ # ExceptionDb.create({"UUID":id,"function":"codeFileAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
1476
+ er=[{"UUID":request_id_var.get(),"function":"codeFileAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
1477
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1478
+ logobj = {"uniqueid":id,"error":er}
1479
+
1480
+ if len(er)!=0:
1481
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1482
+ thread.start()
1483
+ if request_id_var.get() in error_dict:
1484
+ del error_dict[id]
1485
+ raise cie
1486
+ except Exception as e:
1487
+ log.error(str(e))
1488
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"codeFileAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1489
+ er=[{"UUID":request_id_var.get(),"function":"codeFileAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1490
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1491
+ logobj = {"uniqueid":id,"error":er}
1492
+
1493
+ if len(er)!=0:
1494
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1495
+ thread.start()
1496
+ if request_id_var.get() in error_dict:
1497
+ del error_dict[id]
1498
+ raise HTTPException(
1499
+ status_code=500,
1500
+ detail="Please check with administration!!",
1501
+ headers={"X-Error": "Please check with administration!!"})
1502
+
1503
+
1504
+
1505
+
1506
+ # # from privacy.service.test import Test
1507
+ # @router.get('/privacy/pii/video/anonymizea')
1508
+ # async def image_analyze():
1509
+ # try:
1510
+ # log.info("Entered create usecase routing method" )
1511
+ # # payload={"image":image,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
1512
+ # # response =VideoAnalyzer.anonymize(payload)
1513
+ # # print(response)
1514
+ # # if(response==None):
1515
+ # # raise HTTPException(
1516
+ # # status_code=430,
1517
+ # # detail="Portfolio/Account Is Incorrect",
1518
+ # # headers={"X-Error": "There goes my error"},
1519
+ # # )
1520
+ # # log.info("after invoking create usecase service ")
1521
+ # # x=[]
1522
+ # x=Test.work()
1523
+ # # for i in x:
1524
+ # # print(i)
1525
+ # # log.info("exit create usecase routing method")
1526
+ # return StreamingResponse(x,media_type="plain/text")
1527
+
1528
+
1529
+ # except PrivacyException as cie:
1530
+ # log.error(cie.__dict__)
1531
+ # log.info("exit create usecase routing method")
1532
+ # raise HTTPException(**cie.__dict__)
1533
+ # app=FastAPI()
1534
+ # cc=set()
1535
+ # @app.websocket("/ws")
1536
+ # async def check(websocket:WebSocket):
1537
+ # await websocket.accept()
1538
+ # cc.add(websocket)
1539
+ # try:
1540
+ # while True:
1541
+ # m="asdasdasdasdasd"
1542
+ # await websocket.send_text(m)
1543
+ # await asyncio.sleep(1)
1544
+ # except:
1545
+ # cc.remove(websocket)
1546
+
1547
+
1548
+
1549
+ from privacy.service.diffrentialPrivacy import DiffPrivacy
1550
+ @router.post('/privacy/DifferentialPrivacy/file')
1551
+ def diff_privacy_file(dataset: UploadFile = File(...),auth= Depends(auth)):
1552
+ id = uuid.uuid4().hex
1553
+ request_id_var.set(id)
1554
+ log.info("Entered create into uploadFIle routing method" )
1555
+ try:
1556
+ # payload={"excel":excel}
1557
+ # print("payload==",payload)
1558
+ # print("type==",excel.file.content_type)
1559
+ startTime = time.time()
1560
+ log.debug("Entered into uploadFIle function")
1561
+ response = DiffPrivacy.uploadFIle(dataset)
1562
+ log.debug("Returned from uploadFIle function")
1563
+ endTime = time.time()
1564
+ totalTime = endTime - startTime
1565
+ log.info("Total Time taken "+str(totalTime))
1566
+ if(response==None):
1567
+ raise NoAccountException
1568
+ # raise HTTPException(
1569
+ # status_code=430,
1570
+ # detail="Portfolio/Account Is Incorrect",
1571
+ # headers={"X-Error": "There goes my error"},
1572
+ # )
1573
+ # log.info("after invoking create usecase service ")
1574
+
1575
+ log.info("exit create from uploadFIle routing method")
1576
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1577
+ # tel_Falg = telFlagData["TelemetryFlag"]
1578
+ # print("tel_Flag===",tel_Falg)
1579
+ # if(tel_Falg == True):
1580
+ # print("Inside Telemetry Flag")
1581
+ #
1582
+ # # Trigger the API call asynchronously using a separate thread
1583
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1584
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1585
+ return response
1586
+ except PrivacyException as cie:
1587
+ log.error("Exception for uploadFIle")
1588
+ log.error(cie.__dict__)
1589
+ # ExceptionDb.create({"UUID":id,"function":"diffPrivacyFileRouter","msg":cie.__dict__,"description":cie.__dict__})
1590
+ er=[{"UUID":request_id_var.get(),"function":"diffPrivacyFileRouter","msg":cie.__dict__,"description":cie.__dict__}]
1591
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1592
+ logobj = {"uniqueid":id,"error":er}
1593
+
1594
+ if len(er)!=0:
1595
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1596
+ thread.start()
1597
+ if request_id_var.get() in error_dict:
1598
+ del error_dict[id]
1599
+ log.error(cie, exc_info=True)
1600
+ log.info("exit create from uploadFIle routing method")
1601
+ raise HTTPException(**cie.__dict__)
1602
+ except NoAccountException:
1603
+ raise HTTPException(
1604
+ status_code=430,
1605
+ detail="Portfolio/Account Is Incorrect",
1606
+ headers={"X-Error": "There goes my error"},
1607
+ )
1608
+ except Exception as e:
1609
+ log.error(str(e))
1610
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"diffPrivacyFileRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1611
+ er=[{"UUID":request_id_var.get(),"function":"diffPrivacyFileRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1612
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1613
+ logobj = {"uniqueid":id,"error":er}
1614
+
1615
+ if len(er)!=0:
1616
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1617
+ thread.start()
1618
+ if request_id_var.get() in error_dict:
1619
+ del error_dict[id]
1620
+ raise HTTPException(
1621
+ status_code=500,
1622
+ detail="Please check with administration!!",
1623
+ headers={"X-Error": "Please check with administration!!"})
1624
+
1625
+ from privacy.service.diffrentialPrivacy import DiffPrivacy
1626
+ @router.post('/privacy/DifferentialPrivacy/anonymize')
1627
+ def diff_privacy_anonymize(suppression:Optional[str]=Form(""),noiselist:Optional[str]=Form(""),binarylist:Optional[str]=Form(""),rangeList:Optional[str]=Form(""),auth= Depends(auth)):
1628
+ id = uuid.uuid4().hex
1629
+ request_id_var.set(id)
1630
+ log.info("Entered create into diffPrivacy routing method" )
1631
+ try:
1632
+ # log.info("Entered create usecase routing method" )
1633
+ # payload={"excel":excel}
1634
+ # print("payload==",payload)
1635
+ payload={"suppression":suppression,"noiselist":noiselist,"binarylist":binarylist,"rangelist":rangeList}
1636
+ # print("type==",excel.file.content_type)
1637
+ startTime = time.time()
1638
+ log.debug("Entered into diffPrivacy function")
1639
+ response = DiffPrivacy.diffPrivacy(payload)
1640
+ log.debug("Returned from diffPrivacy function")
1641
+ endTime = time.time()
1642
+ totalTime = endTime - startTime
1643
+ log.info("Total Time taken "+str(totalTime))
1644
+ if(response==None):
1645
+ raise NoAccountException
1646
+ # raise HTTPException(
1647
+ # status_code=430,
1648
+ # detail="Portfolio/Account Is Incorrect",
1649
+ # headers={"X-Error": "There goes my error"},
1650
+ # )
1651
+ # log.info("after invoking create usecase service ")
1652
+
1653
+ log.info("exit create from diffPrivacy routing method")
1654
+ log.debug("res===="+str(response))
1655
+ # telFlagData = TelemetryFlag.findall({"Module":"Privacy"})[0]
1656
+ # tel_Falg = telFlagData["TelemetryFlag"]
1657
+ # print("tel_Flag===",tel_Falg)
1658
+ # if(tel_Falg == True):
1659
+ # print("Inside Telemetry Flag")
1660
+ #
1661
+ # # Trigger the API call asynchronously using a separate thread
1662
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1663
+ # executor.submit(send_telemetry_request, privacy_telemetry_request)
1664
+ # return response
1665
+ headers = {"Content-Disposition": f"attachment; filename=x.csv"}
1666
+ return StreamingResponse(response, media_type="text/csv", headers=headers)
1667
+ except PrivacyException as cie:
1668
+ log.error("Exception for diffPrivacy")
1669
+ log.error(cie.__dict__)
1670
+ # ExceptionDb.create({"UUID":id,"function":"diffPrivacyAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__})
1671
+ er=[{"UUID":request_id_var.get(),"function":"diffPrivacyAnonimyzeRouter","msg":cie.__dict__,"description":cie.__dict__}]
1672
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1673
+ logobj = {"uniqueid":id,"error":er}
1674
+
1675
+ if len(er)!=0:
1676
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1677
+ thread.start()
1678
+ if request_id_var.get() in error_dict:
1679
+ del error_dict[id]
1680
+ log.error(cie, exc_info=True)
1681
+ log.info("exit create usecase routing method")
1682
+ raise HTTPException(**cie.__dict__)
1683
+ except NoAccountException:
1684
+ raise HTTPException(
1685
+ status_code=430,
1686
+ detail="Portfolio/Account Is Incorrect",
1687
+ headers={"X-Error": "There goes my error"},
1688
+ )
1689
+ except Exception as e:
1690
+ log.error(str(e))
1691
+ # er={"UUID":request_id_var.get(),"function":"diffPrivacyAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1692
+ er=[{"UUID":request_id_var.get(),"function":"diffPrivacyAnonimyzeRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)}]
1693
+ er.extend(error_dict[request_id_var.get()] if request_id_var.get() in error_dict else [])
1694
+ logobj = {"uniqueid":id,"error":er}
1695
+
1696
+ if len(er)!=0:
1697
+ thread = threading.Thread(target=Telemetry.error_telemetry_request, args=(logobj,id))
1698
+ thread.start()
1699
+
1700
+ if request_id_var.get() in error_dict:
1701
+ del error_dict[id]
1702
+ raise HTTPException(
1703
+ status_code=500,
1704
+ detail="Please check with administration!!",
1705
+ headers={"X-Error": "Please check with administration!!"})
1706
+
1707
+ @fileRouter.post('/privacy-files/video/anonymize')
1708
+ async def videoPrivacy(ocr: str = Query('Tesseract', enum=['Tesseract',"EasyOcr","ComputerVision"]),magnification:str=Form(...),rotationFlag:str=Form(...),video: UploadFile = File(...),portfolio:Optional[str]=Form(None),account:Optional[str]=Form(None),exclusionList:Optional[str]=Form(None),auth= Depends(auth)):
1709
+ # payload = {"video": video, "easyocr": ocr}
1710
+ id = uuid.uuid4().hex
1711
+ request_id_var.set(id)
1712
+ log.info("Entered create into image_anonymize routing method" )
1713
+ try:
1714
+ payload={"easyocr":ocr,"mag_ratio":magMap[magnification],"rotationFlag":magMap[rotationFlag],"video":video,"portfolio":portfolio,"account":account,"exclusion":exclusionList}
1715
+ startTime = time.time()
1716
+ response = await VideoService.videoPrivacy(payload)
1717
+ endTime = time.time()
1718
+ totalTime = endTime - startTime
1719
+ log.info("Total Time taken "+str(totalTime))
1720
+ if(response==None):
1721
+ raise NoAccountException
1722
+
1723
+
1724
+ log.info("exit create from image_anonymize routing method")
1725
+ return response
1726
+
1727
+ except PrivacyException as cie:
1728
+ log.error("Exception for video_privacy")
1729
+ log.error(cie.__dict__)
1730
+ # ExceptionDb.create({"UUID":id,"function":"videoPrivacyRouter","msg":cie.__dict__,"description":cie.__dict__})
1731
+
1732
+ log.error(cie, exc_info=True)
1733
+ log.info("exit create usecase routing method")
1734
+ raise HTTPException(**cie.__dict__)
1735
+ except NoAccountException:
1736
+ raise HTTPException(
1737
+ status_code=430,
1738
+ detail="Portfolio/Account Is Incorrect",
1739
+ headers={"X-Error": "There goes my error"},
1740
+ )
1741
+ except Exception as e:
1742
+ log.error(str(e))
1743
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"videoPrivacyRouter","msg":str(e),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
1744
+ raise HTTPException(
1745
+ status_code=500,
1746
+ detail="Please check with administration!!",
1747
+ headers={"X-Error": "Please check with administration!!"})
src/privacy/service/Video_service.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ import base64
12
+ import io
13
+ from typing import Tuple
14
+ import cv2
15
+ from PIL import Image
16
+ from privacy.service.imagePrivacy import AttributeDict, ImagePrivacy
17
+ import numpy as np
18
+ from privacy.config.logger import request_id_var
19
+ from privacy.config.logger import CustomLogger
20
+ import os
21
+ import shutil
22
+ import threading
23
+ import time
24
+ import uuid
25
+
26
+ log = CustomLogger()
27
+
28
+ path="../video/"
29
+ error_dict={}
30
+
31
+ class VideoService:
32
+ def frameAnonymization(payload,frame,indx,procFrame,request_id):
33
+ try:
34
+ # request_id_var.set(request_id)
35
+ id = uuid.uuid4().hex
36
+ request_id_var.set(id)
37
+ ipath=path+str(request_id)+"/"+str(indx)+".jpg"
38
+ # print(ipath)
39
+ # Convert the frame to PIL Image
40
+ # base64.b64encode(frame).decode()
41
+ # Image.open(base64.b64encode(frame).decode())
42
+ # print(type(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
43
+ imagef = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
44
+ imagef.save(ipath)
45
+ # image=open("test.jpg","rb")
46
+ # print(type(imagef))
47
+ image={"file":ipath}
48
+ image=AttributeDict(image)
49
+ payload["image"]=image
50
+ # ocr=None
51
+ # global imageAnalyzerEngine
52
+
53
+ # imageAnalyzerEngine = ImageAnalyzerEngine(analyzer_engine=analyzer,ocr=ocr)
54
+ # imageRedactorEngine = ImageRedactorEngine(image_analyzer_engine=imageAnalyzerEngine)
55
+ # redacted_image = imageRedactorEngine.redact(image, (255, 192, 203))
56
+ # payload={"easyocr":"Tesseract","mag_ratio":False,"rotationFlag":False,"image":image,"portfolio":None,"account":None,"exclusion":None}
57
+
58
+ redacted_image=ImagePrivacy.image_anonymize(payload)
59
+ decoded_bytes = base64.b64decode(redacted_image)
60
+
61
+ # Create a BytesIO object to simulate a file-like object
62
+ bio = io.BytesIO(decoded_bytes)
63
+
64
+ # Use OpenCV (assuming it's an image) or other libraries to load the image from the BytesIO object
65
+ img = cv2.imdecode(np.fromstring(bio.getvalue(), np.uint8), cv2.IMREAD_COLOR)
66
+
67
+ # Convert the PIL Image back to OpenCV frame
68
+ frame = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
69
+ procFrame[indx]=frame
70
+ return (frame,indx)
71
+ # Write the frame into the file 'output.avi'
72
+ # out.write(frame)
73
+
74
+ # else:
75
+ except Exception as e:
76
+ log.error(str(e))
77
+ log.error("Line No:"+str(e.__traceback__.tb_lineno))
78
+ log.error(str(e.__traceback__.tb_frame))
79
+ # error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"VideoAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
80
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
81
+ raise Exception(e)
82
+ # break
83
+
84
+
85
+ async def videoPrivacy(payload) -> Tuple[str, str]:
86
+ error_dict[request_id_var.get()]=[]
87
+ try:
88
+ payload=AttributeDict(payload)
89
+ upload_file = payload.video
90
+ filename=upload_file.filename
91
+
92
+ id = uuid.uuid4().hex
93
+ request_id_var.set(id)
94
+ _path=path+str(id)
95
+ if(not os.path.exists(_path)):
96
+ os.makedirs(_path)
97
+ video_data = await upload_file.read()
98
+ s=time.time()
99
+ temp_file_path = path+"input.pm4"
100
+ output_file_path =path+"output3.mp4"
101
+ with open(temp_file_path, "wb") as temp_file:
102
+ temp_file.write(video_data)
103
+ video = cv2.VideoCapture(temp_file_path)
104
+ # Get video properties
105
+ width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
106
+ height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
107
+ fps = video.get(cv2.CAP_PROP_FPS)
108
+ sampling_rate=int(fps*0.3)
109
+ # Define the codec and create a VideoWriter object
110
+ fourcc = cv2.VideoWriter_fourcc(*'XVID')
111
+ out = cv2.VideoWriter(output_file_path, fourcc, fps, (width, height))
112
+ frameList=[]
113
+ indxList=[]
114
+ first=True
115
+ count=0
116
+ last_frame=None
117
+ log.debug("samp "+str(sampling_rate))
118
+
119
+
120
+ # audio_fps = video.get(cv2.CAP_PROP_FPS)
121
+ # fourcc = int(video.get(cv2.CAP_PROP_FOURCC))
122
+ # print("aud",audio_fps,fourcc)
123
+ # sampling_rate=1
124
+ while(video.isOpened()):
125
+ ret, frame = video.read()
126
+ # print(ret)
127
+ if ret==True:
128
+ if first:
129
+ frameList.append(frame)
130
+ indxList.append(count)
131
+ first=False
132
+ else:
133
+ if count % sampling_rate == 0:
134
+ frameList.append(frame)
135
+ indxList.append(count)
136
+ # else:
137
+ # frameList.append(None)
138
+ last_frame=frame
139
+ count+=1
140
+ else:
141
+ break
142
+ if(count%sampling_rate!=0):
143
+ frameList.append(last_frame)
144
+ indxList.append(count)
145
+ log.debug("totalFrame:"+str(count))
146
+ # print(indxList,len(indxList))
147
+ log.debug("after sampling"+str(len(frameList)))
148
+ rcount=len(frameList)
149
+ framecopy=frameList.copy()
150
+ procFrame=[None]*(count+1)
151
+ # print(len(procFrame))
152
+ # indx=0
153
+ while framecopy:
154
+ threads = []
155
+ for _ in range(min(6, len(framecopy))): # Limit calls to remaining arguments
156
+ arg = framecopy.pop(0) # Get the first argument and remove it
157
+ indx=indxList.pop(0)
158
+ thread = threading.Thread(target=VideoService.frameAnonymization, args=(payload,arg,indx,procFrame,request_id_var.get()))
159
+ thread.start()
160
+ threads.append(thread)
161
+ # print(thread)
162
+ indx+=1
163
+ # Wait for all threads in the current set to finish
164
+
165
+ log.debug("remaining:"+str(rcount-len(framecopy))+"/"+str(rcount))
166
+ for thread in threads:
167
+ thread.join()
168
+ # print("===",procFrame)
169
+ # Release everything when job is finished
170
+ # print(procFrame)
171
+ lstFrame=None
172
+ for frm in procFrame:
173
+ # print(frm,frm.any())
174
+ # print(frm,frm.all())
175
+ if(lstFrame is None):
176
+ lstFrame=frm
177
+ if(frm is not None):
178
+ lstFrame=frm
179
+ else:
180
+ frm=lstFrame
181
+ out.write(frm)
182
+ video.release()
183
+ out.release()
184
+ # Remove temporary file
185
+ # os.remove(temp_file_path)
186
+ # Read the processed video file
187
+ with open(output_file_path, "rb") as video_file:
188
+ video_data = video_file.read()
189
+ # Convert the video to base64
190
+ video_str = base64.b64encode(video_data).decode()
191
+ # Remove the output file
192
+ # os.remove(output_file_path)
193
+ # log.debug(path)
194
+ shutil.rmtree(_path)
195
+ # log.debug("====",time.time()-s)
196
+ del procFrame
197
+ del indxList
198
+ del frameList
199
+ return video_str
200
+
201
+ except Exception as e:
202
+ log.error(str(e))
203
+ log.error("Line No:"+str(e.__traceback__.tb_lineno))
204
+ log.error(str(e.__traceback__.tb_frame))
205
+ error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"VideoAnonymizeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
206
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
207
+ raise Exception(e)
src/privacy/service/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextvars
2
+ from presidio_analyzer import Pattern, PatternRecognizer, AnalyzerEngine, RecognizerRegistry,predefined_recognizers
3
+ from presidio_anonymizer import AnonymizerEngine, DeanonymizeEngine
4
+ from presidio_anonymizer.entities import (RecognizerResult,
5
+ OperatorResult,
6
+ OperatorConfig)
7
+ from privacy.config.logger import CustomLogger
8
+ from presidio_image_redactor import ImageRedactorEngine,ImageAnalyzerEngine,ImagePiiVerifyEngine
9
+ from presidio_image_redactor import DicomImageRedactorEngine
10
+
11
+ from privacy.util.encrypt import EncryptImage
12
+ from privacy.config.logger import CustomLogger
13
+ log = CustomLogger()
14
+ print("===========init==========")
15
+ error_dict={}
16
+ admin_par={}
17
+ session_dict = contextvars.ContextVar('session_dict', default={})
18
+
19
+ # Example usage:
20
+ def update_session_dict(key, value):
21
+ session_dict.get()[key] = value
22
+
23
+ def get_session_dict():
24
+ return session_dict.get()
25
+
26
+ class AttributeDict(dict):
27
+ __getattr__ = dict.__getitem__
28
+ __setattr__ = dict.__setitem__
29
+ __delattr__ = dict.__delitem__
30
+
31
+ registry = RecognizerRegistry()
32
+ # log.info("============2a")
33
+ # analyzer = AnalyzerEngine(registry=registry)
34
+ # log.debug("============2b")
35
+ anonymizer = AnonymizerEngine()
36
+ # Create NLP engine based on configuration
37
+ # flair_recognizer = (
38
+ # FlairRecognizer()
39
+ # )
40
+ # registry.add_recognizer(flair_recognizer)
41
+ # provider = NlpEngineProvider(nlp_configuration=configuration)
42
+ analyzer = AnalyzerEngine(registry=registry)
43
+ imageAnalyzerEngine = ImageAnalyzerEngine(analyzer_engine=analyzer)
44
+ imageRedactorEngine = ImageRedactorEngine(image_analyzer_engine=imageAnalyzerEngine)
45
+ imagePiiVerifyEngine = ImagePiiVerifyEngine(image_analyzer_engine=imageAnalyzerEngine)
46
+ encryptImageEngin=EncryptImage(image_analyzer_engine=imageAnalyzerEngine)
47
+ deanonymizer = DeanonymizeEngine()
48
+ DicomEngine = DicomImageRedactorEngine()
49
+ registry.load_predefined_recognizers()
50
+
51
+
src/privacy/service/api_req.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from privacy.config.logger import CustomLogger,request_id_var
4
+ log = CustomLogger()
5
+ from privacy.service.__init__ import *
6
+ import time
7
+ import requests
8
+ load_dotenv()
9
+ class ApiCall:
10
+ # records=[]
11
+ # encryptionList=[]
12
+ # scoreTreshold= 0.0
13
+ def request(data):
14
+ try:
15
+ # admin_par[request_id_var]={}
16
+ # raise Exception()
17
+ # print("==================",os.getenv("ADMIN_CONNECTION"))
18
+ # print("==================",os.getenv("ADMIN_CONNECTION")=="False")
19
+
20
+ if(os.getenv("ADMIN_CONNECTION")=="False" or os.getenv("ADMIN_CONNECTION")=="false"):
21
+
22
+ # print("--------------------------------------------------------------")
23
+ return 404
24
+ # ApiCall.records.clear()
25
+ # ApiCall.encryptionList.clear()
26
+ payload=AttributeDict({"portfolio":data.portfolio,"account":data.account})
27
+
28
+ # payload={"accName":"Infosys","subAccName":"Impact"}
29
+ api_url = os.getenv("PRIVADMIN_API")
30
+
31
+ # print(api_url)
32
+ t=time.time()
33
+
34
+ # aurl="http://10.66.155.13:30016/api/v1/rai/admin/PrivacyDataList"
35
+ aurl=api_url
36
+ # log.debug(aurl)
37
+ # log.debug(str(type(aurl)))
38
+ log.debug("Calling Admin Api ======")
39
+ # log.debug("api payload:"+str(payload))
40
+ # print(payload)
41
+ response1 = requests.post(
42
+ url=aurl
43
+ , headers={'Content-Type': "application/json",
44
+ 'accept': "application/json"}
45
+ , json=payload
46
+ )
47
+ # print(response1.content[0])
48
+ # response1=httpx.post(aurl, json=payload)
49
+ # response1=httpx.post('http://10.66.155.13:30016/api/v1/rai/admin/PrivacyDataList', json=payload)
50
+ # log.debug("response="+str(response1))
51
+ # log.debug("response11="+str(response1.text))
52
+ # response1=PrivacyData.getDataList(payload)
53
+ entityType,datalist,preEntity,records,encryptionList,scoreTreshold=response1.json()["datalist"]
54
+ # print("=========================",time.time()-t)
55
+ log.debug("data fetched")
56
+ if(len(records)==0):
57
+ return None
58
+ log.debug("entityType="+str(entityType))
59
+ admin_par[request_id_var.get()]={"encryptionList":encryptionList,"records":records,"scoreTreshold":scoreTreshold[0]}
60
+ # print("===============",len(admin_par))
61
+ # ApiCall.encryptionList.extend(encryptionList)
62
+ # ApiCall.records.extend(records)
63
+ # ApiCall.scoreTreshold=scoreTreshold[0]
64
+ return(entityType,datalist,preEntity)
65
+ except Exception as e:
66
+ log.error(str(e))
67
+ log.error("Line No:"+str(e.__traceback__.tb_lineno))
68
+ log.error(str(e.__traceback__.tb_frame))
69
+ # print("------------------------------",request_id_var.get())
70
+ # ExceptionDb.create({"UUID":request_id_var.get(),"function":"ApiRequestFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
71
+ error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"ApiRequestFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
72
+ # print("err",error_dict,error_dict[request_id_var.get()])
73
+
74
+ return Exception(e)
75
+ # raise Exception(e)
76
+
77
+
78
+ # record=[ele for ele in records if ele.RecogName=="PASSPORT"][0]
79
+
80
+ def getRecord(name):
81
+ # log.debug("name="+str(name))
82
+ # log.debug("ApiCall.records="+str(ApiCall.records))
83
+ record=[ele for ele in admin_par[request_id_var.get()]["records"] if ele["RecogName"]==name][0]
84
+ return record
85
+ def delAdminList():
86
+ id=request_id_var.get()
87
+ if id in admin_par:
88
+ del admin_par[id]
src/privacy/service/azureComputerVision.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+ # from privacy.util.encrypt import EncryptImage
12
+
13
+ from presidio_image_redactor import ImageRedactorEngine,ImageAnalyzerEngine,ImagePiiVerifyEngine,OCR
14
+ # from privacy.service import easyocr_analyzer
15
+ from dotenv import load_dotenv
16
+ from privacy.config.logger import CustomLogger
17
+ # pytesseract.pytesseract.tesseract_cmd = r"C:\Users\amitumamaheshwar.h\AppData\Local\Programs\Tesseract-OCR"
18
+ import time
19
+ load_dotenv()
20
+ import os
21
+ import sys
22
+ import requests
23
+
24
+ from PIL import Image
25
+ from io import BytesIO
26
+
27
+ log = CustomLogger()
28
+
29
+ # log = CustomLogger()
30
+ # output_type = easyocr.Reader(['en'],model_storage_directory=r"privacy/util/model",download_enabled=False)
31
+
32
+ class AttributeDict(dict):
33
+ __getattr__ = dict.__getitem__
34
+ __setattr__ = dict.__setitem__
35
+ __delattr__ = dict.__delitem__
36
+ class Data:
37
+ encrypted_text=[]
38
+
39
+ apikey=os.getenv("API_KEY")
40
+ apiendpint=os.getenv("API_ENDPOINT")
41
+ # image_path=r"C:\WORK\GIT\responsible-ai-admin\responsible-ai-admin\src\rai_admin\temp\MicrosoftTeams-image (4).png"
42
+ # # Read the image into a byte array
43
+ # image_data = open(image_path, "rb").read()
44
+ # Set Content-Type to octet-stream
45
+ headers = {'Ocp-Apim-Subscription-Key': apikey, 'Content-Type': 'application/octet-stream'}
46
+ params = {'language': 'en', 'detectOrientation': 'true','features':['read']}
47
+ class ComputerVision(OCR):
48
+
49
+ def process(a):
50
+ return a
51
+
52
+
53
+
54
+
55
+ # def perform_ocr(self, image: object, **kwargs) -> dict:
56
+ # # output_type = easyocr.Reader(['en'])
57
+ # s=time.time()
58
+ # # response(code)
59
+
60
+ # textmap={"text":[],"left":[],"top":[],"width":[],"height":[],"conf":[]}
61
+ # buffer = BytesIO()
62
+
63
+ # # Save the image to the in-memory buffer in PNG format
64
+ # image.save(buffer, "PNG")
65
+
66
+ # # Get the binary data from the buffer (seek to the beginning)
67
+ # binary_data = buffer.getvalue()
68
+ # image_data = binary_data
69
+ # # put the byte array into your post request
70
+ # response = requests.post(apiendpint, headers=headers, params=params, data = image_data)
71
+
72
+ # response.raise_for_status()
73
+
74
+ # analysis = response.json()
75
+ # line_infos = [region["lines"] for region in analysis["regions"]]
76
+ # word_infos = []
77
+ # for line in line_infos:
78
+ # for word_metadata in line:
79
+ # for word_info in word_metadata["words"]:
80
+ # word_infos.append(word_info)
81
+
82
+ # for val in word_infos:
83
+ # boxval=val["boundingBox"].split(',')
84
+ # textmap["text"].append(val["text"])
85
+ # textmap["left"].append(int(boxval[0]))
86
+ # textmap["top"].append(int(boxval[1]))
87
+ # textmap["width"].append(int(boxval[2]))
88
+ # textmap["height"].append(int(boxval[3]))
89
+ # # textmap["conf"].append(val["conf"])
90
+ # # text.append(val["text"])
91
+ # # left.append(min(val['coordinates'][0][0],val["coordinates"][3][0]))
92
+ # # top.append(min(val['coordinates'][0][1],val["coordinates"][1][1]))
93
+ # # width.append(abs(val['coordinates'][1][0]-val["coordinates"][0][0]))
94
+ # # height.append(abs(val['coordinates'][3][1]-val["coordinates"][0][1]))
95
+ # # conf.append(val["conf"])
96
+ # print(textmap)
97
+ # log.warn("time======="+str(time.time()-s))
98
+ # return textmap
99
+
100
+
101
+ def perform_ocr(self, image: object, **kwargs) -> dict:
102
+ # output_type = easyocr.Reader(['en'])
103
+ s=time.time()
104
+ # response(code)
105
+
106
+ textmap={"text":[],"left":[],"top":[],"width":[],"height":[],"conf":[]}
107
+ buffer = BytesIO()
108
+
109
+ # Save the image to the in-memory buffer in PNG format
110
+ image.save(buffer, "PNG")
111
+
112
+ # Get the binary data from the buffer (seek to the beginning)
113
+ binary_data = buffer.getvalue()
114
+ image_data = binary_data
115
+ # put the byte array into your post request
116
+ response = requests.post(apiendpint, headers=headers, params=params, data = image_data)
117
+
118
+ response.raise_for_status()
119
+
120
+ analysis = response.json()
121
+ print(analysis)
122
+ line_infos = [region["lines"] for region in analysis["readResult"]["blocks"]]
123
+ textmap={"text":[],"left":[],"top":[],"width":[],"height":[],"conf":[]}
124
+ for line in line_infos:
125
+ for word_metadata in line:
126
+ for val in word_metadata["words"]:
127
+ # word_infos.append(val)
128
+ textmap["text"].append(val["text"])
129
+ textmap["left"].append(min(val['boundingPolygon'][0]['x'],val["boundingPolygon"][3]['x']))
130
+ textmap["top"].append(min(val['boundingPolygon'][0]['y'],val["boundingPolygon"][1]['y']))
131
+ textmap["width"].append(abs(val['boundingPolygon'][1]['x']-val["boundingPolygon"][0]['x']))
132
+ textmap["height"].append(abs(val['boundingPolygon'][3]['y']-val["boundingPolygon"][0]['y']))
133
+ textmap["conf"].append(val["confidence"])
134
+ print(textmap)
135
+ log.warn("time======="+str(time.time()-s))
136
+ return textmap
137
+
src/privacy/service/code_detect_service.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+
11
+
12
+ import base64
13
+ import json
14
+ import io, base64
15
+ from PIL import Image
16
+ import requests
17
+ import pandas as pd
18
+ from privacy.mappers.mappers import *
19
+ import os
20
+
21
+ from privacy.config.logger import CustomLogger
22
+ from privacy.util.code_detect import *
23
+ from privacy.util.code_detect.regexdetection import *
24
+ import json
25
+ from privacy.util.code_detect.ner.pii_inference.netcustom import code_detect_ner
26
+ log = CustomLogger()
27
+
28
+ class AttributeDict(dict):
29
+ __getattr__ = dict.__getitem__
30
+ __setattr__ = dict.__setitem__
31
+ __delattr__ = dict.__delitem__
32
+
33
+
34
+ class CodeDetect:
35
+ def codeDetectRegex(payload)->PIICodeDetectRequest:
36
+ payload=AttributeDict(payload)
37
+ print("Text===",payload)
38
+ #finalpayload=str(payload)
39
+ #ouputjson=json.loads(payload)
40
+ output_code=code_detect.codeDetectRegex(payload.inputText)
41
+ print("output_code===",output_code)
42
+ return output_code
43
+
44
+ def codeDetectNerText(payload)->PIICodeDetectRequest:
45
+ payload=AttributeDict(payload)
46
+ print("Text===",payload)
47
+ #finalpayload=str(payload)
48
+ #ouputjson=json.loads(payload)
49
+ output_code=code_detect_ner.textner(payload.inputText)
50
+ print("output_code===",output_code)
51
+ return output_code
src/privacy/service/dicomPrivacy.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd
3
+
4
+ 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:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ 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.
9
+ '''
10
+ import base64
11
+ import io
12
+ import matplotlib.pyplot as plt
13
+ import pydicom
14
+ from PIL import Image
15
+ from privacy.service.__init__ import *
16
+ from privacy.service.api_req import ApiCall
17
+ from privacy.config.logger import request_id_var
18
+
19
+
20
+
21
+ class DICOMPrivacy:
22
+ def dcmToPng(dcmObj):
23
+ plt.clf()
24
+ plt.imshow(dcmObj.pixel_array,cmap=plt.cm.bone)
25
+ plt.axis('off')
26
+ buffer=io.BytesIO()
27
+ plt.savefig(buffer,format='png', bbox_inches='tight', pad_inches=0)
28
+ buffer.seek(0)
29
+ return base64.b64encode(buffer.getvalue())
30
+
31
+
32
+
33
+
34
+ def readDicom(payload):
35
+ error_dict[request_id_var.get()]=[]
36
+ log.debug("Entering in readDicom function")
37
+ try:
38
+ # print(type(payload))
39
+ # print(payload.file)
40
+
41
+ # predefined_recognizers.data_recognizer.DataList.entity.clear()
42
+ # predefined_recognizers.data_recognizer.DataList.resetData()
43
+ DicomEngine = DicomImageRedactorEngine()
44
+ dicom_instance = pydicom.dcmread(payload.file)
45
+ # print(type(dicom_instance))
46
+ redacted_dicom_instance = DicomEngine.redact(dicom_instance, fill="contrast")
47
+ original=DICOMPrivacy.dcmToPng(dicom_instance)
48
+ redacted=DICOMPrivacy.dcmToPng(redacted_dicom_instance)
49
+
50
+ obj={"original":original,"anonymize":redacted}
51
+ log.debug("Returning from readDicom function")
52
+ return obj
53
+
54
+ except Exception as e:
55
+ log.error(str(e))
56
+ log.error("Line No:"+str(e.__traceback__.tb_lineno))
57
+ log.error(str(e.__traceback__.tb_frame))
58
+ error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"readDICOMFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
59
+ raise Exception(e)
60
+
61
+
62
+
63
+
64
+ class saveImage:
65
+ def saveImg(img_data):
66
+
67
+
68
+ with open("file.png", "wb") as fh:
69
+ fh.write(base64.decodebytes(img_data))
70
+