CobaltZvc commited on
Commit
a0bef4f
1 Parent(s): 382f93f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +355 -352
app.py CHANGED
@@ -172,381 +172,291 @@ def openai_response(PROMPT):
172
  #}
173
  #</style>
174
  #"""
175
-
176
- #st.markdown(page_bg_img, unsafe_allow_html=True)
177
- st.title("Ask :red[Mukesh] anything!!🤖")
178
- st.title("Puchne mai kya jaata hai??")
179
-
180
- option_ = ['Random Questions','Questions based on custom CSV data']
181
- Usage = st.selectbox('Select an option:', option_)
182
- if Usage == 'Questions based on custom CSV data':
183
- st.text('''
184
- You can use your own custom csv files to test this feature or
185
- you can use the sample csv file which contains data about cars.
186
-
187
- Example question:
188
- - How many cars were manufactured each year between 2000 to 2008?
189
- ''')
190
 
191
- option = ['Sample_Cars_csv','Upload_csv']
192
- res = st.selectbox('Select from below options:',option)
193
- if res == 'Upload_csv':
194
- uploaded_file = st.file_uploader("Add dataset (csv) ",type=['csv'])
195
- if uploaded_file is not None:
196
- st.write("File Uploaded")
197
- file_name=uploaded_file.name
198
- ext=file_name.split(".")[0]
199
- st.write(ext)
200
- df=pd.read_csv(uploaded_file)
201
- save_uploadedfile(uploaded_file)
202
- col= df.columns
203
- try:
204
- columns = str((df.columns).tolist())
205
- column = clean(columns)
206
- st.write('Columns:' )
207
- st.text(col)
208
- except:
209
- pass
210
 
211
- temp = st.slider('Temperature: ', 0.0, 1.0, 0.0)
 
 
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
- with st.form(key='columns_in_form2'):
215
- col3, col4 = st.columns(2)
216
- with col3:
217
- userPrompt = st.text_area("Input Prompt",'Enter Natural Language Query')
218
- submitButton = st.form_submit_button(label = 'Submit')
219
- if submitButton:
 
 
 
 
 
 
 
 
 
 
220
  try:
221
- col_p ="Create SQL statement from instruction. "+ext+" " " (" + column +")." +" Request:" + userPrompt + "SQL statement:"
222
- result = gpt3(col_p)
223
- except:
224
- results = gpt3(userPrompt)
225
- st.success('loaded')
226
- with col4:
227
- try:
228
- sqlOutput = st.text_area('SQL Query', value=gpt3(col_p))
229
- warning(sqlOutput)
230
- cars=pd.read_csv('cars.csv')
231
- result_tab2=ps.sqldf(sqlOutput)
232
- st.write(result_tab2)
233
- with open("fewshot_matplot.txt", "r") as file:
234
- text_plot = file.read()
235
-
236
- result_tab = result_tab2.reset_index(drop=True)
237
- result_tab_string = result_tab.to_string()
238
- gr_prompt = text_plot + userPrompt + result_tab_string + "Plot graph for: "
239
-
240
- if len(gr_prompt) > 4097:
241
- st.write('OVERWHELMING DATA!!! You have given me more than 4097 tokens! ^_^')
242
- st.write('As of today, the NLP model text-davinci-003 that I run on takes in inputs that have less than 4097 tokens. Kindly retry ^_^')
243
-
244
- elif len(result_tab2.columns) < 2:
245
- st.write("I need more data to conduct analysis and provide visualizations for you... ^_^")
246
-
247
- else:
248
- st.success("Plotting...")
249
- response_graph = openai.Completion.create(
250
- engine="text-davinci-003",
251
- prompt = gr_prompt,
252
- max_tokens=1024,
253
- n=1,
254
- stop=None,
255
- temperature=0.5,
256
- )
257
 
258
- if response_graph['choices'][0]['text'] != "":
259
- print(response_graph['choices'][0]['text'])
260
- exec(response_graph['choices'][0]['text'])
261
 
 
 
 
262
  else:
