CobaltZvc/HyperBot
27
1import os2import openai3import wget4import streamlit as st5from PIL import Image6from serpapi import GoogleSearch7import torch8from diffusers import StableDiffusionPipeline9from bokeh.models.widgets import Button10from bokeh.models.widgets.buttons import Button11from bokeh.models import CustomJS12from streamlit_bokeh_events import streamlit_bokeh_events13import base6414from streamlit_player import st_player15from pytube import YouTube16from pytube import Search17import io18import warnings19from PIL import Image20from stability_sdk import client21import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation22import datetime23from google.oauth2 import service_account24from googleapiclient.discovery import build25import wget26import urllib.request27import csv28 29 30def save_uploadedfile(uploadedfile):31 with open(uploadedfile.name,"wb") as f:32 f.write(uploadedfile.getbuffer())33 34stability_api = client.StabilityInference(35 key=st.secrets["STABILITY_KEY"], #os.environ("STABILITY_KEY"), # key=os.environ['STABILITY_KEY'], # API Key reference.36 verbose=True, # Print debug messages.37 engine="stable-diffusion-v1-5", # Set the engine to use for generation.38 # Available engines: stable-diffusion-v1 stable-diffusion-v1-5 stable-diffusion-512-v2-0 stable-diffusion-768-v2-039 # stable-diffusion-512-v2-1 stable-diffusion-768-v2-1 stable-inpainting-v1-0 stable-inpainting-512-v2-040)41 42header = ["sl. no.", "Input Prompt", "Output", "Date_time"]43 44def csv_logs(mytext, result, date_time):45 with open("logs.csv", "r") as file:46 sl_no = sum(1 for _ in csv.reader(file))47 48 with open("logs.csv", "a", newline="") as file:49 writer = csv.writer(file)50 writer.writerow([sl_no, mytext, result, date_time])51 52def search_internet(question):53 try: 54 params = {55 "q": question,56 "location": "Bengaluru, Karnataka, India",57 "hl": "hi",58 "gl": "in",59 "google_domain": "google.co.in",60 # "api_key": ""61 "api_key": st.secrets["GOOGLE_API"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']62 }63 64 params = {65 "q": question,66 "location": "Bengaluru, Karnataka, India",67 "hl": "hi",68 "gl": "in",69 "google_domain": "google.co.in",70 # "api_key": ""71 "api_key": st.secrets["GOOGLE_API"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']72 }73 74 search = GoogleSearch(params)75 results = search.get_dict()76 organic_results = results["organic_results"]77 st.text("Key 0 used")78 79 80 snippets = ""81 counter = 182 for item in organic_results:83 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'84 counter += 185 86 # snippets87 88 response = openai.Completion.create(89 model="text-davinci-003",90 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',91 temperature=0.49,92 max_tokens=256,93 top_p=1,94 frequency_penalty=0,95 presence_penalty=0)96 97 now = datetime.datetime.now()98 date_time = now.strftime("%Y-%m-%d %H:%M:%S")99 string_temp = response.choices[0].text100 csv_logs(question, string_temp, date_time)101 st.write(string_temp)102 st.write(snippets)103 except:104 try:105 106 params = {107 "q": question,108 "location": "Bengaluru, Karnataka, India",109 "hl": "hi",110 "gl": "in",111 "google_domain": "google.co.in",112 # "api_key": ""113 "api_key": st.secrets["GOOGLE_API1"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']114 }115 116 params = {117 "q": question,118 "location": "Bengaluru, Karnataka, India",119 "hl": "hi",120 "gl": "in",121 "google_domain": "google.co.in",122 # "api_key": ""123 "api_key": st.secrets["GOOGLE_API1"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']124 }125 126 search = GoogleSearch(params)127 results = search.get_dict()128 organic_results = results["organic_results"]129 st.text("Key 1 used")130 131 132 snippets = ""133 counter = 1134 for item in organic_results:135 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'136 counter += 1137 138 # snippets139 140 response = openai.Completion.create(141 model="text-davinci-003",142 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',143 temperature=0.49,144 max_tokens=256,145 top_p=1,146 frequency_penalty=0,147 presence_penalty=0)148 149 now = datetime.datetime.now()150 date_time = now.strftime("%Y-%m-%d %H:%M:%S")151 string_temp = response.choices[0].text152 csv_logs(question, string_temp, date_time)153 st.write(string_temp)154 st.write(snippets)155 except:156 try:157 158 params = {159 "q": question,160 "location": "Bengaluru, Karnataka, India",161 "hl": "hi",162 "gl": "in",163 "google_domain": "google.co.in",164 # "api_key": ""165 "api_key": st.secrets["GOOGLE_API2"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']166 }167 168 params = {169 "q": question,170 "location": "Bengaluru, Karnataka, India",171 "hl": "hi",172 "gl": "in",173 "google_domain": "google.co.in",174 # "api_key": ""175 "api_key": st.secrets["GOOGLE_API2"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']176 }177 178 search = GoogleSearch(params)179 results = search.get_dict()180 organic_results = results["organic_results"]181 st.text("Key 2 used")182 183 184 snippets = ""185 counter = 1186 for item in organic_results:187 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'188 counter += 1189 190 # snippets191 192 response = openai.Completion.create(193 model="text-davinci-003",194 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',195 temperature=0.49,196 max_tokens=256,197 top_p=1,198 frequency_penalty=0,199 presence_penalty=0)200 201 now = datetime.datetime.now()202 date_time = now.strftime("%Y-%m-%d %H:%M:%S")203 string_temp = response.choices[0].text204 csv_logs(question, string_temp, date_time)205 st.write(string_temp)206 st.write(snippets)207 except:208 try:209 210 params = {211 "q": question,212 "location": "Bengaluru, Karnataka, India",213 "hl": "hi",214 "gl": "in",215 "google_domain": "google.co.in",216 # "api_key": ""217 "api_key": st.secrets["GOOGLE_API3"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']218 }219 220 params = {221 "q": question,222 "location": "Bengaluru, Karnataka, India",223 "hl": "hi",224 "gl": "in",225 "google_domain": "google.co.in",226 # "api_key": ""227 "api_key": st.secrets["GOOGLE_API3"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']228 }229 230 search = GoogleSearch(params)231 results = search.get_dict()232 organic_results = results["organic_results"]233 st.text("Key 3 used")234 235 236 snippets = ""237 counter = 1238 for item in organic_results:239 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'240 counter += 1241 242 # snippets243 244 response = openai.Completion.create(245 model="text-davinci-003",246 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',247 temperature=0.49,248 max_tokens=256,249 top_p=1,250 frequency_penalty=0,251 presence_penalty=0)252 253 now = datetime.datetime.now()254 date_time = now.strftime("%Y-%m-%d %H:%M:%S")255 string_temp = response.choices[0].text256 csv_logs(question, string_temp, date_time)257 st.write(string_temp)258 st.write(snippets)259 except:260 try:261 262 params = {263 "q": question,264 "location": "Bengaluru, Karnataka, India",265 "hl": "hi",266 "gl": "in",267 "google_domain": "google.co.in",268 # "api_key": ""269 "api_key": st.secrets["GOOGLE_API4"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']270 }271 272 params = {273 "q": question,274 "location": "Bengaluru, Karnataka, India",275 "hl": "hi",276 "gl": "in",277 "google_domain": "google.co.in",278 # "api_key": ""279 "api_key": st.secrets["GOOGLE_API4"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']280 }281 282 search = GoogleSearch(params)283 results = search.get_dict()284 organic_results = results["organic_results"]285 st.text("Key 4 used")286 287 288 snippets = ""289 counter = 1290 for item in organic_results:291 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'292 counter += 1293 294 # snippets295 296 response = openai.Completion.create(297 model="text-davinci-003",298 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',299 temperature=0.49,300 max_tokens=256,301 top_p=1,302 frequency_penalty=0,303 presence_penalty=0)304 305 now = datetime.datetime.now()306 date_time = now.strftime("%Y-%m-%d %H:%M:%S")307 string_temp = response.choices[0].text308 csv_logs(question, string_temp, date_time)309 st.write(string_temp)310 st.write(snippets)311 except:312 try:313 314 params = {315 "q": question,316 "location": "Bengaluru, Karnataka, India",317 "hl": "hi",318 "gl": "in",319 "google_domain": "google.co.in",320 # "api_key": ""321 "api_key": st.secrets["GOOGLE_API5"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']322 }323 324 params = {325 "q": question,326 "location": "Bengaluru, Karnataka, India",327 "hl": "hi",328 "gl": "in",329 "google_domain": "google.co.in",330 # "api_key": ""331 "api_key": st.secrets["GOOGLE_API5"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']332 }333 334 search = GoogleSearch(params)335 results = search.get_dict()336 organic_results = results["organic_results"]337 st.text("Key 5 used")338 339 340 snippets = ""341 counter = 1342 for item in organic_results:343 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'344 counter += 1345 346 # snippets347 348 response = openai.Completion.create(349 model="text-davinci-003",350 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',351 temperature=0.49,352 max_tokens=256,353 top_p=1,354 frequency_penalty=0,355 presence_penalty=0)356 357 now = datetime.datetime.now()358 date_time = now.strftime("%Y-%m-%d %H:%M:%S")359 string_temp = response.choices[0].text360 csv_logs(question, string_temp, date_time)361 st.write(string_temp)362 st.write(snippets)363 except:364 try:365 366 params = {367 "q": question,368 "location": "Bengaluru, Karnataka, India",369 "hl": "hi",370 "gl": "in",371 "google_domain": "google.co.in",372 # "api_key": ""373 "api_key": st.secrets["GOOGLE_API6"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']374 }375 376 params = {377 "q": question,378 "location": "Bengaluru, Karnataka, India",379 "hl": "hi",380 "gl": "in",381 "google_domain": "google.co.in",382 # "api_key": ""383 "api_key": st.secrets["GOOGLE_API6"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']384 }385 386 search = GoogleSearch(params)387 results = search.get_dict()388 organic_results = results["organic_results"]389 st.text("Key 6 used")390 391 392 snippets = ""393 counter = 1394 for item in organic_results:395 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'396 counter += 1397 398 # snippets399 400 response = openai.Completion.create(401 model="text-davinci-003",402 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',403 temperature=0.49,404 max_tokens=256,405 top_p=1,406 frequency_penalty=0,407 presence_penalty=0)408 409 now = datetime.datetime.now()410 date_time = now.strftime("%Y-%m-%d %H:%M:%S")411 string_temp = response.choices[0].text412 csv_logs(question, string_temp, date_time)413 st.write(string_temp)414 st.write(snippets)415 except:416 try:417 418 params = {419 "q": question,420 "location": "Bengaluru, Karnataka, India",421 "hl": "hi",422 "gl": "in",423 "google_domain": "google.co.in",424 # "api_key": ""425 "api_key": st.secrets["GOOGLE_API7"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']426 }427 428 params = {429 "q": question,430 "location": "Bengaluru, Karnataka, India",431 "hl": "hi",432 "gl": "in",433 "google_domain": "google.co.in",434 # "api_key": ""435 "api_key": st.secrets["GOOGLE_API7"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']436 }437 438 search = GoogleSearch(params)439 results = search.get_dict()440 organic_results = results["organic_results"]441 st.text("Key 7 used")442 443 444 snippets = ""445 counter = 1446 for item in organic_results:447 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'448 counter += 1449 450 # snippets451 452 response = openai.Completion.create(453 model="text-davinci-003",454 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',455 temperature=0.49,456 max_tokens=256,457 top_p=1,458 frequency_penalty=0,459 presence_penalty=0)460 461 now = datetime.datetime.now()462 date_time = now.strftime("%Y-%m-%d %H:%M:%S")463 string_temp = response.choices[0].text464 csv_logs(question, string_temp, date_time)465 st.write(string_temp)466 st.write(snippets)467 except:468 try:469 470 params = {471 "q": question,472 "location": "Bengaluru, Karnataka, India",473 "hl": "hi",474 "gl": "in",475 "google_domain": "google.co.in",476 # "api_key": ""477 "api_key": st.secrets["GOOGLE_API8"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']478 }479 480 params = {481 "q": question,482 "location": "Bengaluru, Karnataka, India",483 "hl": "hi",484 "gl": "in",485 "google_domain": "google.co.in",486 # "api_key": ""487 "api_key": st.secrets["GOOGLE_API8"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']488 }489 490 search = GoogleSearch(params)491 results = search.get_dict()492 organic_results = results["organic_results"]493 st.text("Key 8 used")494 495 496 snippets = ""497 counter = 1498 for item in organic_results:499 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'500 counter += 1501 502 # snippets503 504 response = openai.Completion.create(505 model="text-davinci-003",506 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',507 temperature=0.49,508 max_tokens=256,509 top_p=1,510 frequency_penalty=0,511 presence_penalty=0)512 513 now = datetime.datetime.now()514 date_time = now.strftime("%Y-%m-%d %H:%M:%S")515 string_temp = response.choices[0].text516 csv_logs(question, string_temp, date_time)517 st.write(string_temp)518 st.write(snippets)519 except:520 try:521 522 params = {523 "q": question,524 "location": "Bengaluru, Karnataka, India",525 "hl": "hi",526 "gl": "in",527 "google_domain": "google.co.in",528 # "api_key": ""529 "api_key": st.secrets["GOOGLE_API9"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']530 }531 532 params = {533 "q": question,534 "location": "Bengaluru, Karnataka, India",535 "hl": "hi",536 "gl": "in",537 "google_domain": "google.co.in",538 # "api_key": ""539 "api_key": st.secrets["GOOGLE_API9"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']540 }541 542 search = GoogleSearch(params)543 results = search.get_dict()544 organic_results = results["organic_results"]545 st.text("Key 9 used")546 547 548 snippets = ""549 counter = 1550 for item in organic_results:551 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'552 counter += 1553 554 # snippets555 556 response = openai.Completion.create(557 model="text-davinci-003",558 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',559 temperature=0.49,560 max_tokens=256,561 top_p=1,562 frequency_penalty=0,563 presence_penalty=0)564 565 now = datetime.datetime.now()566 date_time = now.strftime("%Y-%m-%d %H:%M:%S")567 string_temp = response.choices[0].text568 csv_logs(question, string_temp, date_time)569 st.write(string_temp)570 st.write(snippets)571 except:572 try:573 574 params = {575 "q": question,576 "location": "Bengaluru, Karnataka, India",577 "hl": "hi",578 "gl": "in",579 "google_domain": "google.co.in",580 # "api_key": ""581 "api_key": st.secrets["GOOGLE_API10"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']582 }583 584 params = {585 "q": question,586 "location": "Bengaluru, Karnataka, India",587 "hl": "hi",588 "gl": "in",589 "google_domain": "google.co.in",590 # "api_key": ""591 "api_key": st.secrets["GOOGLE_API10"] #os.environ("GOOGLE_API") #os.environ['GOOGLE_API']592 }593 594 search = GoogleSearch(params)595 results = search.get_dict()596 organic_results = results["organic_results"]597 st.text("Key 10 used")598 599 600 snippets = ""601 counter = 1602 for item in organic_results:603 snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'604 counter += 1605 606 # snippets607 608 response = openai.Completion.create(609 model="text-davinci-003",610 prompt=f'''following are snippets from google search with these as knowledge base only answer questions and print reference link as well followed by answer. \n\n {snippets}\n\n question-{question}\n\nAnswer-''',611 temperature=0.49,612 max_tokens=256,613 top_p=1,614 frequency_penalty=0,615 presence_penalty=0)616 617 now = datetime.datetime.now()618 date_time = now.strftime("%Y-%m-%d %H:%M:%S")619 string_temp = response.choices[0].text620 csv_logs(question, string_temp, date_time)621 st.write(string_temp)622 st.write(snippets)623 except:624 pass625 626 627 628openai.api_key = st.secrets["OPENAI_KEY"] #os.environ("OPENAI_KEY") #os.environ['OPENAI_KEY']629# date_time = str(datetime.now())630 631openai.api_key = st.secrets["OPENAI_KEY"]632 633def openai_response(PROMPT):634 response = openai.Image.create(635 prompt=PROMPT,636 n=1,637 size="256x256",638)639 return response["data"][0]["url"]640 641st.title("Hi! :red[HyperBot] here!!🤖⭐️")642st.title("Go on ask me anything!!")643 644st.write('''645⭐️ *HyperBot is your virtual assistant powered by Whisper / 646chatgpt / internet / Dall-E / OpenAI embeddings - the perfect 647companion for you. With HyperBot, you can ask anything you ask 648internet everyday . Get answers to questions about the weather, 649stocks 📈, news📰, and more! Plus, you can also generate 🖌️ 650paintings, drawings, abstract art 🎨, play music 🎵 or videos, 651create tweets 🐦 and posts 📝, and compose emails 📧 - all with 652the help of HyperBot!* 🤖 ✨653''')654 655st.text('''You can ask me: 6561. All the things you ask ChatGPT.6572. To generate paintings, drawings, abstract art. 6583. Music or Videos6594. Weather 6605. Stocks 6616. Current Affairs and News.6627. Create or compose tweets or Linkedin posts or email.''')663 664Input_type = st.radio(665 "**Input type:**",666 ('TEXT', 'SPEECH')667 )668 669if Input_type == 'TEXT':670 mytext = st.text_input('**Go on! Ask me anything:**')671 if st.button("SUBMIT"):672 question=mytext673 response = openai.Completion.create(674 model="text-davinci-003",675 prompt=f'''Your name is HyperBot and knowledge cutoff date is 2021-09, and you are not aware of any events after that time. if the 676 Answer to following questions is not from your knowledge base or in case of queries like date, time, weather 677 updates / stock updates / current affairs / news or people which requires you to have internet connection then print i don't have access to internet to answer your question, 678 if question is related to image or painting or drawing or diagram generation then print ipython type output function gen_draw("detailed prompt of image to be generated")679 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")680 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)") . 681 if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")682 \nQuestion-{question}683 \nAnswer -''',684 temperature=0.49,685 max_tokens=256,686 top_p=1,687 frequency_penalty=0,688 presence_penalty=0689 )690 string_temp=response.choices[0].text691 692 if ("gen_draw" in string_temp):693 try:694 try:695 wget.download(openai_response(prompt))696 img2 = Image.open(wget.download(openai_response(prompt)))697 img2.show()698 rx = 'Image returned'699 now = datetime.datetime.now()700 date_time = now.strftime("%Y-%m-%d %H:%M:%S")701 csv_logs(mytext, rx, date_time)702 except:703 urllib.request.urlretrieve(openai_response(prompt),"img_ret.png")704 img = Image.open("img_ret.png")705 img.show()706 rx = 'Image returned'707 now = datetime.datetime.now()708 date_time = now.strftime("%Y-%m-%d %H:%M:%S")709 csv_logs(mytext, rx, date_time)710 except:711 # Set up our initial generation parameters.712 answers = stability_api.generate(713 prompt = mytext,714 seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.715 # 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.716 # Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.717 steps=30, # Amount of inference steps performed on image generation. Defaults to 30.718 cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.719 # Setting this value higher increases the strength in which it tries to match your prompt.720 # Defaults to 7.0 if not specified.721 width=512, # Generation width, defaults to 512 if not included.722 height=512, # Generation height, defaults to 512 if not included.723 samples=1, # Number of images to generate, defaults to 1 if not included.724 sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.725 # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.726 # (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)727 )728 729 for resp in answers:730 for artifact in resp.artifacts:731 if artifact.finish_reason == generation.FILTER:732 warnings.warn(733 "Your request activated the API's safety filters and could not be processed."734 "Please modify the prompt and try again.")735 st.warning("Issue with image generation")736 if artifact.type == generation.ARTIFACT_IMAGE:737 img = Image.open(io.BytesIO(artifact.binary))738 st.image(img)739 img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.740 rx = 'Image returned'741 # g_sheet_log(mytext, rx)742 now = datetime.datetime.now()743 date_time = now.strftime("%Y-%m-%d %H:%M:%S")744 csv_logs(mytext, rx, date_time)745 746 747 elif ("vid_tube" in string_temp):748 s = Search(mytext)749 search_res = s.results750 first_vid = search_res[0]751 print(first_vid)752 string = str(first_vid)753 video_id = string[string.index('=') + 1:-1]754 # print(video_id)755 YoutubeURL = "https://www.youtube.com/watch?v="756 OurURL = YoutubeURL + video_id757 st.write(OurURL)758 st_player(OurURL)759 now = datetime.datetime.now()760 date_time = now.strftime("%Y-%m-%d %H:%M:%S")761 ry = 'Youtube link and video returned'762 # g_sheet_log(mytext, ry)763 csv_logs(mytext, ry, date_time)764 765 elif ("don't" in string_temp or "internet" in string_temp):766 st.write('searching internet ')767 search_internet(question)768 # rz = 'Internet result returned'769 # g_sheet_log(mytext, string_temp)770 # csv_logs(mytext, rz, date_time)771 772 else:773 st.write(string_temp)774 # g_sheet_log(mytext, string_temp)775 now = datetime.datetime.now()776 date_time = now.strftime("%Y-%m-%d %H:%M:%S")777 csv_logs(mytext, string_temp, date_time)778 779elif Input_type == 'SPEECH':780 option_speech = st.selectbox(781 'Choose from below: (Options for Transcription)',782 ('Use Microphone', 'OpenAI Whisper (Upload audio file)')783 )784 785 if option_speech == 'Use Microphone':786 stt_button = Button(label="Speak", width=100)787 stt_button.js_on_event("button_click", CustomJS(code="""788 var recognition = new webkitSpeechRecognition();789 recognition.continuous = true;790 recognition.interimResults = true;791 792 recognition.onresult = function (e) {793 var value = "";794 for (var i = e.resultIndex; i < e.results.length; ++i) {795 if (e.results[i].isFinal) {796 value += e.results[i][0].transcript;797 }798 }799 if ( value != "") {800 document.dispatchEvent(new CustomEvent("GET_TEXT", {detail: value}));801 }802 }803 recognition.start();804 """))805 806 result = streamlit_bokeh_events(807 stt_button,808 events="GET_TEXT",809 key="listen",810 refresh_on_update=False,811 override_height=75,812 debounce_time=0)813 814 if result:815 if "GET_TEXT" in result:816 question = result.get("GET_TEXT")817 st.text(question)818 response = openai.Completion.create(819 model="text-davinci-003",820 prompt=f'''Your name is HyperBot and knowledge cutoff date is 2021-09, and you are not aware of any events after that time. if the 821 Answer to following questions is not from your knowledge base or in case of queries like date, time, weather 822 updates / stock updates / current affairs / news or people which requires you to have internet connection then print i don't have access to internet to answer your question, 823 if question is related to image or painting or drawing or diagram generation then print ipython type output function gen_draw("detailed prompt of image to be generated")824 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")825 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)") . 826 if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")827 \nQuestion-{question}828 \nAnswer -''',829 temperature=0.49,830 max_tokens=256,831 top_p=1,832 frequency_penalty=0,833 presence_penalty=0834 )835 string_temp=response.choices[0].text836 837 if ("gen_draw" in string_temp):838 try:839 try:840 wget.download(openai_response(prompt))841 img2 = Image.open(wget.download(openai_response(prompt)))842 img2.show()843 rx = 'Image returned'844 now = datetime.datetime.now()845 date_time = now.strftime("%Y-%m-%d %H:%M:%S")846 csv_logs(question, rx, date_time)847 except:848 urllib.request.urlretrieve(openai_response(prompt),"img_ret.png")849 img = Image.open("img_ret.png")850 img.show()851 rx = 'Image returned'852 now = datetime.datetime.now()853 date_time = now.strftime("%Y-%m-%d %H:%M:%S")854 csv_logs(question, rx, date_time)855 except:856 # Set up our initial generation parameters.857 answers = stability_api.generate(858 prompt = mytext,859 seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.860 # 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.861 # Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.862 steps=30, # Amount of inference steps performed on image generation. Defaults to 30.863 cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.864 # Setting this value higher increases the strength in which it tries to match your prompt.865 # Defaults to 7.0 if not specified.866 width=512, # Generation width, defaults to 512 if not included.867 height=512, # Generation height, defaults to 512 if not included.868 samples=1, # Number of images to generate, defaults to 1 if not included.869 sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.870 # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.871 # (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)872 )873 874 for resp in answers:875 for artifact in resp.artifacts:876 if artifact.finish_reason == generation.FILTER:877 warnings.warn(878 "Your request activated the API's safety filters and could not be processed."879 "Please modify the prompt and try again.")880 if artifact.type == generation.ARTIFACT_IMAGE:881 img = Image.open(io.BytesIO(artifact.binary))882 st.image(img)883 img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.884 rx = 'Image returned'885 # g_sheet_log(mytext, rx)886 csv_logs(question, rx, date_time)887 888 elif ("vid_tube" in string_temp):889 s = Search(question)890 search_res = s.results891 first_vid = search_res[0]892 print(first_vid)893 string = str(first_vid)894 video_id = string[string.index('=') + 1:-1]895 # print(video_id)896 YoutubeURL = "https://www.youtube.com/watch?v="897 OurURL = YoutubeURL + video_id898 st.write(OurURL)899 st_player(OurURL)900 now = datetime.datetime.now()901 date_time = now.strftime("%Y-%m-%d %H:%M:%S")902 ry = 'Youtube link and video returned'903 # g_sheet_log(mytext, ry)904 csv_logs(question, ry, date_time)905 906 907 elif ("don't" in string_temp or "internet" in string_temp ):908 st.write('*searching internet*')909 search_internet(question)910 else:911 st.write(string_temp)912 now = datetime.datetime.now()913 date_time = now.strftime("%Y-%m-%d %H:%M:%S")914 csv_logs(question, string_temp, date_time)915 916 917 elif option_speech == 'OpenAI Whisper (Upload audio file)':918 audio_file = st.file_uploader("Upload Audio file",type=['wav', 'mp3'])919 if audio_file is not None:920 # file = open(audio_file, "rb")921 st.audio(audio_file)922 transcription = openai.Audio.transcribe("whisper-1", audio_file)923 st.write(transcription["text"])924 result = transcription["text"]925 question = result926 response = openai.Completion.create(927 model="text-davinci-003",928 prompt=f'''Your name is HyperBot and knowledge cutoff date is 2021-09, and you are not aware of any events after that time. if the 929 Answer to following questions is not from your knowledge base or in case of queries like date, time, weather 930 updates / stock updates / current affairs / news or people which requires you to have internet connection then print i don't have access to internet to answer your question, 931 if question is related to image or painting or drawing or diagram generation then print ipython type output function gen_draw("detailed prompt of image to be generated")932 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")933 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)") . 934 if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")935 \nQuestion-{question}936 \nAnswer -''',937 temperature=0.49,938 max_tokens=256,939 top_p=1,940 frequency_penalty=0,941 presence_penalty=0942 )943 944 string_temp=response.choices[0].text945 946 if ("gen_draw" in string_temp):947 try:948 try:949 wget.download(openai_response(prompt))950 img2 = Image.open(wget.download(openai_response(prompt)))951 img2.show()952 rx = 'Image returned'953 now = datetime.datetime.now()954 date_time = now.strftime("%Y-%m-%d %H:%M:%S")955 csv_logs(question, rx, date_time)956 except:957 urllib.request.urlretrieve(openai_response(prompt),"img_ret.png")958 img = Image.open("img_ret.png")959 img.show()960 rx = 'Image returned'961 now = datetime.datetime.now()962 date_time = now.strftime("%Y-%m-%d %H:%M:%S")963 csv_logs(question, rx, date_time)964 except:965 # Set up our initial generation parameters.966 answers = stability_api.generate(967 prompt = mytext,968 seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.969 # 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.970 # Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.971 steps=30, # Amount of inference steps performed on image generation. Defaults to 30.972 cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.973 # Setting this value higher increases the strength in which it tries to match your prompt.974 # Defaults to 7.0 if not specified.975 width=512, # Generation width, defaults to 512 if not included.976 height=512, # Generation height, defaults to 512 if not included.977 samples=1, # Number of images to generate, defaults to 1 if not included.978 sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.979 # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.980 # (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)981 )982 983 for resp in answers:984 for artifact in resp.artifacts:985 if artifact.finish_reason == generation.FILTER:986 warnings.warn(987 "Your request activated the API's safety filters and could not be processed."988 "Please modify the prompt and try again.")989 if artifact.type == generation.ARTIFACT_IMAGE:990 img = Image.open(io.BytesIO(artifact.binary))991 st.image(img)992 img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.993 rx = 'Image returned'994 # g_sheet_log(mytext, rx)995 csv_logs(question, rx, date_time)996 997 998 elif ("vid_tube" in string_temp):999 s = Search(question)1000 search_res = s.results1001 first_vid = search_res[0]1002 print(first_vid)1003 string = str(first_vid)1004 video_id = string[string.index('=') + 1:-1]1005 # print(video_id)1006 YoutubeURL = "https://www.youtube.com/watch?v="1007 OurURL = YoutubeURL + video_id1008 st.write(OurURL)1009 st_player(OurURL)1010 now = datetime.datetime.now()1011 date_time = now.strftime("%Y-%m-%d %H:%M:%S")1012 ry = 'Youtube link and video returned'1013 # g_sheet_log(mytext, ry)1014 csv_logs(question, ry, date_time)1015 1016 elif ("don't" in string_temp or "internet" in string_temp ):1017 st.write('*searching internet*')1018 search_internet(question)1019 else:1020 st.write(string_temp)1021 now = datetime.datetime.now()1022 date_time = now.strftime("%Y-%m-%d %H:%M:%S")1023 csv_logs(question, string_temp, date_time)1024 1025else:1026 pass1027 