aimodelshare 0.1.32__py3-none-any.whl → 0.1.62__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of aimodelshare might be problematic. Click here for more details.

Files changed (38) hide show
  1. aimodelshare/__init__.py +94 -14
  2. aimodelshare/aimsonnx.py +312 -95
  3. aimodelshare/api.py +13 -12
  4. aimodelshare/auth.py +163 -0
  5. aimodelshare/aws.py +4 -4
  6. aimodelshare/base_image.py +1 -1
  7. aimodelshare/containerisation.py +1 -1
  8. aimodelshare/data_sharing/download_data.py +142 -87
  9. aimodelshare/generatemodelapi.py +7 -6
  10. aimodelshare/main/authorization.txt +275 -275
  11. aimodelshare/main/eval_lambda.txt +81 -13
  12. aimodelshare/model.py +493 -197
  13. aimodelshare/modeluser.py +89 -1
  14. aimodelshare/moral_compass/README.md +408 -0
  15. aimodelshare/moral_compass/__init__.py +37 -0
  16. aimodelshare/moral_compass/_version.py +3 -0
  17. aimodelshare/moral_compass/api_client.py +601 -0
  18. aimodelshare/moral_compass/apps/__init__.py +17 -0
  19. aimodelshare/moral_compass/apps/tutorial.py +198 -0
  20. aimodelshare/moral_compass/challenge.py +365 -0
  21. aimodelshare/moral_compass/config.py +187 -0
  22. aimodelshare/playground.py +26 -14
  23. aimodelshare/preprocessormodules.py +60 -6
  24. aimodelshare/pyspark/authorization.txt +258 -258
  25. aimodelshare/pyspark/eval_lambda.txt +1 -1
  26. aimodelshare/reproducibility.py +20 -5
  27. aimodelshare/utils/__init__.py +78 -0
  28. aimodelshare/utils/optional_deps.py +38 -0
  29. aimodelshare-0.1.62.dist-info/METADATA +298 -0
  30. {aimodelshare-0.1.32.dist-info → aimodelshare-0.1.62.dist-info}/RECORD +33 -25
  31. {aimodelshare-0.1.32.dist-info → aimodelshare-0.1.62.dist-info}/WHEEL +1 -1
  32. aimodelshare-0.1.62.dist-info/licenses/LICENSE +5 -0
  33. {aimodelshare-0.1.32.dist-info → aimodelshare-0.1.62.dist-info}/top_level.txt +0 -1
  34. aimodelshare-0.1.32.dist-info/METADATA +0 -78
  35. aimodelshare-0.1.32.dist-info/licenses/LICENSE +0 -22
  36. tests/__init__.py +0 -0
  37. tests/test_aimsonnx.py +0 -135
  38. tests/test_playground.py +0 -721