263
- print('Retry! Graph could not be plotted *_*')
264
-
265
- except:
266
- pass
267
-
268
- elif res == "Sample_Cars_csv":
269
- df = pd.read_csv('cars.csv')
270
- col= df.columns
271
- try:
272
- columns = str((df.columns).tolist())
273
- column = clean(columns)
274
- st.write('Columns:' )
275
- st.text(col)
276
- except:
277
- pass
 
278
 
279
- temp = st.slider('Temperature: ', 0.0, 1.0, 0.0)
280
-
281
-
282
- with st.form(key='columns_in_form2'):
283
- col3, col4 = st.columns(2)
284
- with col3:
285
- userPrompt = st.text_area("Input Prompt",'Enter Natural Language Query')
286
- submitButton = st.form_submit_button(label = 'Submit')
287
- if submitButton:
288
- try:
289
- col_p ="Create SQL statement from instruction. "+ext+" " " (" + column +")." +" Request:" + userPrompt + "SQL statement:"
290
- result = gpt3(col_p)
291
- except:
292
- results = gpt3(userPrompt)
293
- st.success('loaded')
294
- with col4:
295
  try:
296
- sqlOutput = st.text_area('SQL Query', value=gpt3(col_p))
297
- warning(sqlOutput)
298
- cars=pd.read_csv('cars.csv')
299
- result_tab2=ps.sqldf(sqlOutput)
300
- st.write(result_tab2)
301
- with open("fewshot_matplot.txt", "r") as file:
302
- text_plot = file.read()
303
-
304
- result_tab = result_tab2.reset_index(drop=True)
305
- result_tab_string = result_tab.to_string()
306
- gr_prompt = text_plot + userPrompt + result_tab_string + "Plot graph for: "
307
-
308
- if len(gr_prompt) > 4097:
309
- st.write('OVERWHELMING DATA!!! You have given me more than 4097 tokens! ^_^')
310
- st.write('As of today, the NLP model text-davinci-003 that I run on takes in inputs that have less than 4097 tokens. Kindly retry ^_^')
311
-
312
- elif len(result_tab2.columns) < 2:
313
- st.write("I need more data to conduct analysis and provide visualizations for you... ^_^")
314
-
315
- else:
316
- st.success("Plotting...")
317
- response_graph = openai.Completion.create(
318
- engine="text-davinci-003",
319
- prompt = gr_prompt,
320
- max_tokens=1024,
321
- n=1,
322
- stop=None,
323
- temperature=0.5,
324
- )
325
-
326
- if response_graph['choices'][0]['text'] != "":
327
- print(response_graph['choices'][0]['text'])
328
- exec(response_graph['choices'][0]['text'])
329
-
330
- else:
331
- print('Retry! Graph could not be plotted *_*')
332
-
333
  except:
334
  pass
335
 
336
-
337
- elif Usage == 'Random Questions':
338
- st.text('''You can ask me:
339
- 1. All the things you ask ChatGPT.
340
- 2. Generating paintings, drawings, abstract art.
341
- 3. Music or Videos
342
- 4. Weather
343
- 5. Stocks
344
- 6. Current Affairs and News.
345
- 7. Create or compose tweets or Linkedin posts or email.''')
346
-
347
- Input_type = st.radio(
348
- "**Input type:**",
349
- ('TEXT', 'SPEECH')
350
- )
351
-
352
- if Input_type == 'TEXT':
353
- #page_bg_img2 = """
354
- #<style>
355
- #[data-testid="stAppViewContainer"] {
356
- #background-color: #e5e5f7;
357
- #opacity: 0.8;
358
- #background-size: 20px 20px;
359
- #background-image: repeating-linear-gradient(0deg, #32d947, #32d947 1px, #e5e5f7 1px, #e5e5f7);
360
- #}
361
- #</style>
362
- #"""
363
- #st.markdown(page_bg_img, unsafe_allow_html=True)
364
- st.write('**You are now in Text input mode**')
365
- mytext = st.text_input('**Go on! Ask me anything:**')
366
- if st.button("SUBMIT"):
367
- question=mytext
368
- response = openai.Completion.create(
369
- model="text-davinci-003",
370
- prompt=f'''Your name is alexa and knowledge cutoff date is 2021-09, and it is not aware of any events after that time. if the
371
- Answer to following questions is not from your knowledge base or in case of queries like weather
372
- updates / stock updates / current news Etc which requires you to have internet connection then print i don't have access to internet to answer your question,
373
- if question is related to image or painting or drawing generation then print ipython type output function gen_draw("detailed prompt of image to be generated")
374
- if the question is related to playing a song or video or music of a singer then print ipython type output function vid_tube("relevent search query")
375
- if the question is related to operating home appliances then print ipython type output function home_app(" action(ON/Off),appliance(TV,Geaser,Fridge,Lights,fans,AC)") .
376
- if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")
377
- \nQuestion-{question}
378
- \nAnswer -''',
379
- temperature=0.49,
380
- max_tokens=256,
381
- top_p=1,
382
- frequency_penalty=0,
383
- presence_penalty=0
384
- )
385
- string_temp=response.choices[0].text
386
-
387
- if ("gen_draw" in string_temp):
388
- try:
389
  try:
