File size: 10,443 Bytes
f496f54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
'''
MIT license https://opensource.org/licenses/MIT Copyright 2024 Infosys Ltd

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

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

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

import secrets
import json
import io, base64
import random
from privacy.config.logger import request_id_var
import pandas as pd
from privacy.service.easy import EasyOCR
# from privacy.dao.TelemetryFlagDb import TelemetryFlag
from privacy.mappers.mappers import *
# from privacy.util.nltk_recog import CustomNltkNlpEngine
from diffprivlib.mechanisms import binary
from privacy.util.encrypt import EncryptImage

from typing import List
from privacy.constants.local_constants import (DELTED_SUCCESS_MESSAGE)
from privacy.config.logger import CustomLogger
import base64
import io
from dotenv import load_dotenv
from privacy.service.__init__ import error_dict
from diffprivlib.mechanisms import snapping
from diffprivlib.mechanisms import laplace
from diffprivlib.mechanisms import gaussian
load_dotenv()
import numpy as np
import math
log = CustomLogger()

class AttributeDict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class DiffPrivacy:
    headder=["a","b"]
    df=pd.DataFrame()

    
    def noiseAdd(df,col):
        log.info("noiseAdd Function called........")
        epsilon = 1.0  # Privacy parameter for differential privacy
        sensitivity = 1  # Sensitivity of the age values
        scale = sensitivity / epsilon
        laplace_noise = np.random.laplace(loc=0, scale=scale, size=len(df))
        # print(laplace_noise)
        # keyList=[]
        if(df[col].dtypes=='int64'):
            df[col] += laplace_noise
            df[col]=df[col].astype(int)
            # keyList.append(math.ceil(laplace_noise))
        else:
            # keyList.append(laplace_noise)
            df[col] += laplace_noise
        # DiffPrivacy.key[col]={"value":False,"key":keyList}
            
    def binaryCheck(df,col):
        log.info("BinaryCheck Function")
        data=list(df[col].unique())
        # print(data)
        # keyList=[]
        mechanism = binary.Binary(epsilon=1.0,value0=data[0],value1=data[1])
        for d in range(len(df[col])):
            temp=df.loc[d,col]
            # print("==/",temp)
            res=mechanism.randomise(temp)
            # keyList.append(int(temp==res))
            df.loc[d,col]=res
        # DiffPrivacy.key[col]={"value":data,"key":keyList}
        
        
            
    def rangeAdd(df,col):
        log.info("range Adding Function")
        import math
        minv=df[col].min()
        maxv=df[col].max()

        base=10
        maxrange=math.ceil(maxv / base) * base
        minrange=round(minv/base)*base
        
        range_magnitude = abs(maxrange - minrange)
        # print(range_magnitude)
        # Determine the number of ranges based on the magnitude``
        num_ranges = max(range_magnitude // 10, 1)  # Assuming a minimum range size of 10

        # Calculate the interval
        interval = range_magnitude / num_ranges
        binlist=set()
        lablelist=[]

        for i in range(num_ranges):
            start = minrange + i * interval
            end = minrange + (i + 1) * interval
            if(i==num_ranges-1):
                # print(i)
                end=maxrange
            binlist.add(start)
            binlist.add(end)
            lablelist.append(f"{start}-{end}")
            # ranges.append((start, end))
        binlist=sorted(list(binlist))
        df[col]=pd.cut(df[col], bins=binlist, labels=lablelist)


    def gaussianFunc(df,col):
        log.info("gaussian Function......")
        gaussianVal=gaussian.GaussianAnalytic(epsilon=1,delta=1,sensitivity=2)
        # keyList=[]
        for d in range(len(df[col])):
            temp=df.loc[d,col]
            # print("==/",temp)
            res=gaussianVal.randomise(temp)
            if(df[col].dtypes=='int64'):
                # keyList.append(math.ceil((temp-res)))
                df.loc[d,col]=int(res)
            else:    
                # keyList.append((temp-res))
                df.loc[d,col]=res
        # DiffPrivacy.key[col]={"value":False,"key":keyList}
        
        
    def laplaceFunc(df,col):
        log.info("Laplace Function......")
        minv=df[col].min()-5
        maxv=df[col].max()+5
        # keyList=[]
        laplaceVar=laplace.LaplaceTruncated(epsilon=1,delta=0,sensitivity=1,lower=minv,upper=maxv)
        for d in range(len(df[col])):
            temp=df.loc[d,col]
            # print("==/",temp)
            res=laplaceVar.randomise(temp)
            if(df[col].dtypes=='int64'):
                # keyList.append(math.ceil((temp-res)))
                df.loc[d,col]=int(res)
            else:    
                # keyList.append((temp-res))
                df.loc[d,col]=res
        # DiffPrivacy.key[col]={"value":False,"key":keyList}
    
    def snappingFunc(df,col):
        log.info("Snapping Function......")
        # print(df)
        # print(col)
        # print(df[col])
        # print(df[col].min())
        
        minv=df[col].min()-5
        maxv=df[col].max()+5
        # keyList=[]
        snappingVar=snapping.Snapping(epsilon=1,sensitivity=1,lower=minv,upper=maxv)
        for d in range(len(df[col])):
            temp=df.loc[d,col]
            # print("==/",temp)
            res=snappingVar.randomise(temp)
            if(df[col].dtypes=='int64'):
                # keyList.append(math.ceil((temp-res)))
                df.loc[d,col]=int(res)
            else:    
                # keyList.append((temp-res))
                df.loc[d,col]=res
        # DiffPrivacy.key[col]={"value":False,"key":keyList}
        
        
            
    
        
    def uploadFIle(file):
        error_dict[request_id_var.get()]=[]
        log.info("Entering in uploadFIle function")
        # print(file.file.read())
        try:
            df=pd.read_csv(file.file)
            # df=pd.read_csv(file)
            DiffPrivacy.df=df
            headders=df.columns
            print(headders)
            numaricHeadder=df.select_dtypes(include = ['int64',"float64"])
            print(numaricHeadder)
            DiffPrivacy.headder.extend(headders)
            binaryList=[]
            for c in df.columns:
    # pr    int(s)
               if(len(df[c].unique())==2):
                    binaryList.append(c)
            log.info("Returning from uploadFIle function")

            return {"allHeadders":list(headders),"numaricHeadder":list(numaricHeadder.columns),"binaryHeadder":list(binaryList)}
        except Exception as e:
            log.error(str(e))
            log.error("Line No:"+str(e.__traceback__.tb_lineno))
            log.error(str(e.__traceback__.tb_frame))
            error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
            # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
            raise Exception(e)
    def listParser(listdata):
        if(listdata[0]==""):
            
            return []
        return listdata
    def diffPrivacy(payload):
        error_dict[request_id_var.get()]=[]
        log.info("Entering in diffPrivacy function")
        try:
            log.debug(payload)
            log.debug(payload["suppression"])
            df=DiffPrivacy.df

            suppressHedder=DiffPrivacy.listParser(payload["suppression"].split(","))
            # if(suppressHedder[0]==""):
            #     suppressHedder=[]

            noiseHeadder=DiffPrivacy.listParser(payload["noiselist"].split(","))
            binaryHeadder=DiffPrivacy.listParser(payload["binarylist"].split(","))
            rangeHeadder=DiffPrivacy.listParser(payload["rangelist"].split(","))
            log.debug(df)
            log.debug(suppressHedder)
            # print(h)
            noiseList=["laplaceFunc","noiseAdd","gaussianFunc","snappingFunc"]

            noiseVar = getattr(DiffPrivacy, secrets.choice(noiseList))
            if(suppressHedder is not []):
                df = df.drop(suppressHedder, axis=1)
            for noise in noiseHeadder:
                # DiffPrivacy.noiseAdd(df,noise)
                noiseVar(df,noise)

            for bcol in binaryHeadder:
                DiffPrivacy.binaryCheck(df,bcol)

            for rcol in rangeHeadder:
                DiffPrivacy.rangeAdd(df,rcol)
            log.debug(df)


            buffer = io.BytesIO()

            df.to_csv(buffer,index=False)
            # csv=csvData.encode()
            buffer.seek(0)

            log.info("Returning from diffPrivacy function")
            # return [df,DiffPrivacy.key]
            return buffer
        except Exception as e:
            log.error(str(e))
            log.error("Line No:"+str(e.__traceback__.tb_lineno))
            log.error(str(e.__traceback__.tb_frame))
            error_dict[request_id_var.get()].append({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
            # ExceptionDb.create({"UUID":request_id_var.get(),"function":"textAnalyzeMainFunction","msg":str(e.__class__.__name__),"description":str(e)+"Line No:"+str(e.__traceback__.tb_lineno)})
            raise Exception(e)