@@ -1,258 +1,258 @@
1
- from __future__ import print_function
2
-
3
- import re
4
- import json
5
-
6
-
7
- def handler(event, context):
8
- print("Client token: " + event['authorizationToken'])
9
- print("Method ARN: " + event['methodArn'])
10
-
11
- '''
12
- Validate the incoming token and produce the principal user identifier
13
- associated with the token. This can be accomplished in a number of ways:
14
-
15
- 1. Call out to the OAuth provider
16
- 2. Decode a JWT token inline
17
- 3. Lookup in a self-managed DB
18
- '''
19
- idtoken=event['authorizationToken']
20
- try:
21
- tokenbodydata=json.loads(idtoken)
22
- idtoken=tokenbodydata['token']
23
- evaltrue=tokenbodydata['eval']
24
- except:
25
- evaltrue="FALSE"
26
-
27
- print(event)
28
- principalId = idtoken
29
- import jwt
30
- decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
31
-
32
- # Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
33
- # 200 status indicates accept, 403 means unauthorized
34
-
35
-
36
- #==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
37
-
38
- '''
39
- You can send a 401 Unauthorized response to the client by failing like so:
40
-
41
- raise Exception('Unauthorized')
42
-
43
- If the token is valid, a policy must be generated which will allow or deny
44
- access to the client. If access is denied, the client will receive a 403
45
- Access Denied response. If access is allowed, API Gateway will proceed with
46
- the backend integration configured on the method that was called.
47
-
48
- This function must generate a policy that is associated with the recognized
49
- principal user identifier. Depending on your use case, you might store
50
- policies in a DB, or generate them on the fly.
51
-
52
- Keep in mind, the policy is cached for 5 minutes by default (TTL is
53
- configurable in the authorizer) and will apply to subsequent calls to any
54
- method/resource in the RestApi made with the same token.
55
-
56
- The example policy below denies access to all resources in the RestApi.
57
- '''
58
- tmp = event['methodArn'].split(':')
59
- apiGatewayArnTmp = tmp[5].split('/')
60
- awsAccountId = tmp[4]
61
-
62
- policy = AuthPolicy(principalId, awsAccountId)
63
- policy.restApiId = apiGatewayArnTmp[0]
64
- policy.region = tmp[3]
65
- policy.stage = apiGatewayArnTmp[1]
66
-
67
-
68
- #====================Accept/Deny auth for AIMODELSHARE begins here===========================================
69
- import requests
70
-
71
-
72
- headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
73
-
74
- response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
75
- json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
76
- print(response.status_code)
77
- uniquemodversion=str(response.text)
78
-
79
- print(response.text)
80
- if any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
81
- policyresult="deny"
82
- else:
83
- policyresult="accept"
84
-
85
- if policyresult=="deny":
86
- policy.denyAllMethods()
87
- else:
88
- policy.allowAllMethods()
89
-
90
- # Finally, build the policy
91
- authResponse = policy.build()
92
- authResponse['context']['uniquemodversion']=uniquemodversion
93
-
94
- # new! -- add additional key-value pairs associated with the authenticated principal
95
- # these are made available by APIGW like so: $context.authorizer.<key>
96
- # additional context is cached
97
-
98
-
99
-
100
- return authResponse
101
-
102
-
103
- class HttpVerb:
104
- GET = 'GET'
105
- POST = 'POST'
106
- PUT = 'PUT'
107
- PATCH = 'PATCH'
108
- HEAD = 'HEAD'
109
- DELETE = 'DELETE'
110
- OPTIONS = 'OPTIONS'
111
- ALL = '*'
112
-
113
-
114
- class AuthPolicy(object):
115
- # The AWS account id the policy will be generated for. This is used to create the method ARNs.
116
- awsAccountId = ''
117
- # The principal used for the policy, this should be a unique identifier for the end user.
118
- principalId = ''
119
- # The policy version used for the evaluation. This should always be '2012-10-17'
120
- version = '2012-10-17'
121
- # The regular expression used to validate resource paths for the policy
122
- pathRegex = '^[/.a-zA-Z0-9-\*]+$'
123
-
124
- '''Internal lists of allowed and denied methods.
125
-
126
- These are lists of objects and each object has 2 properties: A resource
127
- ARN and a nullable conditions statement. The build method processes these
128
- lists and generates the approriate statements for the final policy.
129
- '''
130
- allowMethods = []
131
- denyMethods = []
132
-
133
- # The API Gateway API id. By default this is set to '*'
134
- restApiId = '*'
135
- # The region where the API is deployed. By default this is set to '*'
136
- region = '*'
137
- # The name of the stage used in the policy. By default this is set to '*'
138
- stage = '*'
139
-
140
- def __init__(self, principal, awsAccountId):
141
- self.awsAccountId = awsAccountId
142
- self.principalId = principal
143
- self.allowMethods = []
144
- self.denyMethods = []
145
-
146
- def _addMethod(self, effect, verb, resource, conditions):
147
- '''Adds a method to the internal lists of allowed or denied methods. Each object in
148
- the internal list contains a resource ARN and a condition statement. The condition
149
- statement can be null.'''
150
- if verb != '*' and not hasattr(HttpVerb, verb):
151
- raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
152
- resourcePattern = re.compile(self.pathRegex)
153
- if not resourcePattern.match(resource):
154
- raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
155
-
156
- if resource[:1] == '/':
157
- resource = resource[1:]
158
-
159
- resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
160
-
161
- if effect.lower() == 'allow':
162
- self.allowMethods.append({
163
- 'resourceArn': resourceArn,
164
- 'conditions': conditions
165
- })
166
- elif effect.lower() == 'deny':
167
- self.denyMethods.append({
168
- 'resourceArn': resourceArn,
169
- 'conditions': conditions
170
- })
171
-
172
- def _getEmptyStatement(self, effect):
173
- '''Returns an empty statement object prepopulated with the correct action and the
174
- desired effect.'''
175
- statement = {
176
- 'Action': 'execute-api:Invoke',
177
- 'Effect': effect[:1].upper() + effect[1:].lower(),
178
- 'Resource': []
179
- }
180
-
181
- return statement
182
-
183
- def _getStatementForEffect(self, effect, methods):
184
- '''This function loops over an array of objects containing a resourceArn and
185
- conditions statement and generates the array of statements for the policy.'''
186
- statements = []
187
-
188
- if len(methods) > 0:
189
- statement = self._getEmptyStatement(effect)
190
-
191
- for curMethod in methods:
192
- if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
193
- statement['Resource'].append(curMethod['resourceArn'])
194
- else:
195
- conditionalStatement = self._getEmptyStatement(effect)
196
- conditionalStatement['Resource'].append(curMethod['resourceArn'])
197
- conditionalStatement['Condition'] = curMethod['conditions']
198
- statements.append(conditionalStatement)
199
-
200
- if statement['Resource']:
201
- statements.append(statement)
202
-
203
- return statements
204
-
205
- def allowAllMethods(self):
206
- '''Adds a '*' allow to the policy to authorize access to all methods of an API'''
207
- self._addMethod('Allow', HttpVerb.ALL, '*', [])
208
-
209
- def denyAllMethods(self):
210
- '''Adds a '*' allow to the policy to deny access to all methods of an API'''
211
- self._addMethod('Deny', HttpVerb.ALL, '*', [])
212
-
213
- def allowMethod(self, verb, resource):
214
- '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
215
- methods for the policy'''
216
- self._addMethod('Allow', verb, resource, [])
217
-
218
- def denyMethod(self, verb, resource):
219
- '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
220
- methods for the policy'''
221
- self._addMethod('Deny', verb, resource, [])
222
-
223
- def allowMethodWithConditions(self, verb, resource, conditions):
224
- '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
225
- methods and includes a condition for the policy statement. More on AWS policy
226
- conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
227
- self._addMethod('Allow', verb, resource, conditions)
228
-
229
- def denyMethodWithConditions(self, verb, resource, conditions):
230
- '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
231
- methods and includes a condition for the policy statement. More on AWS policy
232
- conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
233
- self._addMethod('Deny', verb, resource, conditions)
234
-
235
- def build(self):
236
- '''Generates the policy document based on the internal lists of allowed and denied
237
- conditions. This will generate a policy with two main statements for the effect:
238
- one statement for Allow and one statement for Deny.
239
- Methods that includes conditions will have their own statement in the policy.'''
240
- if ((self.allowMethods is None or len(self.allowMethods) == 0) and
241
- (self.denyMethods is None or len(self.denyMethods) == 0)):
242
- raise NameError('No statements defined for the policy')
243
-
244
- policy = {
245
- 'principalId': self.principalId,
246
- 'policyDocument': {
247
- 'Version': self.version,
248
- 'Statement': []
249
- },
250
- "context": {
251
- "uniquemodversion":"string"
252
- }
253
- }
254
-
255
- policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
256
- policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
257
-
258
- return policy
1
+ from __future__ import print_function
2
+
3
+ import re
4
+ import json
5
+
6
+
7
+ def handler(event, context):
8
+ print("Client token: " + event['authorizationToken'])
9
+ print("Method ARN: " + event['methodArn'])
10
+
11
+ '''
12
+ Validate the incoming token and produce the principal user identifier
13
+ associated with the token. This can be accomplished in a number of ways:
14
+
15
+ 1. Call out to the OAuth provider
16
+ 2. Decode a JWT token inline
17
+ 3. Lookup in a self-managed DB
18
+ '''
19
+ idtoken=event['authorizationToken']
20
+ try:
21
+ tokenbodydata=json.loads(idtoken)
22
+ idtoken=tokenbodydata['token']
23
+ evaltrue=tokenbodydata['eval']
24
+ except:
25
+ evaltrue="FALSE"
26
+
27
+ print(event)
28
+ principalId = idtoken
29
+ import jwt
30
+ decoded = jwt.decode(idtoken, options={"verify_signature": False}) # works in PyJWT < v2.0
31
+
32
+ # Check token access with live rest api (with cognito auth activated) to ensure user isn't sending incorrect username
33
+ # 200 status indicates accept, 403 means unauthorized
34
+
35
+
36
+ #==============AIMODELSHARE Note: accept / deny languange located on line 67=======================================================
37
+
38
+ '''
39
+ You can send a 401 Unauthorized response to the client by failing like so:
40
+
41
+ raise Exception('Unauthorized')
42
+
43
+ If the token is valid, a policy must be generated which will allow or deny
44
+ access to the client. If access is denied, the client will receive a 403
45
+ Access Denied response. If access is allowed, API Gateway will proceed with
46
+ the backend integration configured on the method that was called.
47
+
48
+ This function must generate a policy that is associated with the recognized
49
+ principal user identifier. Depending on your use case, you might store
50
+ policies in a DB, or generate them on the fly.
51
+
52
+ Keep in mind, the policy is cached for 5 minutes by default (TTL is
53
+ configurable in the authorizer) and will apply to subsequent calls to any
54
+ method/resource in the RestApi made with the same token.
55
+
56
+ The example policy below denies access to all resources in the RestApi.
57
+ '''
58
+ tmp = event['methodArn'].split(':')
59
+ apiGatewayArnTmp = tmp[5].split('/')
60
+ awsAccountId = tmp[4]
61
+
62
+ policy = AuthPolicy(principalId, awsAccountId)
63
+ policy.restApiId = apiGatewayArnTmp[0]
64
+ policy.region = tmp[3]
65
+ policy.stage = apiGatewayArnTmp[1]
66
+
67
+
68
+ #====================Accept/Deny auth for AIMODELSHARE begins here===========================================
69
+ import requests
70
+
71
+
72
+ headers_with_authentication = {'Content-Type': 'application/json', 'Authorization': idtoken}
73
+
74
+ response=requests.post("https://1b861v14ne.execute-api.us-east-1.amazonaws.com/dev/redisusagetrackerembedded",
75
+ json={"apiid": str(policy.restApiId),"eval":evaltrue}, headers=headers_with_authentication)
76
+ print(response.status_code)
77
+ uniquemodversion=str(response.text)
78
+
79
+ print(response.text)
80
+ if any([response.status_code!=200,response.text.find("Missing")>0,response.text.find("Monthly")>0,response.text.find("monthly")>0]):
81
+ policyresult="deny"
82
+ else:
83
+ policyresult="accept"
84
+
85
+ if policyresult=="deny":
86
+ policy.denyAllMethods()
87
+ else:
88
+ policy.allowAllMethods()
89
+
90
+ # Finally, build the policy
91
+ authResponse = policy.build()
92
+ authResponse['context']['uniquemodversion']=uniquemodversion
93
+
94
+ # new! -- add additional key-value pairs associated with the authenticated principal
95
+ # these are made available by APIGW like so: $context.authorizer.<key>
96
+ # additional context is cached
97
+
98
+
99
+
100
+ return authResponse
101
+
102
+
103
+ class HttpVerb:
104
+ GET = 'GET'
105
+ POST = 'POST'
106
+ PUT = 'PUT'
107
+ PATCH = 'PATCH'
108
+ HEAD = 'HEAD'
109
+ DELETE = 'DELETE'
110
+ OPTIONS = 'OPTIONS'
111
+ ALL = '*'
112
+
113
+
114
+ class AuthPolicy(object):
115
+ # The AWS account id the policy will be generated for. This is used to create the method ARNs.
116
+ awsAccountId = ''
117
+ # The principal used for the policy, this should be a unique identifier for the end user.
118
+ principalId = ''
119
+ # The policy version used for the evaluation. This should always be '2012-10-17'
120
+ version = '2012-10-17'
121
+ # The regular expression used to validate resource paths for the policy
122
+ pathRegex = '^[/.a-zA-Z0-9-\*]+$'
123
+
124
+ '''Internal lists of allowed and denied methods.
125
+
126
+ These are lists of objects and each object has 2 properties: A resource
127
+ ARN and a nullable conditions statement. The build method processes these
128
+ lists and generates the approriate statements for the final policy.
129
+ '''
130
+ allowMethods = []
131
+ denyMethods = []
132
+
133
+ # The API Gateway API id. By default this is set to '*'
134
+ restApiId = '*'
135
+ # The region where the API is deployed. By default this is set to '*'
136
+ region = '*'
137
+ # The name of the stage used in the policy. By default this is set to '*'
138
+ stage = '*'
139
+
140
+ def __init__(self, principal, awsAccountId):
141
+ self.awsAccountId = awsAccountId
142
+ self.principalId = principal
143
+ self.allowMethods = []
144
+ self.denyMethods = []
145
+
146
+ def _addMethod(self, effect, verb, resource, conditions):
147
+ '''Adds a method to the internal lists of allowed or denied methods. Each object in
148
+ the internal list contains a resource ARN and a condition statement. The condition
149
+ statement can be null.'''
150
+ if verb != '*' and not hasattr(HttpVerb, verb):
151
+ raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')
152
+ resourcePattern = re.compile(self.pathRegex)
153
+ if not resourcePattern.match(resource):
154
+ raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)
155
+
156
+ if resource[:1] == '/':
157
+ resource = resource[1:]
158
+
159
+ resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)
160
+
161
+ if effect.lower() == 'allow':
162
+ self.allowMethods.append({
163
+ 'resourceArn': resourceArn,
164
+ 'conditions': conditions
165
+ })
166
+ elif effect.lower() == 'deny':
167
+ self.denyMethods.append({
168
+ 'resourceArn': resourceArn,
169
+ 'conditions': conditions
170
+ })
171
+
172
+ def _getEmptyStatement(self, effect):
173
+ '''Returns an empty statement object prepopulated with the correct action and the
174
+ desired effect.'''
175
+ statement = {
176
+ 'Action': 'execute-api:Invoke',
177
+ 'Effect': effect[:1].upper() + effect[1:].lower(),
178
+ 'Resource': []
179
+ }
180
+
181
+ return statement
182
+
183
+ def _getStatementForEffect(self, effect, methods):
184
+ '''This function loops over an array of objects containing a resourceArn and
185
+ conditions statement and generates the array of statements for the policy.'''
186
+ statements = []
187
+
188
+ if len(methods) > 0:
189
+ statement = self._getEmptyStatement(effect)
190
+
191
+ for curMethod in methods:
192
+ if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
193
+ statement['Resource'].append(curMethod['resourceArn'])
194
+ else:
195
+ conditionalStatement = self._getEmptyStatement(effect)
196
+ conditionalStatement['Resource'].append(curMethod['resourceArn'])
197
+ conditionalStatement['Condition'] = curMethod['conditions']
198
+ statements.append(conditionalStatement)
199
+
200
+ if statement['Resource']:
201
+ statements.append(statement)
202
+
203
+ return statements
204
+
205
+ def allowAllMethods(self):
206
+ '''Adds a '*' allow to the policy to authorize access to all methods of an API'''
207
+ self._addMethod('Allow', HttpVerb.ALL, '*', [])
208
+
209
+ def denyAllMethods(self):
210
+ '''Adds a '*' allow to the policy to deny access to all methods of an API'''
211
+ self._addMethod('Deny', HttpVerb.ALL, '*', [])
212
+
213
+ def allowMethod(self, verb, resource):
214
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
215
+ methods for the policy'''
216
+ self._addMethod('Allow', verb, resource, [])
217
+
218
+ def denyMethod(self, verb, resource):
219
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
220
+ methods for the policy'''
221
+ self._addMethod('Deny', verb, resource, [])
222
+
223
+ def allowMethodWithConditions(self, verb, resource, conditions):
224
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed
225
+ methods and includes a condition for the policy statement. More on AWS policy
226
+ conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
227
+ self._addMethod('Allow', verb, resource, conditions)
228
+
229
+ def denyMethodWithConditions(self, verb, resource, conditions):
230
+ '''Adds an API Gateway method (Http verb + Resource path) to the list of denied
231
+ methods and includes a condition for the policy statement. More on AWS policy
232
+ conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''
233
+ self._addMethod('Deny', verb, resource, conditions)
234
+
235
+ def build(self):
236
+ '''Generates the policy document based on the internal lists of allowed and denied
237
+ conditions. This will generate a policy with two main statements for the effect:
238
+ one statement for Allow and one statement for Deny.
239
+ Methods that includes conditions will have their own statement in the policy.'''
240
+ if ((self.allowMethods is None or len(self.allowMethods) == 0) and
241
+ (self.denyMethods is None or len(self.denyMethods) == 0)):
242
+ raise NameError('No statements defined for the policy')
243
+
244
+ policy = {
245
+ 'principalId': self.principalId,
246
+ 'policyDocument': {
247
+ 'Version': self.version,
248
+ 'Statement': []
249
+ },
250
+ "context": {
251
+ "uniquemodversion":"string"
252
+ }
253
+ }
254
+
255
+ policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))
256
+ policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))
257
+
258
+ return policy
@@ -827,7 +827,7 @@ def get_leaderboard(task_type="$task_type", verbose=3, columns=None):
827
827
  newleaderboard = pd.read_csv("/tmp/"+"model_eval_data_mastertable_v"+str(i)+".csv", sep="\t")
828
828
  newleaderboard.drop(newleaderboard.filter(regex="Unname"),axis=1, inplace=True)
829
829
 
830
- leaderboard=pd.concat([leaderboard, newleaderboard]).drop_duplicates()
830
+ leaderboard=leaderboard.append(newleaderboard).drop_duplicates()
831
831
 
832
832
  leaderboard.drop(leaderboard.filter(regex="Unname"),axis=1, inplace=True)
833
833
  #save new leaderboard here
@@ -3,11 +3,22 @@ import sys
3
3
  import json
4
4
  import random
5
5
  import tempfile
6
- import pkg_resources
7
6
  import requests
8
7
 
9
8
  import numpy as np
10
- import tensorflow as tf
9
+
10
+ # TensorFlow is optional - only needed for reproducibility setup with TF models
11
+ try:
12
+ import tensorflow as tf
13
+ _TF_AVAILABLE = True
14
+ except ImportError:
15
+ _TF_AVAILABLE = False
16
+ tf = None
17
+
18
+ try:
19
+ import importlib.metadata as md
20
+ except ImportError: # pragma: no cover
21
+ import importlib_metadata as md
11
22
 
12
23
  from aimodelshare.aws import get_s3_iam_client, run_function_on_lambda, get_aws_client
13
24
 
@@ -44,9 +55,13 @@ def export_reproducibility_env(seed, directory, mode="gpu"):
44
55
  else:
45
56
  raise Exception("Error: unknown 'mode' value, expected 'gpu' or 'cpu'")
46
57
 
47
- installed_packages = pkg_resources.working_set
48
- installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
49
- for i in installed_packages])
58
+ # Get installed packages using importlib.metadata
59
+ installed_packages_list = []
60
+ for dist in md.distributions():
61
+ name = dist.metadata.get("Name") or "unknown"
62
+ version = dist.version
63
+ installed_packages_list.append(f"{name}=={version}")
64
+ installed_packages_list = sorted(installed_packages_list)
50
65
 
51
66
  data["session_runtime_info"] = {
52
67
  "installed_packages": installed_packages_list,
@@ -0,0 +1,78 @@
1
+ """Utility modules for aimodelshare."""
2
+ import os
3
+ import sys
4
+ import shutil
5
+ import tempfile
6
+ import functools
7
+ import warnings
8
+ from typing import Type
9
+
10
+ from .optional_deps import check_optional
11
+
12
+
13
+ def delete_files_from_temp_dir(temp_dir_file_deletion_list):
14
+ temp_dir = tempfile.gettempdir()
15
+ for file_name in temp_dir_file_deletion_list:
16
+ file_path = os.path.join(temp_dir, file_name)
17
+ if os.path.exists(file_path):
18
+ os.remove(file_path)
19
+
20
+
21
+ def delete_folder(folder_path):
22
+ if os.path.exists(folder_path):
23
+ shutil.rmtree(folder_path)
24
+
25
+
26
+ def make_folder(folder_path):
27
+ os.makedirs(folder_path, exist_ok=True)
28
+
29
+
30
+ class HiddenPrints:
31
+ """Context manager that suppresses stdout and stderr (used for silencing noisy outputs)."""
32
+ def __enter__(self):
33
+ self._original_stdout = sys.stdout
34
+ self._original_stderr = sys.stderr
35
+ self._devnull_stdout = open(os.devnull, 'w')
36
+ self._devnull_stderr = open(os.devnull, 'w')
37
+ sys.stdout = self._devnull_stdout
38
+ sys.stderr = self._devnull_stderr
39
+ return self
40
+
41
+ def __exit__(self, exc_type, exc_val, exc_tb):
42
+ sys.stdout = self._original_stdout
43
+ sys.stderr = self._original_stderr
44
+ self._devnull_stdout.close()
45
+ self._devnull_stderr.close()
46
+
47
+
48
+ def ignore_warning(warning: Type[Warning]):
49
+ """
50
+ Ignore a given warning occurring during method execution.
51
+
52
+ Args:
53
+ warning (Warning): warning type to ignore.
54
+
55
+ Returns:
56
+ the inner function
57
+ """
58
+
59
+ def inner(func):
60
+ @functools.wraps(func)
61
+ def wrapper(*args, **kwargs):
62
+ with warnings.catch_warnings():
63
+ warnings.filterwarnings("ignore", category=warning)
64
+ return func(*args, **kwargs)
65
+
66
+ return wrapper
67
+
68
+ return inner
69
+
70
+
71
+ __all__ = [
72
+ "check_optional",
73
+ "HiddenPrints",
74
+ "ignore_warning",
75
+ "delete_files_from_temp_dir",
76
+ "delete_folder",
77
+ "make_folder",
78
+ ]