390
- wget.download(openai_response(prompt))
391
- img2 = Image.open(wget.download(openai_response(prompt)))
392
- img2.show()
393
- rx = 'Image returned'
394
- g_sheet_log(mytext, rx)
395
- except:
396
- urllib.request.urlretrieve(openai_response(prompt),"img_ret.png")
397
- img = Image.open("img_ret.png")
398
- img.show()
399
- rx = 'Image returned'
400
- g_sheet_log(mytext, rx)
401
- except:
402
- # Set up our initial generation parameters.
403
- answers = stability_api.generate(
404
- prompt = mytext,
405
- seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.
406
- # What this means is that as long as all generation parameters remain the same, you can always recall the same image simply by generating it again.
407
- # Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.
408
- steps=30, # Amount of inference steps performed on image generation. Defaults to 30.
409
- cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.
410
- # Setting this value higher increases the strength in which it tries to match your prompt.
411
- # Defaults to 7.0 if not specified.
412
- width=512, # Generation width, defaults to 512 if not included.
413
- height=512, # Generation height, defaults to 512 if not included.
414
- samples=1, # Number of images to generate, defaults to 1 if not included.
415
- sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.
416
- # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.
417
- # (Available Samplers: ddim, plms, k_euler, k_euler_ancestral, k_heun, k_dpm_2, k_dpm_2_ancestral, k_dpmpp_2s_ancestral, k_lms, k_dpmpp_2m)
418
- )
419
-
420
- # Set up our warning to print to the console if the adult content classifier is tripped.
421
- # If adult content classifier is not tripped, save generated images.
422
- for resp in answers:
423
- for artifact in resp.artifacts:
424
- if artifact.finish_reason == generation.FILTER:
425
- warnings.warn(
426
- "Your request activated the API's safety filters and could not be processed."
427
- "Please modify the prompt and try again.")
428
- if artifact.type == generation.ARTIFACT_IMAGE:
429
- img = Image.open(io.BytesIO(artifact.binary))
430
- st.image(img)
431
- img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.
432
- rx = 'Image returned'
433
- g_sheet_log(mytext, rx)
434
-
435
- # except:
436
- # st.write('image is being generated please wait...')
437
- # def extract_image_description(input_string):
438
- # return input_string.split('gen_draw("')[1].split('")')[0]
439
- # prompt=extract_image_description(string_temp)
440
- # # model_id = "CompVis/stable-diffusion-v1-4"
441
- # model_id='runwayml/stable-diffusion-v1-5'
442
- # device = "cuda"
443
-
444
-
445
- # pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
446
- # pipe = pipe.to(device)
447
 
448
- # # prompt = "a photo of an astronaut riding a horse on mars"
449
- # image = pipe(prompt).images[0]
 
 
 
 
 
450
 
451
- # image.save("astronaut_rides_horse.png")
452
- # st.image(image)
453
- # # image
454
 
455
- elif ("vid_tube" in string_temp):
456
- s = Search(mytext)
457
- search_res = s.results
458
- first_vid = search_res[0]
459
- print(first_vid)
460
- string = str(first_vid)
461
- video_id = string[string.index('=') + 1:-1]
462
- # print(video_id)
463
- YoutubeURL = "https://www.youtube.com/watch?v="
464
- OurURL = YoutubeURL + video_id
465
- st.write(OurURL)
466
- st_player(OurURL)
467
- ry = 'Youtube link and video returned'
468
- g_sheet_log(mytext, ry)
 
 
 
