ChatBot / app-bak.py
bumk766fall2023's picture
Major update
dd4984c
Raw History Blame Contribute Delete
9.58 kB
#import openai
import gradio as gr
import os
# openai.api_key = "MY_API_KEY"
# messages = [
# {"role": "system", "content": "You are a helpful and kind AI Assistant."},
# ]
# def chatbot(input):
# if input:
# messages.append({"role": "user", "content": input})
# chat = openai.ChatCompletion.create(
# model="gpt-3.5-turbo", messages=messages
# )
# reply = chat.choices[0].message.content
# messages.append({"role": "assistant", "content": reply})
# return reply
import random
import time
import numpy as np
theme2 = gr.themes.Base(
primary_hue="gray",
secondary_hue="gray",
).set(
background_fill_primary_dark='*block_title_background_fill',
background_fill_secondary_dark='*neutral_950'
)
theme3 = gr.themes.Base(
primary_hue="gray",
secondary_hue="gray",
).set(
background_fill_primary_dark='*neutral_950'
)
theme1 = gr.themes.Base()
def get_params(request: gr.Request):
params = request.query_params
ip = request.client.host
return {"params": params, "ip": ip}
with gr.Blocks(theme = theme3) as demo:
chatbot = gr.Chatbot(value = [], elem_id="chatbot", layout = "panel",
#avatar_images=("https://drive.google.com/uc?export=download&id=14X5ClSbPAXdFzyk1w4pwsefCQCjry_qF", "https://drive.google.com/uc?export=download&id=1iK93a8f36bV2LRHhe5cqRqEZmWh6d0Dm"),)
#avatar_images=("https://drive.google.com/uc?export=view&id=13K109W715t-C5lw1sdWz9Cbj2L0di2uF", "https://drive.google.com/uc?export=view&id=1QK-y3_HtljLG79XGloWAtPLNOti7Q31M"),)
avatar_images=("images/usericon.jpeg", "images/chatboticon.jpeg"),)
#avatar_images=(None, (os.path.join(os.path.dirname(__file__), "images/chatboticon.jpeg"))))
url_params = gr.State()
demo.load(get_params, None, url_params, queue=True)
with gr.Row():
with gr.Column(min_width=200, scale=10):
msg = gr.Textbox(
show_label=False,
placeholder="Enter text and press enter",
max_lines = 5,
container = False,
)
with gr.Column(min_width = 42, scale= 1):
btn = gr.Button(value="⬆︎")
with gr.Column(min_width = 42, scale= 1):
Infa_text = gr.Textbox(label="Infa here")
def user(user_message, history):
qs = {'params': 'url_params', 'hello': 'hi, how can i help you?', 'hi': 'hi, how can i help you?', 'restaurants': "New York City boasts a diverse culinary scene. Notable restaurants include fine dining establishments like Per Se, iconic pizzerias like Di Fara Pizza, classic delis like Katz's, and trendy spots like Momofuku Noodle Bar. Options range from Italian at Lilia to Asian fusion at Mission Chinese Food, with diverse choices reflecting the city's international influences. Explore neighborhoods for hidden gems, and iconic markets like Chelsea Market offer a variety of food experiences.", 'president': 'As of my last knowledge update in January 2022, Joe Biden was the President of the United States. However, please note that my information might be outdated, as I do not have real-time capabilities. I recommend checking the latest reliable sources for the most current information on the President of the United States.', 'moon': "The Moon is Earth's only natural satellite, formed about 4.5 billion years ago. It has a diameter of 3,474 kilometers, 1/6th of Earth's gravity, and features like craters, mountains, and lunar maria. The Moon has no significant atmosphere, experiences phases due to its orbit, and was explored by astronauts during the Apollo missions. Future plans include returning to the Moon for exploration and potential habitation.",
'gogh': "Vincent van Gogh (1853–1890) was a Dutch post-impressionist painter. He is renowned for his expressive use of color, bold brushstrokes, and emotional intensity in works like Starry Night and Sunflowers. Despite struggling with mental health issues throughout his life, van Gogh created over 2,000 artworks, but he only gained widespread recognition after his death. His impact on art and his unique style have made him an enduring figure in the history of Western art.",
'a': "The clever word play makes this book a fun choice for story time. One day, a chimpanzee and a kinkajou take a walk, enjoying the buttercups, at least until the chimpanzee lets loose a gigantic sneeze; otherwise known as a chimpanSNEEZE. The sneeze sends the kinkajou flying off the page into the back of an elephant painting a fence. The rhyming text follows the disasters that occur as a result of the initiating sneeze. An elephant with paint on it's head and an extended trunk, trips a buffalo carrying bread, which leads to a disaster with mustard and a hippo. It seems nothing will fix the mess, until another mighty sneeze rights the ship. Or does it? The vivid illustrations showing all kinds of mayhem will hold the attention of the youngest listeners, while older children will appreciate unusually combined words such as Buffaloaf and Hippopotamustard. Not only a fun tale of nonsense but a perfect demonstration of the power of cause and effect. An enjoyable read for young and old."}
def chat(input):
for q in set(input.lower().split()):
if q in qs:
return qs[q]
break
else:
#return "### ![BOT logo](https://gradio.app/assets/gradio.svg). Sorry, I don't know (10:17pm)"
return "Sorry, I don't know (Wed 14:15)"
bot_message = chat(user_message)
return "", history + [[user_message, bot_message]]
def bot(history):
#print(history)
# bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
#history[-1][1] = ""
time.sleep(2)
bot_message = history[-1][1]
history[-1][1] = ""
for character in bot_message:
history[-1][1] += character
if character != " ":
a = 1
time.sleep(0.000000025)
time.sleep(0.005)
else:
#time.sleep(abs(s[random.randint(0, 99)]) * 0.1)
a = 2
yield history
#def mean_var_calculator(history):
# def mean_var_calculator():
# mu = random.randint(1, 10)
# sigma = random.randint(1, 5) # mean and standard deviation
# global s
# s = np.random.normal(mu, sigma, 100)
# return mu, sigma
def print_params(passe):
return passe #url_params
# msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
# bot, chatbot, chatbot
# )
# msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False)
# msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
# bot, chatbot, chatbot
# )
btn.click(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
bot, chatbot, chatbot
)
#btn.click(user, [msg, chatbot], [msg, chatbot], queue=False, show_progress=False).then(
# print_params, url_params, Infa_text
#)
#mean_var_calculator()
demo.queue()
#demo.launch()
demo.launch(allowed_paths=["."]) # , allowed_paths=['/images']
# qs = {'hello': 'hi, how can i help you?', 'hi': 'hi, how can i help you?', 'restaurants': "New York City boasts a diverse culinary scene. Notable restaurants include fine dining establishments like Per Se, iconic pizzerias like Di Fara Pizza, classic delis like Katz's, and trendy spots like Momofuku Noodle Bar. Options range from Italian at Lilia to Asian fusion at Mission Chinese Food, with diverse choices reflecting the city's international influences. Explore neighborhoods for hidden gems, and iconic markets like Chelsea Market offer a variety of food experiences.", 'president': 'As of my last knowledge update in January 2022, Joe Biden was the President of the United States. However, please note that my information might be outdated, as I do not have real-time capabilities. I recommend checking the latest reliable sources for the most current information on the President of the United States.', 'moon': "The Moon is Earth's only natural satellite, formed about 4.5 billion years ago. It has a diameter of 3,474 kilometers, 1/6th of Earth's gravity, and features like craters, mountains, and lunar maria. The Moon has no significant atmosphere, experiences phases due to its orbit, and was explored by astronauts during the Apollo missions. Future plans include returning to the Moon for exploration and potential habitation.",
# 'gogh': "Vincent van Gogh (1853–1890) was a Dutch post-impressionist painter. He is renowned for his expressive use of color, bold brushstrokes, and emotional intensity in works like Starry Night and Sunflowers. Despite struggling with mental health issues throughout his life, van Gogh created over 2,000 artworks, but he only gained widespread recognition after his death. His impact on art and his unique style have made him an enduring figure in the history of Western art."}
# def chatbot(input):
# for q in set(input.lower().split()):
# if q in qs:
# return qs[q]
# inputs = gr.Textbox(lines=7, label="Chat with AI")
# outputs = gr.Textbox(label="Reply")
# gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
# description="Ask anything you want",
# theme="compact").launch(share=True)