GirishKiran commited on
Commit
7a8bd09
1 Parent(s): c401999

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +252 -0
app.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """ A Utility calss which contains most commonly used functions """
3
+
4
+ import huggingface_hub
5
+ import huggingface_hub.hf_api
6
+ import psutil
7
+ import torch
8
+ import functools
9
+ import socket
10
+ import cryptography
11
+ import cryptography.fernet
12
+
13
+ class Utility(object):
14
+
15
+ def __init__(self, name="Utility") -> None:
16
+ self.name = name
17
+ self.author = "Duc Haba, Girish"
18
+ self._pp("Hello from class", str(self.__class__) + " Class: " + str(self.__class__.__name__))
19
+ self._pp("Code name", self.name)
20
+
21
+ #Define encrypted keys
22
+ self._huggingface_key="gAAAAABkgtmOIjpnjwXFWmgh1j2et2kMjHUze-ym6h3BieAp34Sqkqv3EVYvRinETvpw-kXu7RSRl5_9FqrYe-7unfakMvMkU8nHrfB3hBSC76ZTXwkVSzlN0RfBNs9NL8BGjaSJ8mz8"
23
+
24
+ #Key for crypto
25
+ self._fkey="=cvsOPRcWD6JONmdr4Sh6-PqF6nT1InYh965mI8f_sef"
26
+ return
27
+
28
+ # Print : Pretty print output name-value line
29
+ def _pp(self, a, b,is_print=True):
30
+ # print("%34s : %s" % (str(a), str(b)))
31
+ x = f'{"%34s" % str(a)} : {str(b)}'
32
+ y = None
33
+ if (is_print):
34
+ print(x)
35
+ else:
36
+ y = x
37
+ return y
38
+
39
+ # Print : Pretty print the header or footer lines
40
+ def _ph(self,is_print=True):
41
+ x = f'{"-"*34} : {"-"*34}'
42
+ y = None
43
+ if (is_print):
44
+ print(x)
45
+ else:
46
+ y = x
47
+ return y
48
+
49
+ # Hugging face : Login to Hugging face
50
+ def _login_hface(self):
51
+ huggingface_hub.login(self._decrypt_it(self._huggingface_key),
52
+ add_to_git_credential=True) # non-blocking login
53
+ self._ph()
54
+ return
55
+
56
+ # Hugging face : Push files to Hugging face
57
+ def push_hface_files(self,
58
+ hf_names,
59
+ hf_space="GirishKiran/yml",
60
+ local_dir="/content/"):
61
+ f = str(hf_names) + " is not iteratable, type: " + str(type(hf_names))
62
+ try:
63
+ for f in hf_names:
64
+ lo = local_dir + f
65
+ huggingface_hub.upload_file(
66
+ path_or_fileobj=lo,
67
+ path_in_repo=f,
68
+ repo_id=hf_space,
69
+ repo_type=huggingface_hub.REPO_TYPE_SPACE)
70
+ except Exception as e:
71
+ self._pp("*Error", e)
72
+ return
73
+
74
+ # Hugging face : Push folders to Hugging face
75
+ def push_hface_folder(self, hf_folder, hf_space_id, hf_dest_folder=None):
76
+ api = huggingface_hub.HfApi()
77
+ api.upload_folder(folder_path=hf_folder,
78
+ repo_id=hf_space_id,
79
+ path_in_repo=hf_dest_folder,
80
+ repo_type="space")
81
+ return
82
+
83
+ # Hugging face : Login to Hugging face
84
+ def _login_hface(self):
85
+ huggingface_hub.login(self._decrypt_it(self._huggingface_key),
86
+ add_to_git_credential=True) # non-blocking login
87
+ self._ph()
88
+ return
89
+
90
+ # System Info : Fetch available CPU and RAM of the system
91
+ def fetch_system_info(self):
92
+ s=''
93
+ # Get CPU usage as a percentage
94
+ cpu_usage = psutil.cpu_percent()
95
+ # Get available memory in bytes
96
+ mem = psutil.virtual_memory()
97
+ # Convert bytes to gigabytes
98
+ mem_total_gb = mem.total / (1024 ** 3)
99
+ mem_available_gb = mem.available / (1024 ** 3)
100
+ mem_used_gb = mem.used / (1024 ** 3)
101
+ # Print the results
102
+ s += f"CPU usage: {cpu_usage}%\n"
103
+ s += f"Total memory: {mem_total_gb:.2f} GB\n"
104
+ s += f"Available memory: {mem_available_gb:.2f} GB\n"
105
+ # print(f"Used memory: {mem_used_gb:.2f} GB")
106
+ s += f"Memory usage: {mem_used_gb/mem_total_gb:.2f}%\n"
107
+ return
108
+
109
+ # System Info : Fetch GPU information of the system
110
+ def fetch_gpu_info(self):
111
+ s=''
112
+ try:
113
+ s += f'Your GPU is the {torch.cuda.get_device_name(0)}\n'
114
+ s += f'GPU ready staus {torch.cuda.is_available()}\n'
115
+ s += f'GPU allocated RAM: {round(torch.cuda.memory_allocated(0)/1024**3,1)} GB\n'
116
+ s += f'GPU reserved RAM {round(torch.cuda.memory_reserved(0)/1024**3,1)} GB\n'
117
+ except Exception as e:
118
+ s += f'**Warning, No GPU: {e}'
119
+ return s
120
+
121
+ # System Info : Fetch host ip address
122
+ def fetch_host_ip(self):
123
+ s=''
124
+ hostname = socket.gethostname()
125
+ ip_address = socket.gethostbyname(hostname)
126
+ s += f"Hostname: {hostname}\n"
127
+ s += f"IP Address: {ip_address}\n"
128
+ return s
129
+
130
+ # Create and writes data to the file
131
+ def write_file(self,fname, txt):
132
+ f = open(fname, "w")
133
+ f.writelines("\n".join(txt))
134
+ f.close()
135
+ return
136
+
137
+ # Crypto : Fetch crypto key
138
+ def _fetch_crypt(self,is_generate=False):
139
+ s=self._fkey[::-1]
140
+ if (is_generate):
141
+ s=open(self._xkeyfile, "rb").read()
142
+ return s
143
+
144
+ # Crypto : Decrypt value
145
+ def _decrypt_it(self, x):
146
+ y = self._fetch_crypt()
147
+ f = cryptography.fernet.Fernet(y)
148
+ m = f.decrypt(x)
149
+ return m.decode()
150
+
151
+ # Crypto : Encrypt value
152
+ def _encrypt_it(self, x):
153
+ key = self._fetch_crypt()
154
+ p = x.encode()
155
+ f = cryptography.fernet.Fernet(key)
156
+ y = f.encrypt(p)
157
+ return y
158
+
159
+ # Add method to class
160
+ def add_method(cls):
161
+ def decorator(func):
162
+ @functools.wraps(func)
163
+ def wrapper(*args, **kwargs):
164
+ return func(*args, **kwargs)
165
+ setattr(cls, func.__name__, wrapper)
166
+ return func # returning func means func can still be used normally
167
+ return decorator
168
+
169
+
170
+ """ This file contains multiple Python classes and responssible to provide Emotions based on the given user input
171
+ Currently it supports emotions like Anger, Joy, Optimism and Sadness"""
172
+
173
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
174
+ import scipy
175
+ import scipy.special
176
+ import pandas
177
+
178
+ class SentimentAnalyser(object):
179
+
180
+ global utility
181
+
182
+ # initialize the object
183
+ def __init__(self, name="Sentiment",*args, **kwargs):
184
+ super(SentimentAnalyser, self).__init__(*args, **kwargs)
185
+ self.author = "Duc Haba, Girish"
186
+ self.name = name
187
+ utility = Utility(name="Calling From SentimentAnalyser")
188
+ self.utility = utility
189
+ utility._ph()
190
+ utility._pp("Hello from class", str(self.__class__) + " Class: " + str(self.__class__.__name__))
191
+ utility._pp("Code name", self.name)
192
+ utility._pp("Author is" , self.author)
193
+ utility._ph()
194
+ print(utility.fetch_system_info())
195
+ utility._ph()
196
+ print(utility.fetch_gpu_info())
197
+ utility._ph()
198
+ print(utility.fetch_host_ip())
199
+ utility._ph()
200
+ self._init_model()
201
+ utility._login_hface()
202
+ return
203
+
204
+ # initalise the model
205
+ def _init_model(self):
206
+ modelLink = "bhadresh-savani/distilbert-base-uncased-emotion"
207
+ self.tokenizer = AutoTokenizer.from_pretrained(modelLink)
208
+ self.model = AutoModelForSequenceClassification.from_pretrained(modelLink)
209
+ return
210
+
211
+ sentiment = SentimentAnalyser(name="EmotionAnalyser")
212
+
213
+ @add_method(SentimentAnalyser)
214
+ def _predict_sentiment(p):
215
+ # Tokenize input
216
+ inputs = sentiment.tokenizer(p, return_tensors="pt")
217
+ # Pass inputs through model
218
+ outputs = sentiment.model(**inputs)
219
+ out_data = outputs[0][0]
220
+ scores = out_data.detach().numpy()
221
+ scores = scipy.special.softmax(scores)
222
+ sentiment_map = ['Sadness', 'Joy', 'Love', 'Anger', 'Fear' , "Surprise"]
223
+ df_out = pandas.DataFrame([scores], columns=sentiment_map)
224
+ return df_out
225
+
226
+ @add_method(SentimentAnalyser)
227
+ def draw_bar_plot(df_data, title='Sentiment Analysis', xlabel='p string', ylabel='Emotion Score'):
228
+ pic = df_data.plot.bar(color=['#e89096', '#747c0c', '#84c98c','#dc545c', '#a31a0e' , '#3fbfbf'],
229
+ title=title,
230
+ ylabel=ylabel,
231
+ xlabel=xlabel,
232
+ grid=True)
233
+ return pic
234
+
235
+ @add_method(SentimentAnalyser)
236
+ def predict_sentiment(p):
237
+ df_out = _predict_sentiment(p)
238
+ max_column = df_out.loc[0].idxmax()
239
+ max_value = df_out.loc[0].max()
240
+ title = f'Sentiment Analysis: {max_column}: {round(max_value*100,1)}%'
241
+ xlabel= f'Input: {p}'
242
+ pic = draw_bar_plot(df_out, title=title, xlabel=xlabel)
243
+ return pic.get_figure(), df_out.to_json()
244
+
245
+ import gradio
246
+ in_box = [gradio.Textbox(lines=1, label="Input request", placeholder="your message")]
247
+ out_box = [gradio.Plot(label="Sentiment Score:"),
248
+ gradio.Textbox(lines=4, label="Response Raw JSON Data:")]
249
+
250
+ gradio.Interface(fn=predict_sentiment,
251
+ inputs=in_box,
252
+ outputs=out_box).launch(debug=True)