469
 
470
- elif ("don't" in string_temp or "internet" in string_temp):
471
- st.write('searching internet ')
472
- search_internet(question)
473
- rz = 'Internet result returned'
474
- g_sheet_log(mytext, rz)
475
 
476
- else:
477
- st.write(string_temp)
478
- g_sheet_log(mytext, string_temp)
 
 
 
 
 
 
479
 
480
- elif Input_type == 'SPEECH':
481
- stt_button = Button(label="Speak", width=100)
482
- stt_button.js_on_event("button_click", CustomJS(code="""
483
- var recognition = new webkitSpeechRecognition();
484
- recognition.continuous = true;
485
- recognition.interimResults = true;
486
- recognition.onresult = function (e) {
487
- var value = "";
488
- for (var i = e.resultIndex; i < e.results.length; ++i) {
489
- if (e.results[i].isFinal) {
490
- value += e.results[i][0].transcript;
491
- }
492
- }
493
- if ( value != "") {
494
- document.dispatchEvent(new CustomEvent("GET_TEXT", {detail: value}));
495
- }
496
- }
497
- recognition.start();
498
- """))
499
 
500
- result = streamlit_bokeh_events(
501
- stt_button,
502
- events="GET_TEXT",
503
- key="listen",
504
- refresh_on_update=False,
505
- override_height=75,
506
- debounce_time=0)
507
-
508
- if result:
509
- if "GET_TEXT" in result:
510
- st.write(result.get("GET_TEXT"))
511
- question = result.get("GET_TEXT")
 
 
 
 
512
  response = openai.Completion.create(
513
- model="text-davinci-003",
514
- prompt=f'''Your knowledge cutoff is 2021-09, and it is not aware of any events after that time. if the
515
- Answer to following questions is not from your knowledge base or in case of queries like weather
516
- updates / stock updates / current news Etc which requires you to have internet connection then print i don't have access to internet to answer your question,
517
- if question is related to image or painting or drawing generation then print ipython type output function gen_draw("detailed prompt of image to be generated")
518
- if the question is related to playing a song or video or music of a singer then print ipython type output function vid_tube("relevent search query")
519
- \nQuestion-{question}
520
- \nAnswer -''',
521
- temperature=0.49,
522
- max_tokens=256,
523
- top_p=1,
524
- frequency_penalty=0,
525
- presence_penalty=0
 
 
526
  )
527
  string_temp=response.choices[0].text
528
-
529
  if ("gen_draw" in string_temp):
530
- st.write('*image is being generated please wait..* ')
531
- def extract_image_description(input_string):
532
- return input_string.split('gen_draw("')[1].split('")')[0]
533
- prompt=extract_image_description(string_temp)
534
- # model_id = "CompVis/stable-diffusion-v1-4"
535
- model_id='runwayml/stable-diffusion-v1-5'
536
- device = "cuda"
537
-
538
- pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
539
- pipe = pipe.to(device)
540
-
541
- # prompt = "a photo of an astronaut riding a horse on mars"
542
- image = pipe(prompt).images[0]
543
-
544
- image.save("astronaut_rides_horse.png")
545
- st.image(image)
546
- # image
547
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
  elif ("vid_tube" in string_temp):
549
- s = Search(question)
550
  search_res = s.results
551
  first_vid = search_res[0]
552
  print(first_vid)
@@ -557,9 +467,102 @@ elif Usage == 'Random Questions':
557
  OurURL = YoutubeURL + video_id
558
  st.write(OurURL)
559
  st_player(OurURL)
560
-
561
- elif ("don't" in string_temp or "internet" in string_temp ):
562
- st.write('*searching internet*')
 
 
563
  search_internet(question)
 
 
 
564
  else:
565
  st.write(string_temp)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  #}
173
  #</style>
174
  #"""
