martin8 commited on
Commit
84672ab
1 Parent(s): 8737d42

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +800 -0
app.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TextClassificationPipeline
2
+ from transformers import AutoTokenizer
3
+ from transformers import pipeline
4
+ import evaluate
5
+ import gradio as gr
6
+ import torch
7
+ import random
8
+ from transformers.file_utils import is_tf_available, is_torch_available, is_torch_tpu_available
9
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
10
+ from datasets import load_metric
11
+ from sklearn.model_selection import train_test_split
12
+ import pandas as pd
13
+ import numpy as np
14
+ import streamlit as st
15
+ from textblob import TextBlob
16
+ from streamlit_extras.switch_page_button import switch_page
17
+ from transformers import YolosImageProcessor, YolosForObjectDetection
18
+ from PIL import Image
19
+ import torch
20
+ import requests
21
+ import numpy as np
22
+ import torchvision
23
+ from torchvision.io import read_image
24
+ from torchvision.utils import draw_bounding_boxes
25
+ from transformers import DetrImageProcessor, DetrForObjectDetection
26
+ from transformers import DetrImageProcessor, DetrForObjectDetection
27
+ from transformers import pipeline
28
+ import torch
29
+ from transformers import PegasusForConditionalGeneration, PegasusTokenizer
30
+
31
+
32
+ st.set_page_config(layout="wide")
33
+ def get_models(prompt):
34
+ #prompt = input("Enter your AI task idea:")
35
+ response = pipe(prompt)
36
+ print("AI Model Idea: ", prompt,"\n")
37
+
38
+ x = pd.json_normalize(response[0])
39
+ # x.nlargest(3,['score'])["label"].values
40
+ knowledge_base_tasks = ['depth-estimation', 'image-classification', 'image-segmentation',
41
+ 'image-to-image', 'object-detection', 'video-classification',
42
+ 'unconditional-image-generation', 'zero-shot-image-classification',
43
+ 'conversational', 'fill-mask', 'question-answering',
44
+ 'sentence-similarity', 'summarization', 'table-question-answering',
45
+ 'text-classification', 'text-generation', 'token-classification',
46
+ 'translation', 'zero-shot-classification']
47
+
48
+ temp = []
49
+ for label_code in x.nlargest(3,['score'])["label"].values:
50
+ temp.append(label_code[6:])
51
+ # temp
52
+
53
+ cat_to_model = {}
54
+ top_cats = []
55
+
56
+ for i in range(len(temp)):
57
+ print("Possible Category ",i+1," : ",knowledge_base_tasks[int(temp[i])])
58
+ print("Top three models for this category are:",models_list[models_list["pipeline_tag"] == knowledge_base_tasks[int(temp[i])]].nlargest(3,"downloads")["modelId"].values)
59
+ cat_to_model[knowledge_base_tasks[int(temp[i])]] = models_list[models_list["pipeline_tag"] == knowledge_base_tasks[int(temp[i])]].nlargest(3,"downloads")["modelId"].values
60
+ top_cats.append(knowledge_base_tasks[int(temp[i])])
61
+ # models_list[models_list["pipeline_tag"] == "image-classification"].nlargest(3,"downloads")["modelId"].values
62
+ print()
63
+ print("Returning category-models dictionary..")
64
+ return top_cats,cat_to_model
65
+
66
+
67
+
68
+ def get_top_3(top_cat):
69
+
70
+ top_3_df = pd.read_csv("./Top_3_models.csv")
71
+ top_3 = []
72
+ for i in range(top_3_df.shape[0]):
73
+ if top_3_df["Category"].iloc[i].lower() == top_cat:
74
+ top_3.append(top_3_df["Model_1"].iloc[i])
75
+ top_3.append(top_3_df["Model_2"].iloc[i])
76
+ top_3.append(top_3_df["Model_3"].iloc[i])
77
+ break
78
+ return top_3
79
+
80
+
81
+
82
+
83
+
84
+ def get_top_3_a(prompt,pipe):
85
+ response = pipe(prompt)
86
+ x = pd.json_normalize(response[0])
87
+ temp = []
88
+ for label_code in x.nlargest(3,['score'])["label"].values:
89
+ temp.append(label_code[6:])
90
+ knowledge_base_tasks = ['depth-estimation', 'image-classification', 'image-segmentation',
91
+ 'image-to-image', 'object-detection', 'video-classification',
92
+ 'unconditional-image-generation', 'zero-shot-image-classification',
93
+ 'conversational', 'fill-mask', 'question-answering',
94
+ 'sentence-similarity', 'summarization', 'table-question-answering',
95
+ 'text-classification', 'text-generation', 'token-classification',
96
+ 'translation', 'zero-shot-classification']
97
+
98
+ top_cat = knowledge_base_tasks[int(temp[0])]
99
+
100
+
101
+ top_3_df = pd.read_csv("./Top_3_models.csv")
102
+ top_3 = []
103
+ for i in range(top_3_df.shape[0]):
104
+ if top_3_df["Category"].iloc[i] == top_cat:
105
+ top_3.append(top_3_df["Model_1"].iloc[i])
106
+ top_3.append(top_3_df["Model_2"].iloc[i])
107
+ top_3.append(top_3_df["Model_3"].iloc[i])
108
+ break
109
+ return top_cat,top_3
110
+
111
+
112
+
113
+
114
+ def get_response(input_text,model_name):
115
+ torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
116
+ tokenizer = PegasusTokenizer.from_pretrained(model_name)
117
+ model = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device)
118
+ batch = tokenizer([input_text],truncation=True,padding='longest',max_length=1024, return_tensors="pt").to(torch_device)
119
+ gen_out = model.generate(**batch,max_length=128,num_beams=5, num_return_sequences=1, temperature=1.5)
120
+ output_text = tokenizer.batch_decode(gen_out, skip_special_tokens=True)
121
+ return output_text
122
+
123
+
124
+ def summarizer (models, data):
125
+ model_Eval = {}
126
+ for i in range (len(models)):
127
+ # print(models[i])
128
+ if models[i] == 'tuner007/pegasus_summarizer':
129
+ model_name = 'tuner007/pegasus_summarizer'
130
+
131
+ result = get_response(data,model_name)
132
+ rouge = evaluate.load('rouge')
133
+ # print("345",rouge.compute(predictions=[result],references=[data]))
134
+ print(type(result), type([data]))
135
+ quality = rouge.compute(predictions=[result[0]],references=[data])
136
+ model_Eval[models[i]] = {"Score":quality,"Result": result}
137
+ else:
138
+ summarizer_model = pipeline("summarization", model = models[i])
139
+ print(models[i], summarizer_model(data))
140
+ try:
141
+ result = summarizer_model(data)[0]["summary_text"]
142
+ rouge = evaluate.load('rouge')
143
+ # print("345",rouge.compute(predictions=[result],references=[data]))
144
+ quality = rouge.compute(predictions=[result],references=[data])
145
+ model_Eval[models[i]] = {"Score":quality,"Result": result}
146
+ except:
147
+ print("Model {} has issues.".format(models[i]))
148
+
149
+ return model_Eval
150
+
151
+
152
+
153
+
154
+ def best_model (analysis, data):
155
+ best_model_score = 0
156
+ best_model_name = ""
157
+ best_model_result = ""
158
+ temp2 = 0
159
+ for model in analysis.keys():
160
+ temp1 = analysis[model]["Score"]["rougeLsum"]
161
+ if temp1 > temp2:
162
+ temp2 = analysis[model]["Score"]["rougeLsum"]
163
+ best_model_score = analysis[model]["Score"]
164
+ best_model_name = model
165
+ best_model_result = analysis[model]["Result"]
166
+
167
+ return best_model_name, best_model_score,data[:50],best_model_result.replace("\n","")
168
+
169
+
170
+
171
+ def text_summarization():
172
+ top_models = get_top_3("summarization")
173
+ # st.write("Upload your file: ")
174
+ # uploaded_files = ""
175
+ # uploaded_files = st.file_uploader("Choose your file", accept_multiple_files=True)
176
+
177
+
178
+
179
+
180
+ option = st.selectbox(
181
+ 'What text would you like AI to summarize for you now ?',
182
+ ("Choose text files below:",'How to Win friends - Text', 'The Age of Intelligent Machines', 'The Singularity is Near - Ray Kurzweil.txt')) #add 2 other options of files here
183
+
184
+ if option == 'How to Win friends - Text' or option == 'The Age of Intelligent Machines' or option == 'The Singularity is Near - Ray Kurzweil.txt':### update book text files here
185
+ st.write('You selected:', option)
186
+
187
+ if option == 'How to Win friends - Text': # add text
188
+ name = "How_to_win_friends.txt"
189
+ st.write("Selected file for analyis is: How_to_win_friends.txt")
190
+ st.write("\nThank you for your patience. AI is generating 3 different outputs for you to compare")
191
+
192
+ if option == 'The Age of Intelligent Machines':
193
+ name = "The Age of Intelligent Machines.txt"
194
+ st.write("Selected file for analyis is: The Age of Intelligent Machines.txt")
195
+ st.write("\nThank you for your patience. AI is generating 3 different outputs for you to compare")
196
+
197
+ if option == "The Singularity is Near - Ray Kurzweil.txt":
198
+ name = "The Singularity is Near - Ray Kurzweil.txt"
199
+ st.write("The Singularity is Near - Ray Kurzweil.txt")
200
+ st.write("\nThank you for your patience. AI is generating 3 different outputs for you to compare")
201
+
202
+ if st.button("Accept"):
203
+ global file_data
204
+ # st.write("filename:", uploaded_files)
205
+ # for uploaded_file in uploaded_files:
206
+ # # print("here")
207
+ # file_data = open(uploaded_file.name,encoding="utf8").read()
208
+ # st.write("filename:", uploaded_file.name)
209
+ # # st.write(file_data[:500])
210
+ # # print("before summarizer")
211
+ # print(file_data[:50])
212
+ file_data = open(name,encoding="utf8").read()
213
+
214
+ analysis = summarizer(models = top_models, data = file_data[:500])
215
+
216
+ x,c,v,b = best_model(analysis,file_data[:500])
217
+ # st.write("Best model for Task: ",z)
218
+
219
+ st.markdown(f'<p style="color: #012d51;font-size:32px;border-radius:%;">{"Best Model with Summarization Results"}</p>', unsafe_allow_html=True)
220
+ st.write("\nBest model name: ",x)
221
+ # st.write("\nBest model Score: ",c)
222
+
223
+ st.write("Best Model Rouge Scores: ")
224
+ st.write("Rouge 1 Score: ",c["rouge1"])
225
+ st.write("Rouge 2 Score: ",c["rouge2"])
226
+ st.write("Rouge L Score: ",c["rougeL"])
227
+ st.write("Rouge LSum Score: ",c["rougeLsum"])
228
+
229
+ st.write("\nOriginal Data first 50 characters: ", v)
230
+ st.write("\nBest Model Result: ",b)
231
+
232
+
233
+ # print("between summarizer analysis")
234
+ st.markdown(f'<p style="color: #012d51;font-size:32px;border-radius:%;">{"Summarization Results for Model 1: Bart"}</p>', unsafe_allow_html=True)
235
+ # st.write("Summarization Results for Model 1")
236
+ st.write("Model name: facebook/bart-large-cnn")
237
+ st.write("Rouge Scores: ")
238
+ st.write("Rouge 1 Score: ",analysis["facebook/bart-large-cnn"]["Score"]["rouge1"])
239
+ st.write("Rouge 2 Score: ",analysis["facebook/bart-large-cnn"]["Score"]["rouge2"])
240
+ st.write("Rouge L Score: ",analysis["facebook/bart-large-cnn"]["Score"]["rougeL"])
241
+ st.write(f"Rouge LSum Score: ",analysis["facebook/bart-large-cnn"]["Score"]["rougeLsum"])
242
+ st.write("Result: ", analysis["facebook/bart-large-cnn"]["Result"])
243
+
244
+ st.markdown(f'<p style="color: #012d51;font-size:32px;border-radius:%;">{"Summarization Results for Model 2: Pegasus"}</p>', unsafe_allow_html=True)
245
+ # st.write("Summarization Results for Model 2")
246
+ st.write("Model name: tuner007/pegasus_summarizer")
247
+ st.write("Rouge Scores: ")
248
+ st.write("Rouge 1 Score: ",analysis["tuner007/pegasus_summarizer"]["Score"]["rouge1"])
249
+ st.write("Rouge 2 Score: ",analysis["tuner007/pegasus_summarizer"]["Score"]["rouge2"])
250
+ st.write("Rouge L Score: ",analysis["tuner007/pegasus_summarizer"]["Score"]["rougeL"])
251
+ st.write("Rouge LSum Score: ",analysis["tuner007/pegasus_summarizer"]["Score"]["rougeLsum"])
252
+ st.write("Result: ", analysis["tuner007/pegasus_summarizer"]["Result"][0])
253
+
254
+
255
+
256
+ st.markdown(f'<p style="color: #012d51;font-size:32px;border-radius:%;">{"Summarization Results for Model 3: Distilbart"}</p>', unsafe_allow_html=True)
257
+ # st.write("Summarization Results for Model 3")
258
+ st.write("Model name: sshleifer/distilbart-cnn-12-6")
259
+ st.write("Rouge Scores: ")
260
+ st.write("Rouge 1 Score: ",analysis["sshleifer/distilbart-cnn-12-6"]["Score"]["rouge1"])
261
+ st.write("Rouge 2 Score: ",analysis["sshleifer/distilbart-cnn-12-6"]["Score"]["rouge2"])
262
+ st.write("Rouge L Score: ",analysis["sshleifer/distilbart-cnn-12-6"]["Score"]["rougeL"])
263
+ st.write("Rouge LSum Score: ",analysis["sshleifer/distilbart-cnn-12-6"]["Score"]["rougeLsum"])
264
+
265
+ st.write("Result: ", analysis["sshleifer/distilbart-cnn-12-6"]["Result"])
266
+
267
+
268
+
269
+
270
+ #OBJECT DETECTION
271
+
272
+ def yolo_tiny(name):
273
+ image = read_image(name)
274
+
275
+ model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')
276
+ image_processor = YolosImageProcessor.from_pretrained("hustvl/yolos-tiny")
277
+
278
+ inputs = image_processor(images=image, return_tensors="pt")
279
+ outputs = model(**inputs)
280
+
281
+ # model predicts bounding boxes and corresponding COCO classes
282
+ logits = outputs.logits
283
+ bboxes = outputs.pred_boxes
284
+
285
+
286
+ # print results
287
+ target_sizes = torch.tensor([image.shape[::-1][:2]])
288
+
289
+ results = image_processor.post_process_object_detection(outputs, threshold=0.7, target_sizes=target_sizes)[0]
290
+
291
+ label_ = []
292
+ bboxes = []
293
+
294
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
295
+ box = [round(i, 2) for i in box.tolist()]
296
+ print(
297
+ f"Detected {model.config.id2label[label.item()]} with confidence "
298
+ f"{round(score.item(), 3)} at location {box}"
299
+ )
300
+
301
+ label_.append(model.config.id2label[label.item()])
302
+ bboxes.append(np.asarray(box,dtype="int"))
303
+ bboxes = torch.tensor(bboxes, dtype=torch.int)
304
+
305
+ img=draw_bounding_boxes(image, bboxes,labels = label_, width=3)
306
+ img = torchvision.transforms.ToPILImage()(img)
307
+ return img
308
+ # img.show()
309
+
310
+
311
+
312
+ def resnet_101(name):
313
+ image = read_image(name)
314
+ processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-101")
315
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-101")
316
+
317
+ inputs = processor(images=image, return_tensors="pt")
318
+ outputs = model(**inputs)
319
+
320
+ # convert outputs (bounding boxes and class logits) to COCO API
321
+ # let's only keep detections with score > 0.9
322
+ target_sizes = torch.tensor([image.shape[::-1][:2]])
323
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.7)[0]
324
+ label_ = []
325
+ bboxes = []
326
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
327
+ box = [round(i, 2) for i in box.tolist()]
328
+ print(
329
+ f"Detected {model.config.id2label[label.item()]} with confidence "
330
+ f"{round(score.item(), 3)} at location {box}")
331
+ label_.append(model.config.id2label[label.item()])
332
+ bboxes.append(np.asarray(box,dtype="int"))
333
+ bboxes = torch.tensor(bboxes, dtype=torch.int)
334
+
335
+
336
+ bboxes = torch.tensor(bboxes, dtype=torch.int)
337
+
338
+ img=draw_bounding_boxes(image, bboxes,labels = label_, width=3)
339
+ img = torchvision.transforms.ToPILImage()(img)
340
+ return img
341
+
342
+
343
+
344
+
345
+
346
+ def resnet_50(name):
347
+ image = read_image(name)
348
+ processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
349
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
350
+
351
+ inputs = processor(images=image, return_tensors="pt")
352
+ outputs = model(**inputs)
353
+
354
+ # convert outputs (bounding boxes and class logits) to COCO API
355
+ # let's only keep detections with score > 0.9
356
+ target_sizes = torch.tensor([image.shape[::-1][:2]])
357
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.7)[0]
358
+ label_ = []
359
+ bboxes = []
360
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
361
+ box = [round(i, 2) for i in box.tolist()]
362
+ print(
363
+ f"Detected {model.config.id2label[label.item()]} with confidence "
364
+ f"{round(score.item(), 3)} at location {box}"
365
+ )
366
+ label_.append(model.config.id2label[label.item()])
367
+ bboxes.append(np.asarray(box,dtype="int"))
368
+ bboxes = torch.tensor(bboxes, dtype=torch.int)
369
+
370
+ bboxes = torch.tensor(bboxes, dtype=torch.int)
371
+
372
+ img=draw_bounding_boxes(image, bboxes,labels = label_, width=3)
373
+ img = torchvision.transforms.ToPILImage()(img)
374
+ return img
375
+
376
+
377
+
378
+ def object_detection():
379
+ # st.write("Upload your image: ")
380
+ # uploaded_files = ""
381
+ # uploaded_files = st.file_uploader("Choose a image file", accept_multiple_files=True)
382
+
383
+ option = st.selectbox(
384
+ 'What image you want for analysis?',
385
+ ("Choose an image for object detection analysis from the options below:",'Cat and Dog', '2 lazy cats chilling on a couch', 'An astronaut riding wild horse'))
386
+
387
+ if option == 'Cat and Dog' or option == '2 lazy cats chilling on a couch' or option == 'An astronaut riding wild horse':
388
+ st.write('You selected:', option)
389
+
390
+ if option == 'Cat and Dog':
391
+ name = "cat_dog.jpg"
392
+ st.image("cat_dog.jpg")
393
+
394
+ if option == '2 lazy cats chilling on a couch':
395
+ name = "cat_remote.jpg"
396
+ st.image("cat_remote.jpg")
397
+
398
+ if option == 'An astronaut riding wild horse':
399
+ name = "astronaut_rides_horse.png"
400
+ st.image("astronaut_rides_horse.png")
401
+
402
+ if st.button("Accept"):
403
+ # global file_data
404
+ # st.write("filename:", uploaded_files)
405
+ # for uploaded_file in uploaded_files:
406
+ # print("here")
407
+ # file_data = open(uploaded_file.name).read()
408
+ st.write("filename:", name)
409
+ # name = uploaded_file.name
410
+ st.image([yolo_tiny(name),resnet_101(name),resnet_50(name)],caption=["hustvl/yolos-tiny","facebook/detr-resnet-101","facebook/detr-resnet-50"])
411
+
412
+
413
+ def task_categorization_model_predictions():
414
+ st.image("./panelup.png")
415
+
416
+ # st.title("Text Analysis App")
417
+
418
+ data = ""
419
+
420
+ classifier = pipeline("zero-shot-classification",model="facebook/bart-large-mnli")
421
+
422
+ global check
423
+
424
+ st.markdown(f'<p style="color: #012d51;font-size:18px;border-radius:%;">{"Write down below the description of your AI application in few sentences:"}</p>', unsafe_allow_html=True)
425
+
426
+ prompt = st.text_input(" ")
427
+
428
+ st.write("")
429
+ st.write("")
430
+
431
+ if prompt != "":
432
+ # sbert_saved_model = torch.load("Sbert_saved_model", map_location=torch.device('cpu')).to("cpu")
433
+ # model = sbert_saved_model.to("cpu")
434
+ # tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-mpnet-base-v2")
435
+ # pipe = TextClassificationPipeline(model= model, tokenizer=tokenizer, return_all_scores=True)
436
+ # # outputs a list of dicts like [[{'label': 'NEGATIVE', 'score': 0.0001223755971295759}, {'label': 'POSITIVE', 'score': 0.9998776316642761}]]
437
+
438
+ # # prompt = ["What is the the best ai for putting text report into data table?","How can I generate car sales agreement with ai model?","AI model to detect burglar on 48 hours of cctv video footage","I need Ai model help me with rewriting 50 financial statements emails into one summary report ?","I need a model for extracting person from an image"]
439
+ # # responses = pipe(prompt)
440
+
441
+
442
+ # models_list = pd.read_csv("models.csv")
443
+ # # st.write(get_top_3(prompt))
444
+
445
+ # top_cat, top_models = get_top_3(prompt)
446
+ # # prompt = input("Enter your AI task idea:")
447
+ # # top_cats,cat_to_models = get_models(prompt)
448
+
449
+ # # top_models = cat_to_models[top_cats[0]]
450
+
451
+ # top_cat = " " + top_cat[0].upper() + top_cat[1:]
452
+
453
+
454
+
455
+ st.markdown(f'<p style="color: #012d51;font-size:24px;border-radius:%;">{"Recognized AI Domain: "}</p>', unsafe_allow_html=True)
456
+
457
+ domains = ["Computer Vision Task","Natural Language Processing Problem","Audio Operations Problem","Tabular Data Task","Reinforcement Learning Problem","Time Series Forecasting Problem"]
458
+
459
+
460
+
461
+ #st.write(classifier(prompt, domains))
462
+ domain = classifier(prompt, domains)["labels"][0]
463
+
464
+ st.markdown(f'<p style="background-color:#12d51; color:#1782ea;font-size:18px;border-radius:%;">{domain}</p>', unsafe_allow_html=True)
465
+ # st.write("Recommended AI Domain Type: ",top_cat)
466
+ check = 0
467
+ if st.button("This seems accurate"):
468
+ check = 1
469
+ if st.button("Show me other likely category recommendations:"):
470
+ if domain == "Tabular Data Problem":
471
+ if st.button("Computer Vision Task"):
472
+ domain = "Computer Vision Task"
473
+ check = 1
474
+ if st.button("Natural Language Processing Problem"):
475
+ domain = "Natural Language Processing Problem"
476
+ check = 1
477
+ if st.button("Multimodal AI Model"):
478
+ domain = "Multimodal AI Model"
479
+ check = 1
480
+ if st.button("Audio Operations Problem"):
481
+ domain = "Audio Operations Problem"
482
+ check = 1
483
+ # if st.button("Tabular Data Task"):
484
+ # domain = "Tabular Data Task"
485
+ if st.button("Reinforcement Learning Problem"):
486
+ domain = "Reinforcement Learning Problem"
487
+ check = 1
488
+ if st.button("Time Series Forecasting Problem"):
489
+ domain = "Time Series Forecasting Problem"
490
+ check = 1
491
+
492
+
493
+ if domain == "Computer Vision Task":
494
+ # if st.button("Computer Vision Task"):
495
+ # domain = "Computer Vision Task"
496
+ if st.button("Natural Language Processing Problem"):
497
+ domain = "Natural Language Processing Problem"
498
+ check = 1
499
+
500
+ if st.button("Multimodal AI Model"):
501
+ domain = "Multimodal AI Model"
502
+ check = 1
503
+
504
+ if st.button("Audio Operations Problem"):
505
+ domain = "Audio Operations Problem"
506
+ check = 1
507
+ if st.button("Tabular Data Task"):
508
+ domain = "Tabular Data Task"
509
+ check = 1
510
+ if st.button("Reinforcement Learning Problem"):
511
+ domain = "Reinforcement Learning Problem"
512
+ check = 1
513
+ if st.button("Time Series Forecasting Problem"):
514
+ domain = "Time Series Forecasting Problem"
515
+ check = 1
516
+
517
+
518
+ if domain == "Natural Language Processing Problem":
519
+ if st.button("Computer Vision Task"):
520
+ domain = "Computer Vision Task"
521
+ check = 1
522
+ # if st.button("Natural Language Processing Problem"):
523
+ # domain = "Natural Language Processing Problem"
524
+ if st.button("Multimodal AI Model"):
525
+ domain = "multimodal"
526
+ check = 1
527
+ if st.button("Audio Operations Problem"):
528
+ domain = "Audio Operations Problem"
529
+ check = 1
530
+ if st.button("Tabular Data Task"):
531
+ domain = "Tabular Data Task"
532
+ check = 1
533
+ if st.button("Reinforcement Learning Problem"):
534
+ domain = "Reinforcement Learning Problem"
535
+ check = 1
536
+ if st.button("Time Series Forecasting Problem"):
537
+ domain = "Time Series Forecasting Problem"
538
+ check = 1
539
+
540
+
541
+ if domain == "Multimodal AI Model":
542
+ if st.button("Computer Vision Task"):
543
+ domain = "Computer Vision Task"
544
+ check = 1
545
+ if st.button("Natural Language Processing Problem"):
546
+ domain = "Natural Language Processing Problem"
547
+ check = 1
548
+ # if st.button("Multimodal AI Model"):
549
+ # domain = "Multimodal AI Model"
550
+ if st.button("Audio Operations Problem"):
551
+ domain = "Audio Operations Problem"
552
+ check = 1
553
+ if st.button("Tabular Data Task"):
554
+ domain = "Tabular Data Task"
555
+ check = 1
556
+ if st.button("Reinforcement Learning Problem"):
557
+ domain = "Reinforcement Learning Problem"
558
+ check = 1
559
+ if st.button("Time Series Forecasting Problem"):
560
+ domain = "Time Series Forecasting Problem"
561
+ check = 1
562
+
563
+
564
+ if domain == "audio":
565
+ if st.button("Computer Vision Task"):
566
+ domain = "Computer Vision Task"
567
+ check = 1
568
+ if st.button("Natural Language Processing Problem"):
569
+ domain = "Natural Language Processing Problem"
570
+ check = 1
571
+ if st.button("Multimodal AI Model"):
572
+ domain = "Multimodal AI Model"
573
+ check = 1
574
+ # if st.button("Audio Operations Problem"):
575
+ # domain = "Audio Operations Problem"
576
+ if st.button("Tabular Data Task"):
577
+ domain = "Tabular Data Task"
578
+ check = 1
579
+ if st.button("Reinforcement Learning Problem"):
580
+ domain = "Reinforcement Learning Problem"
581
+ check = 1
582
+ if st.button("Time Series Forecasting Problem"):
583
+ domain = "Time Series Forecasting Problem"
584
+ check = 1
585
+
586
+
587
+ if domain == "reinforcement-learning":
588
+ if st.button("Computer Vision Task"):
589
+ domain = "Computer Vision Task"
590
+ check = 1
591
+ if st.button("Natural Language Processing Problem"):
592
+ domain = "Natural Language Processing Problem"
593
+ check = 1
594
+ if st.button("Multimodal AI Model"):
595
+ domain = "multimodal"
596
+ check = 1
597
+ if st.button("Audio Operations Problem"):
598
+ domain = "Audio Operations Problem"
599
+ check = 1
600
+ if st.button("Tabular Data Task"):
601
+ domain = "Tabular Data Task"
602
+ check = 1
603
+ # if st.button("Reinforcement Learning Problem"):
604
+ # domain = "Reinforcement Learning Problem"
605
+ if st.button("Time Series Forecasting Problem"):
606
+ domain = "Time Series Forecasting Problem"
607
+ check = 1
608
+
609
+ if domain == "Time Series Forecasting":
610
+ if st.button("Computer Vision Task"):
611
+ domain = "Computer Vision Task"
612
+ check = 1
613
+ if st.button("Natural Language Processing Problem"):
614
+ domain = "Natural Language Processing Problem"
615
+ check = 1
616
+ if st.button("Multimodal AI Model"):
617
+ domain = "Multimodal AI Model"
618
+ check = 1
619
+ if st.button("Audio Operations Problem"):
620
+ domain = "Audio Operations Problem"
621
+ check = 1
622
+ if st.button("Tabular Data Task"):
623
+ domain = "Tabular Data Task"
624
+ check = 1
625
+ if st.button("Reinforcement Learning Problem"):
626
+ domain = "Reinforcement Learning Problem"
627
+ check = 1
628
+ # if st.button("Time Series Forecasting Problem"):
629
+ # domain = "Time Series Forecasting Problem"
630
+
631
+ # st.write("Recommended Models for category: ",top_cats[0], " are:",top_models)
632
+
633
+ # st.write("Recommended Task category: ",top_models[0])
634
+
635
+
636
+
637
+ knowledge_base_tasks = {"Computer Vision Task":['depth-estimation', 'image-classification', 'image-segmentation',
638
+ 'image-to-image', 'object-detection', 'video-classification',
639
+ 'unconditional-image-generation', 'zero-shot-image-classification'],"Natural Language Processing Problem":[
640
+ 'conversational', 'fill-mask', 'question-answering',
641
+ 'sentence-similarity', 'summarization', 'table-question-answering',
642
+ 'text-classification', 'text-generation', 'token-classification',
643
+ 'translation', 'zero-shot-classification'],"Audio Operations Problem":["audio-classification","audio-to-audio","automatic-speech-recognition",
644
+ "text-to-speech"],"Tabular Data Task":["tabular-classification","tabular-regression"],"others":["document-question-answering",
645
+ "feature-extraction","image-to-text","text-to-image","text-to-video","visual-question-answering"],
646
+ "Reinforcement Learning Problem":["reinforcement-learning"],"time-series-forecasting":["time-series-forecasting"]}
647
+
648
+ # st.write(check)
649
+ # st.write(domain)
650
+ if check == 1:
651
+
652
+ category = classifier(prompt, knowledge_base_tasks[domain])["labels"][0]
653
+
654
+
655
+ st.markdown(f'<p style="color: #012d51;font-size:24px;border-radius:%;">{"Recognized sub category in Domain: "+domain}</p>', unsafe_allow_html=True)
656
+
657
+ st.markdown(f'<p style="background-color:#12d51; color:#1782ea;font-size:18px;border-radius:%;">{category}</p>', unsafe_allow_html=True)
658
+
659
+
660
+ top_models = get_top_3(category)
661
+ #st.write(top_models)
662
+ st.markdown(f'<p style=" margin-left: 0px;color: #012d51;font-size:18px;border-radius:%;">{"The best models selected for this domain:"}</p>', unsafe_allow_html=True)
663
+
664
+
665
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"1- "+top_models[0]}</p>', unsafe_allow_html=True)
666
+
667
+ st.image("./buttons1.png")
668
+
669
+ # if st.button("Show more"):
670
+
671
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"2- "+top_models[1]}</p>', unsafe_allow_html=True)
672
+ st.image("./buttons1.png")
673
+
674
+
675
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"3- "+top_models[2]}</p>', unsafe_allow_html=True)
676
+ st.image("./buttons1.png")
677
+
678
+
679
+
680
+
681
+
682
+
683
+
684
+ def model_selector_sbert():
685
+
686
+ st.image("./panelup.jpg")
687
+
688
+ # st.title("Text Analysis App")
689
+
690
+ data = ""
691
+
692
+
693
+ st.markdown(f'<p style="color: #012d51;font-size:18px;border-radius:%;">{"Please, enter your AI task:"}</p>', unsafe_allow_html=True)
694
+
695
+ prompt = st.text_input(" ")
696
+
697
+ st.write("")
698
+ st.write("")
699
+
700
+ if prompt != "":
701
+ sbert_saved_model = torch.load("Sbert_saved_model", map_location=torch.device('cpu')).to("cpu")
702
+ model = sbert_saved_model.to("cpu")
703
+ tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-mpnet-base-v2")
704
+ pipe = TextClassificationPipeline(model= model, tokenizer=tokenizer, return_all_scores=True)
705
+ # outputs a list of dicts like [[{'label': 'NEGATIVE', 'score': 0.0001223755971295759}, {'label': 'POSITIVE', 'score': 0.9998776316642761}]]
706
+
707
+ # prompt = ["What is the the best ai for putting text report into data table?","How can I generate car sales agreement with ai model?","AI model to detect burglar on 48 hours of cctv video footage","I need Ai model help me with rewriting 50 financial statements emails into one summary report ?","I need a model for extracting person from an image"]
708
+ # responses = pipe(prompt)
709
+
710
+
711
+ models_list = pd.read_csv("models.csv")
712
+ # st.write(get_top_3(prompt))
713
+
714
+ top_cat, top_models = get_top_3_a(prompt,pipe)
715
+ # prompt = input("Enter your AI task idea:")
716
+ # top_cats,cat_to_models = get_models(prompt)
717
+
718
+ # top_models = cat_to_models[top_cats[0]]
719
+
720
+ top_cat = " " + top_cat[0].upper() + top_cat[1:]
721
+ st.markdown(f'<p style="color: #012d51;font-size:24px;border-radius:%;">{"Recognized AI Domain Category: "}</p>', unsafe_allow_html=True)
722
+
723
+ st.markdown(f'<p style="background-color:#12d51; color:#1782ea;font-size:18px;border-radius:%;">{top_cat}</p>', unsafe_allow_html=True)
724
+ # st.write("Recommended AI Domain Type: ",top_cat)
725
+ # st.write("Recommended Models for category: ",top_cats[0], " are:",top_models)
726
+
727
+ # st.write("Recommended Task category: ",top_models[0])
728
+
729
+
730
+ st.markdown(f'<p style=" margin-left: 0px;color: #012d51;font-size:18px;border-radius:%;">{"The best models selected for this task:"}</p>', unsafe_allow_html=True)
731
+
732
+
733
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"1- "+top_models[0]}</p>', unsafe_allow_html=True)
734
+
735
+ st.image("./buttons1.png")
736
+
737
+ if st.button("Show more"):
738
+
739
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"2- "+top_models[1]}</p>', unsafe_allow_html=True)
740
+ st.image("./buttons1.png")
741
+
742
+
743
+ st.markdown(f'<p style="margin-left: 0px;background-color:#e1e1e1; color:#012d51;font-size:18px;border-radius:%;">{"3- "+top_models[2]}</p>', unsafe_allow_html=True)
744
+ st.image("./buttons1.png")
745
+
746
+
747
+
748
+
749
+ page_names_to_funcs = {
750
+ "Select the best Model for your AI app":model_selector_sbert,
751
+ "Compare Model Outputs on Object Detection": object_detection,
752
+ "Compare Model Outputs on Text Summarization": text_summarization
753
+ }
754
+
755
+ demo_name = st.sidebar.selectbox("Find the best model for your next AI task or compare model outputs", page_names_to_funcs.keys())
756
+ page_names_to_funcs[demo_name]()
757
+
758
+
759
+
760
+ # st.write("Recommended Most Popular Model for category ",top_cat, " is:",top_models[0])
761
+ # if st.button("Show more"):
762
+ # for i in range(1,len(top_models)):
763
+ # st.write("Model#",str(i+1),top_models[i])
764
+
765
+
766
+ # data = prompt
767
+
768
+ # # print("before len data")
769
+
770
+ # if len(data) != 0:
771
+ # # print("after len data")
772
+ # st.write("Recommended Task category: ",top_cats[0])
773
+ # st.write("Recommended Most Popular Model for category ",top_cats[0], " is:",top_models[0])
774
+ # if st.button("Show more"):
775
+ # for i in range(1,len(top_models)):
776
+ # st.write("Model#",str(i+1),top_models[i])
777
+
778
+ # st.write("Upload your file: ")
779
+ # uploaded_files = ""
780
+ # uploaded_files = st.file_uploader("Choose a text file", accept_multiple_files=True)
781
+ # if st.button("Select"):
782
+ # global file_data
783
+ # st.write("filename:", uploaded_files)
784
+ # for uploaded_file in uploaded_files:
785
+ # # print("here")
786
+ # file_data = open(uploaded_file.name,encoding="utf8").read()
787
+ # st.write("filename:", uploaded_file.name)
788
+ # # st.write(file_data[:500])
789
+ # # print("before summarizer")
790
+ # print(file_data[:500])
791
+ # analysis = summarizer(models = top_models, data = file_data[:500])
792
+ # # print("between summarizer analysis")
793
+
794
+ # z,x,c,v,b = best_model(analysis,file_data[:500])
795
+ # st.write("Best model for Task: ",z)
796
+ # st.write("\nBest model name: ",x)
797
+ # st.write("\nBest model Score: ",c)
798
+ # st.write("\nOriginal Data first 500 characters: ", v)
799
+ # st.write("\nBest Model Result: ",b)
800
+ # st.success(result)