martin8 commited on
Commit
66c65d8
1 Parent(s): 896d82d

Upload app.py

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