175
+ col1, col2 = st.columns(2)
176
+ with col1:
177
+ st.image('https://ibb.co/rGSj8pB')
178
+ with col2:
179
+ #st.markdown(page_bg_img, unsafe_allow_html=True)
180
+ st.title("Ask :red[Mukesh] anything!!🤖")
181
+ st.title("Puchne mai kya jaata hai??")
 
 
 
 
 
 
 
 
182
 
183
+ option_ = ['Random Questions','Questions based on custom CSV data']
184
+ Usage = st.selectbox('Select an option:', option_)
185
+ if Usage == 'Questions based on custom CSV data':
186
+ st.text('''
187
+ You can use your own custom csv files to test this feature or
188
+ you can use the sample csv file which contains data about cars.
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
+ Example question:
191
+ - How many cars were manufactured each year between 2000 to 2008?
192
+ ''')
193
 
194
+ option = ['Sample_Cars_csv','Upload_csv']
195
+ res = st.selectbox('Select from below options:',option)
196
+ if res == 'Upload_csv':
197
+ uploaded_file = st.file_uploader("Add dataset (csv) ",type=['csv'])
198
+ if uploaded_file is not None:
199
+ st.write("File Uploaded")
200
+ file_name=uploaded_file.name
201
+ ext=file_name.split(".")[0]
202
+ st.write(ext)
203
+ df=pd.read_csv(uploaded_file)
204
+ save_uploadedfile(uploaded_file)
205
+ col= df.columns
206
+ try:
207
+ columns = str((df.columns).tolist())
208
+ column = clean(columns)
209
+ st.write('Columns:' )
210
+ st.text(col)
211
+ except:
212
+ pass
213
 
214
+ temp = st.slider('Temperature: ', 0.0, 1.0, 0.0)
215
+
216
+
217
+ with st.form(key='columns_in_form2'):
218
+ col3, col4 = st.columns(2)
219
+ with col3:
220
+ userPrompt = st.text_area("Input Prompt",'Enter Natural Language Query')
221
+ submitButton = st.form_submit_button(label = 'Submit')
222
+ if submitButton:
223
+ try:
224
+ col_p ="Create SQL statement from instruction. "+ext+" " " (" + column +")." +" Request:" + userPrompt + "SQL statement:"
225
+ result = gpt3(col_p)
226
+ except:
227
+ results = gpt3(userPrompt)
228
+ st.success('loaded')
229
+ with col4:
230
  try:
231
+ sqlOutput = st.text_area('SQL Query', value=gpt3(col_p))
232
+ warning(sqlOutput)
233
+ cars=pd.read_csv('cars.csv')
234
+ result_tab2=ps.sqldf(sqlOutput)
235
+ st.write(result_tab2)
236
+ with open("fewshot_matplot.txt", "r") as file:
237
+ text_plot = file.read()
238
+
239
+ result_tab = result_tab2.reset_index(drop=True)
240
+ result_tab_string = result_tab.to_string()
241
+ gr_prompt = text_plot + userPrompt + result_tab_string + "Plot graph for: "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
+ if len(gr_prompt) > 4097:
244
+ st.write('OVERWHELMING DATA!!! You have given me more than 4097 tokens! ^_^')
245
+ st.write('As of today, the NLP model text-davinci-003 that I run on takes in inputs that have less than 4097 tokens. Kindly retry ^_^')
246
 
247
+ elif len(result_tab2.columns) < 2:
248
+ st.write("I need more data to conduct analysis and provide visualizations for you... ^_^")
249
+
250
  else:
251
+ st.success("Plotting...")
252
+ response_graph = openai.Completion.create(
253
+ engine="text-davinci-003",
254
+ prompt = gr_prompt,
255
+ max_tokens=1024,
256
+ n=1,
257
+ stop=None,
258
+ temperature=0.5,
259
+ )
260
+
261
+ if response_graph['choices'][0]['text'] != "":
262
+ print(response_graph['choices'][0]['text'])
263
+ exec(response_graph['choices'][0]['text'])
264
+
265
+ else:
266
+ print('Retry! Graph could not be plotted *_*')
267
 
268
+ except:
269
+ pass
270
+
271
+ elif res == "Sample_Cars_csv":
272
+ df = pd.read_csv('cars.csv')
273
+ col= df.columns
 
 
 
 
 
 
 
 
 
 
274
  try:
