Cristóbal Hernández commited on
Commit
52ecdad
·
1 Parent(s): 4de0aea

Add application file"

Browse files
Files changed (1) hide show
  1. app.py +79 -24
app.py CHANGED
@@ -7,19 +7,32 @@ import os
7
  ## Loading the model: ##
8
  #######################
9
  api_key = os.environ.get("HF_API_KEY_INFERENCE")
10
- API_URL = "https://api-inference.huggingface.co/models/chernandezc/distilbert-base-uncased-finetuned-items-multi-label-21122023-AUGMENTED" #Api endpoint.
11
- headers = {"Authorization": f"Bearer {api_key}"} #Api Key.
12
-
13
 
14
- def query(payload): #Function to use the API.
15
- response = requests.post(API_URL, headers=headers, json=payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  return response.json() #Return Json.
17
 
18
  # ##########################################################
19
  # Function to process the output and print classifications #
20
  ############################################################
21
  def classify_output(item):
22
- label_dict = {
 
 
23
  'LABEL_0': 'Cognition',
24
  'LABEL_1': 'Affect',
25
  'LABEL_2': 'Self',
@@ -29,38 +42,80 @@ def classify_output(item):
29
  'LABEL_6': 'Context'
30
  }
31
 
32
- output = query({ #Try to query the endpoint.
 
 
 
 
 
 
 
 
33
  "inputs": item,
34
  })
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # If the model is loading, wait and try again.
37
- while 'error' in output:
38
- time.sleep(output["estimated_time"]) #Sleep the estimated time and try again.
39
- output = query({
40
- "inputs": item,
41
- })
42
 
43
  # Store classifications in a list
44
- classifications = []
 
45
 
46
  # Find the item with the highest score
47
- highest_score_item = max(output[0], key=lambda x: x['score'])
 
48
 
49
- for item in output[0]:
50
  # Check if the score is greater than or equal to 0.5
51
  if item['score'] >= 0.5:
52
  # Append the category and score to the classifications list
53
- classifications.append((label_dict[item['label']], item['score']))
54
-
 
 
 
 
 
 
55
  # Construct and print the classification message
56
- if classifications:
57
- classification_str = ', '.join([f"{label} ({score:.2f})" for label, score in classifications])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- output1 = classification_str
60
- return output1
61
  else:
62
- output2 = f"No classifications with a score of 0.5 or higher were found. \n However, the highest probability was for: '{label_dict[highest_score_item['label']]}' ({round(item['score'],2)}) \n Use this classification with caution due to uncertainty"
63
- return output2
 
64
 
65
  #########################################
66
  ######## RUN GRADIO APP #################
 
7
  ## Loading the model: ##
8
  #######################
9
  api_key = os.environ.get("HF_API_KEY_INFERENCE")
 
 
 
10
 
11
+ #7 dimensions:
12
+ API_URL1 = "https://api-inference.huggingface.co/models/chernandezc/EEMM_7_categories_WB" #Api endpoint.
13
+ headers = {"Authorization": f"Bearer {api_key}"} #Api Key, eqwual for both.
14
+
15
+
16
+ def query1(payload): #Function to use the API.
17
+ response = requests.post(API_URL1, headers=headers, json=payload)
18
+ return response.json() #Return Json.
19
+
20
+
21
+ #3 levels:
22
+ API_URL2 = "https://api-inference.huggingface.co/models/chernandezc/EEMM_3_dimensions_1201" #Api endpoint.
23
+
24
+
25
+ def query2(payload): #Function to use the API.
26
+ response = requests.post(API_URL2, headers=headers, json=payload)
27
  return response.json() #Return Json.
28
 
29
  # ##########################################################
30
  # Function to process the output and print classifications #
31
  ############################################################
32
  def classify_output(item):
33
+
34
+ #Dictionary for dimensions.
35
+ label_dict1 = {
36
  'LABEL_0': 'Cognition',
37
  'LABEL_1': 'Affect',
38
  'LABEL_2': 'Self',
 
42
  'LABEL_6': 'Context'
43
  }
44
 
45
+ #Dictionary for levels.
46
+ label_dict2 = {
47
+ 'LABEL_0': 'Social',
48
+ 'LABEL_1': 'Psychological',
49
+ 'LABEL_2': 'Physical'
50
+ }
51
+
52
+
53
+ output1 = query1({ #Try to query the endpoint.
54
  "inputs": item,
55
  })
56
+ output2 = query2({ #Try to query the endpoint.
57
+ "inputs": item,
58
+ })
59
+
60
+ # Initial minimal delay
61
+ min_delay = 1 # seconds
62
+ #If model is idle wait and try again.
63
+ while 'error' in output1 or 'error' in output2:
64
+ if 'error' in output1:
65
+ time.sleep(min(output1.get("estimated_time", min_delay), min_delay))
66
+ output1 = query1({"inputs": item})
67
 
68
+ if 'error' in output2:
69
+ time.sleep(min(output2.get("estimated_time", min_delay), min_delay))
70
+ output2 = query2({"inputs": item})
 
 
 
71
 
72
  # Store classifications in a list
73
+ classifications1 = []
74
+ classifications2 = []
75
 
76
  # Find the item with the highest score
77
+ highest_score_item1 = max(output1[0], key=lambda x: x['score'])
78
+ highest_score_item2 = max(output2[0], key=lambda x: x['score'])
79
 
80
+ for item in output1[0]:
81
  # Check if the score is greater than or equal to 0.5
82
  if item['score'] >= 0.5:
83
  # Append the category and score to the classifications list
84
+ classifications1.append((label_dict1[item['label']], item['score']))
85
+
86
+ for item in output2[0]:
87
+ # Check if the score is greater than or equal to 0.5
88
+ if item['score'] >= 0.5:
89
+ # Append the category and score to the classifications list
90
+ classifications2.append((label_dict2[item['label']], item['score']))
91
+
92
  # Construct and print the classification message
93
+ if (classifications1 and classifications2):
94
+ classification_str1 = ', '.join([f"{label} ({score:.2f})" for label, score in classifications1])
95
+ classification_str2 = ', '.join([f"{label} ({score:.2f})" for label, score in classifications2])
96
+
97
+ output_clas_and_lev = f"For dimensions: {classification_str1}\nFor levels: {classification_str2}"
98
+
99
+ return output_clas_and_lev
100
+
101
+ elif classifications1 and not classifications2:
102
+ classification_str1 = ', '.join([f"{label} ({score:.2f})" for label, score in classifications1])
103
+
104
+ output_clas_no_lev = f"For dimensions: {classification_str1}\nFor levels: No classifications with a score of 0.5 or higher were found.\nHowever, the highest probability was for: '{label_dict2[highest_score_item2['label']]}' ({round(highest_score_item2['score'],2)})\n Use this classification with caution due to uncertainty"
105
+
106
+ return output_clas_no_lev
107
+
108
+ elif classifications2 and not classifications1:
109
+ classification_str2 = ', '.join([f"{label} ({score:.2f})" for label, score in classifications2])
110
+
111
+ output_lev_no_clas = f"For levels: {classification_str2}\nFor dimensions: No classifications with a score of 0.5 or higher were found.\nHowever, the highest probability was for: '{label_dict1[highest_score_item1['label']]}' ({round(highest_score_item1['score'],2)}) \n Use this classification with caution due to uncertainty"
112
+
113
+ return output_lev_no_clas
114
 
 
 
115
  else:
116
+ output_lev_no_no = f"No classification with a score of 0.5 or higher were found for both levels and dimensions\nThe highest probability for dimensions was: '{label_dict1[highest_score_item1['label']]}' ({round(highest_score_item1['score'],2)}\nThe highest probability for level was: '{label_dict2[highest_score_item2['label']]}' ({round(highest_score_item2['score'],2)} \n Use this classification with caution due to uncertainty"
117
+
118
+ return output_lev_no_no
119
 
120
  #########################################
121
  ######## RUN GRADIO APP #################