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