275
+ columns = str((df.columns).tolist())
276
+ column = clean(columns)
277
+ st.write('Columns:' )
278
+ st.text(col)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  except:
280
  pass
281
 
282
+ temp = st.slider('Temperature: ', 0.0, 1.0, 0.0)
283
+
284
+
285
+ with st.form(key='columns_in_form2'):
286
+ col3, col4 = st.columns(2)
287
+ with col3:
288
+ userPrompt = st.text_area("Input Prompt",'Enter Natural Language Query')
289
+ submitButton = st.form_submit_button(label = 'Submit')
290
+ if submitButton:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  try:
292
+ col_p ="Create SQL statement from instruction. "+ext+" " " (" + column +")." +" Request:" + userPrompt + "SQL statement:"
293
+ result = gpt3(col_p)
294
+ except:
295
+ results = gpt3(userPrompt)
296
+ st.success('loaded')
297
+ with col4:
298
+ try:
299
+ sqlOutput = st.text_area('SQL Query', value=gpt3(col_p))
300
+ warning(sqlOutput)
301
+ cars=pd.read_csv('cars.csv')
302
+ result_tab2=ps.sqldf(sqlOutput)
303
+ st.write(result_tab2)
304
+ with open("fewshot_matplot.txt", "r") as file:
305
+ text_plot = file.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
+ result_tab = result_tab2.reset_index(drop=True)
308
+ result_tab_string = result_tab.to_string()
309
+ gr_prompt = text_plot + userPrompt + result_tab_string + "Plot graph for: "
310
+
311
+ if len(gr_prompt) > 4097:
312
+ st.write('OVERWHELMING DATA!!! You have given me more than 4097 tokens! ^_^')
313
+ st.write('As of today, the NLP model text-davinci-003 that I run on takes in inputs that have less than 4097 tokens. Kindly retry ^_^')
314
 
315
+ elif len(result_tab2.columns) < 2:
316
+ st.write("I need more data to conduct analysis and provide visualizations for you... ^_^")
 
317
 
318
+ else:
319
+ st.success("Plotting...")
320
+ response_graph = openai.Completion.create(
321
+ engine="text-davinci-003",
322
+ prompt = gr_prompt,
323
+ max_tokens=1024,
324
+ n=1,
325
+ stop=None,
326
+ temperature=0.5,
327
+ )
328
+
329
+ if response_graph['choices'][0]['text'] != "":
330
+ print(response_graph['choices'][0]['text'])
331
+ exec(response_graph['choices'][0]['text'])
332
+
333
+ else:
334
+ print('Retry! Graph could not be plotted *_*')
335
 
336
+ except:
337
+ pass
338
+
 
 
339
 
340
+ elif Usage == 'Random Questions':
341
+ st.text('''You can ask me:
342
+ 1. All the things you ask ChatGPT.
343
+ 2. Generating paintings, drawings, abstract art.
344
+ 3. Music or Videos
345
+ 4. Weather
346
+ 5. Stocks
347
+ 6. Current Affairs and News.
348
+ 7. Create or compose tweets or Linkedin posts or email.''')
349
 
