CobaltZvc commited on
Commit
b14bec4
1 Parent(s): a0bef4f

Update app.py

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