Spaces:
Running
Running
File size: 13,213 Bytes
12a115f 681c37e 00ee575 12a115f 1212c0e 681c37e 12a115f 1212c0e 681c37e 12a115f 1212c0e 681c37e 12a115f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
import os
import openai
import wget
import streamlit as st
from PIL import Image
from serpapi import GoogleSearch
import torch
from diffusers import StableDiffusionPipeline
from bokeh.models.widgets import Button
from bokeh.models import CustomJS
from streamlit_bokeh_events import streamlit_bokeh_events
import base64
from streamlit_player import st_player
from pytube import YouTube
from pytube import Search
import io
import warnings
from PIL import Image
from stability_sdk import client
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
stability_api = client.StabilityInference(
key=os.environ("STABILITY_KEY"),
# key=os.environ['STABILITY_KEY'], # API Key reference.
verbose=True, # Print debug messages.
engine="stable-diffusion-v1-5", # Set the engine to use for generation.
# Available engines: stable-diffusion-v1 stable-diffusion-v1-5 stable-diffusion-512-v2-0 stable-diffusion-768-v2-0
# stable-diffusion-512-v2-1 stable-diffusion-768-v2-1 stable-inpainting-v1-0 stable-inpainting-512-v2-0
)
def search_internet(question):
params = {
"q": question,
"location": "Bengaluru, Karnataka, India",
"hl": "hi",
"gl": "in",
"google_domain": "google.co.in",
# "api_key": ""
"api_key": os.environ("GOOGLE_API") #os.environ['GOOGLE_API']
}
params = {
"q": question,
"location": "Bengaluru, Karnataka, India",
"hl": "hi",
"gl": "in",
"google_domain": "google.co.in",
# "api_key": ""
"api_key": os.environ("GOOGLE_API") #os.environ['GOOGLE_API']
}
search = GoogleSearch(params)
results = search.get_dict()
organic_results = results["organic_results"]
snippets = ""
counter = 1
for item in organic_results:
snippets += str(counter) + ". " + item.get("snippet", "") + '\n' + item['about_this_result']['source']['source_info_link'] + '\n'
counter += 1
# snippets
response = openai.Completion.create(
model="text-davinci-003",
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-''',
temperature=0.49,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0)
string_temp = response.choices[0].text
st.write(string_temp)
st.write(snippets)
# openai.api_key = ""
openai.api_key = os.environ("OPENAI_KEY") #os.environ['OPENAI_KEY']
def openai_response(PROMPT):
response = openai.Image.create(
prompt=PROMPT,
n=1,
size="256x256",
)
return response["data"][0]["url"]
#page_bg_img = """
#<style>
#[data-testid="stAppViewContainer"] {
#background-color: #ffffff;
#opacity: 0.8;
#background-image: repeating-radial-gradient( circle at 0 0, transparent 0, #ffffff 40px ), repeating-linear-gradient( #55a6f655, #55a6f6 );
#}
#</style>
#"""
#st.markdown(page_bg_img, unsafe_allow_html=True)
st.title("Welcome to :red[_HyperChat_]!!🤖")
st.title("How can I help?")
Input_type = st.radio(
"**Input type:**",
('TEXT', 'SPEECH')
)
if Input_type == 'TEXT':
#page_bg_img2 = """
#<style>
#[data-testid="stAppViewContainer"] {
#background-color: #e5e5f7;
#opacity: 0.8;
#background-size: 20px 20px;
#background-image: repeating-linear-gradient(0deg, #32d947, #32d947 1px, #e5e5f7 1px, #e5e5f7);
#}
#</style>
#"""
#st.markdown(page_bg_img, unsafe_allow_html=True)
st.write('**You are now in Text input mode**')
mytext = st.text_input('**Go on! Ask me anything:**')
if st.button("SUBMIT"):
question=mytext
response = openai.Completion.create(
model="text-davinci-003",
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
Answer to following questions is not from your knowledge base or in case of queries like weather
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,
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")
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")
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)") .
if question is realted to sending mail or sms then print ipython type output function messenger_app(" message of us ,messenger(email,sms)")
\nQuestion-{question}
\nAnswer -''',
temperature=0.49,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
string_temp=response.choices[0].text
if ("gen_draw" in string_temp):
try:
# Set up our initial generation parameters.
answers = stability_api.generate(
prompt = mytext,
seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.
# 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.
# Note: This isn't quite the case for Clip Guided generations, which we'll tackle in a future example notebook.
steps=30, # Amount of inference steps performed on image generation. Defaults to 30.
cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.
# Setting this value higher increases the strength in which it tries to match your prompt.
# Defaults to 7.0 if not specified.
width=512, # Generation width, defaults to 512 if not included.
height=512, # Generation height, defaults to 512 if not included.
samples=1, # Number of images to generate, defaults to 1 if not included.
sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.
# Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.
# (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)
)
# Set up our warning to print to the console if the adult content classifier is tripped.
# If adult content classifier is not tripped, save generated images.
for resp in answers:
for artifact in resp.artifacts:
if artifact.finish_reason == generation.FILTER:
warnings.warn(
"Your request activated the API's safety filters and could not be processed."
"Please modify the prompt and try again.")
if artifact.type == generation.ARTIFACT_IMAGE:
img = Image.open(io.BytesIO(artifact.binary))
st.image(img)
img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.
except:
st.write('image is being generated please wait...')
def extract_image_description(input_string):
return input_string.split('gen_draw("')[1].split('")')[0]
prompt=extract_image_description(string_temp)
# model_id = "CompVis/stable-diffusion-v1-4"
model_id='runwayml/stable-diffusion-v1-5'
device = "cuda"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to(device)
# prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]
image.save("astronaut_rides_horse.png")
st.image(image)
# image
elif ("vid_tube" in string_temp):
s = Search(mytext)
search_res = s.results
first_vid = search_res[0]
print(first_vid)
string = str(first_vid)
video_id = string[string.index('=') + 1:-1]
# print(video_id)
YoutubeURL = "https://www.youtube.com/watch?v="
OurURL = YoutubeURL + video_id
st.write(OurURL)
st_player(OurURL)
elif ("don't" in string_temp or "internet" in string_temp ):
st.write('searching internet ')
search_internet(question)
else:
st.write(string_temp)
elif Input_type == 'SPEECH':
stt_button = Button(label="Speak", width=100)
stt_button.js_on_event("button_click", CustomJS(code="""
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onresult = function (e) {
var value = "";
for (var i = e.resultIndex; i < e.results.length; ++i) {
if (e.results[i].isFinal) {
value += e.results[i][0].transcript;
}
}
if ( value != "") {
document.dispatchEvent(new CustomEvent("GET_TEXT", {detail: value}));
}
}
recognition.start();
"""))
result = streamlit_bokeh_events(
stt_button,
events="GET_TEXT",
key="listen",
refresh_on_update=False,
override_height=75,
debounce_time=0)
if result:
if "GET_TEXT" in result:
st.write(result.get("GET_TEXT"))
question = result.get("GET_TEXT")
response = openai.Completion.create(
model="text-davinci-003",
prompt=f'''Your knowledge cutoff is 2021-09, and it is not aware of any events after that time. if the
Answer to following questions is not from your knowledge base or in case of queries like weather
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,
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")
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")
\nQuestion-{question}
\nAnswer -''',
temperature=0.49,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
string_temp=response.choices[0].text
if ("gen_draw" in string_temp):
st.write('*image is being generated please wait..* ')
def extract_image_description(input_string):
return input_string.split('gen_draw("')[1].split('")')[0]
prompt=extract_image_description(string_temp)
# model_id = "CompVis/stable-diffusion-v1-4"
model_id='runwayml/stable-diffusion-v1-5'
device = "cuda"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to(device)
# prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]
image.save("astronaut_rides_horse.png")
st.image(image)
# image
elif ("vid_tube" in string_temp):
s = Search(question)
search_res = s.results
first_vid = search_res[0]
print(first_vid)
string = str(first_vid)
video_id = string[string.index('=') + 1:-1]
# print(video_id)
YoutubeURL = "https://www.youtube.com/watch?v="
OurURL = YoutubeURL + video_id
st.write(OurURL)
st_player(OurURL)
elif ("don't" in string_temp or "internet" in string_temp ):
st.write('*searching internet*')
search_internet(question)
else:
st.write(string_temp)
|