350
+ Input_type = st.radio(
351
+ "**Input type:**",
352
+ ('TEXT', 'SPEECH')
353
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
+ if Input_type == 'TEXT':
356
+ #page_bg_img2 = """
357
+ #<style>
358
+ #[data-testid="stAppViewContainer"] {
359
+ #background-color: #e5e5f7;
360
+ #opacity: 0.8;
361
+ #background-size: 20px 20px;
362
+ #background-image: repeating-linear-gradient(0deg, #32d947, #32d947 1px, #e5e5f7 1px, #e5e5f7);
363
+ #}
364
+ #</style>
365
+ #"""
366
+ #st.markdown(page_bg_img, unsafe_allow_html=True)
367
+ st.write('**You are now in Text input mode**')
368
+ mytext = st.text_input('**Go on! Ask me anything:**')
369
+ if st.button("SUBMIT"):
370
+ question=mytext
371
  response = openai.Completion.create(
372
+ model="text-davinci-003",
373
+ prompt=f'''Your name is alexa and knowledge cutoff date is 2021-09, and it is not aware of any events after that time. if the
374
+ Answer to following questions is not from your knowledge base or in case of queries like weather
375
+ updates / stock updates / current news Etc which requires you to have internet connection then print i don't have access to internet to answer your question,
376
+ if question is related to image or painting or drawing generation then print ipython type output function gen_draw("detailed prompt of image to be generated")
377
+ if the question is related to playing a song or video or music of a singer then print ipython type output function vid_tube("relevent search query")
378
+ if the question is related to operating home appliances then print ipython type output function home_app(" action(ON/Off),appliance(TV,Geaser,Fridge,Lights,fans,AC)") .
379
+ if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")
380
+ \nQuestion-{question}
381
+ \nAnswer -''',
382
+ temperature=0.49,
383
+ max_tokens=256,
384
+ top_p=1,
385
+ frequency_penalty=0,
386
+ presence_penalty=0
387
  )
388
  string_temp=response.choices[0].text
389
+
390
  if ("gen_draw" in string_temp):
391
+ try:
392
+ try:
393
+ wget.download(openai_response(prompt))
394
+ img2 = Image.open(wget.download(openai_response(prompt)))
395
+ img2.show()
396
+ rx = 'Image returned'
397
+ g_sheet_log(mytext, rx)
398
+ except:
399
+ urllib.request.urlretrieve(openai_response(prompt),"img_ret.png")
400
+ img = Image.open("img_ret.png")
401
+ img.show()
402
+ rx = 'Image returned'
403
+ g_sheet_log(mytext, rx)
404
+ except:
405
+ # Set up our initial generation parameters.
406
+ answers = stability_api.generate(
407
+ prompt = mytext,
408
+ seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.
409
+ # What this means is that as long as all generation parameters remain the same, you can always recall the same image simply by generating it again.
410
+ # Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.
411
+ steps=30, # Amount of inference steps performed on image generation. Defaults to 30.
412
+ cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.
413
+ # Setting this value higher increases the strength in which it tries to match your prompt.
414
+ # Defaults to 7.0 if not specified.
415
+ width=512, # Generation width, defaults to 512 if not included.
416
+ height=512, # Generation height, defaults to 512 if not included.
417
+ samples=1, # Number of images to generate, defaults to 1 if not included.
418
+ sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.
419
+ # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.
420
+ # (Available Samplers: ddim, plms, k_euler, k_euler_ancestral, k_heun, k_dpm_2, k_dpm_2_ancestral, k_dpmpp_2s_ancestral, k_lms, k_dpmpp_2m)
421
+ )
422
+
423
+ # Set up our warning to print to the console if the adult content classifier is tripped.
424
+ # If adult content classifier is not tripped, save generated images.
425
+ for resp in answers:
426
+ for artifact in resp.artifacts:
427
+ if artifact.finish_reason == generation.FILTER:
428
+ warnings.warn(
429
+ "Your request activated the API's safety filters and could not be processed."
430
+ "Please modify the prompt and try again.")
431
+ if artifact.type == generation.ARTIFACT_IMAGE:
432
+ img = Image.open(io.BytesIO(artifact.binary))
433
+ st.image(img)
434
+ img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.
435
+ rx = 'Image returned'
436
+ g_sheet_log(mytext, rx)
437
+
438
+ # except:
439
+ # st.write('image is being generated please wait...')
440
+ # def extract_image_description(input_string):
441
+ # return input_string.split('gen_draw("')[1].split('")')[0]
442
+ # prompt=extract_image_description(string_temp)
443
+ # # model_id = "CompVis/stable-diffusion-v1-4"
444
+ # model_id='runwayml/stable-diffusion-v1-5'
445
+ # device = "cuda"
446
+
447
+
448
+ # pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
449
+ # pipe = pipe.to(device)
450
+
451
+ # # prompt = "a photo of an astronaut riding a horse on mars"
452
+ # image = pipe(prompt).images[0]
453
+
454
+ # image.save("astronaut_rides_horse.png")
455
+ # st.image(image)
456
+ # # image
457
+
458
  elif ("vid_tube" in string_temp):
459
+ s = Search(mytext)
460
  search_res = s.results
461
  first_vid = search_res[0]
462
  print(first_vid)
 
467
  OurURL = YoutubeURL + video_id
468
  st.write(OurURL)
469
  st_player(OurURL)
470
+ ry = 'Youtube link and video returned'
471
+ g_sheet_log(mytext, ry)
472
+
473
+ elif ("don't" in string_temp or "internet" in string_temp):
474
+ st.write('searching internet ')
475
  search_internet(question)
476
+ rz = 'Internet result returned'
477
+ g_sheet_log(mytext, rz)
478
+
479
  else:
480
  st.write(string_temp)
481
+ g_sheet_log(mytext, string_temp)
482
+
483
+ elif Input_type == 'SPEECH':
484
+ stt_button = Button(label="Speak", width=100)
485
+ stt_button.js_on_event("button_click", CustomJS(code="""
486
+ var recognition = new webkitSpeechRecognition();
487
+ recognition.continuous = true;
488
+ recognition.interimResults = true;
489
+ recognition.onresult = function (e) {
490
+ var value = "";
491
+ for (var i = e.resultIndex; i < e.results.length; ++i) {
492
+ if (e.results[i].isFinal) {
493
+ value += e.results[i][0].transcript;
494
+ }
495
+ }
496
+ if ( value != "") {
497
+ document.dispatchEvent(new CustomEvent("GET_TEXT", {detail: value}));
498
+ }
499
+ }
500
+ recognition.start();
501
+ """))
502
+
503
+ result = streamlit_bokeh_events(
504
+ stt_button,
505
+ events="GET_TEXT",
506
+ key="listen",
507
+ refresh_on_update=False,
508
+ override_height=75,
509
+ debounce_time=0)
510
+
511
+ if result:
512
+ if "GET_TEXT" in result:
513
+ st.write(result.get("GET_TEXT"))
514
+ question = result.get("GET_TEXT")
515
+ response = openai.Completion.create(
516
+ model="text-davinci-003",
517
+ prompt=f'''Your knowledge cutoff is 2021-09, and it is not aware of any events after that time. if the
518
+ Answer to following questions is not from your knowledge base or in case of queries like weather
519
+ updates / stock updates / current news Etc which requires you to have internet connection then print i don't have access to internet to answer your question,
520
+ if question is related to image or painting or drawing generation then print ipython type output function gen_draw("detailed prompt of image to be generated")
521
+ if the question is related to playing a song or video or music of a singer then print ipython type output function vid_tube("relevent search query")
522
+ \nQuestion-{question}
523
+ \nAnswer -''',
524
+ temperature=0.49,
525
+ max_tokens=256,
526
+ top_p=1,
527
+ frequency_penalty=0,
528
+ presence_penalty=0
529
+ )
530
+ string_temp=response.choices[0].text
531
+
532
+ if ("gen_draw" in string_temp):
533
+ st.write('*image is being generated please wait..* ')
534
+ def extract_image_description(input_string):
535
+ return input_string.split('gen_draw("')[1].split('")')[0]
536
+ prompt=extract_image_description(string_temp)
537
+ # model_id = "CompVis/stable-diffusion-v1-4"
538
+ model_id='runwayml/stable-diffusion-v1-5'
539
+ device = "cuda"
540
+
541
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
542
+ pipe = pipe.to(device)
543
+
544
+ # prompt = "a photo of an astronaut riding a horse on mars"
545
+ image = pipe(prompt).images[0]
546
+
547
+ image.save("astronaut_rides_horse.png")
548
+ st.image(image)
549
+ # image
550
+
551
+ elif ("vid_tube" in string_temp):
552
+ s = Search(question)
553
+ search_res = s.results
554
+ first_vid = search_res[0]
555
+ print(first_vid)
556
+ string = str(first_vid)
557
+ video_id = string[string.index('=') + 1:-1]
558
+ # print(video_id)
559
+ YoutubeURL = "https://www.youtube.com/watch?v="
560
+ OurURL = YoutubeURL + video_id
561
+ st.write(OurURL)
562
+ st_player(OurURL)
563
+
564
+ elif ("don't" in string_temp or "internet" in string_temp ):
565
+ st.write('*searching internet*')
566
+ search_internet(question)
567
+ else:
568
+ st.write(string_temp)