File size: 8,070 Bytes
374a607 25b522b 44937e4 25b522b 38dd9ca 25b522b 374a607 25b522b 93c5237 25b522b 374a607 25b522b 374a607 25b522b 8dbf27b 25b522b 0fdc36d 25b522b 374a607 25b522b 374a607 25b522b 374a607 af7e304 374a607 25b522b 374a607 25b522b 44937e4 25b522b 374a607 25b522b bf62c66 25b522b ea27e8e 25b522b 374a607 25b522b 374a607 25b522b 374a607 25b522b b8d7506 bf62c66 940e926 25b522b 44937e4 25b522b 44937e4 4ea4a6a 25b522b 803601c 3148385 803601c |
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 |
import os
from datetime import datetime
import streamlit as st
from helper import ChatBot, current_year, invoke_search_api, save_to_audio
# API KEY
API_KEY = os.environ["API_KEY"]
# Front-end
st.set_page_config(layout="wide")
st.title("SearchBot π€")
# Front-end: Sidebar
with st.sidebar:
with st.expander("Instruction Manual"):
st.markdown(
"""
## SearchBot π€
This Streamlit app allows you to search anything.
### How to Use:
1. **Source**: Select your favorite source, i.e. default is Google.
1. **Num**: Select number of output you want to display, i.e. default is 20.
1. **Location**: Select your location so content such as weather can be customized, i.e. default is New York.
2. **Response**: The app will display a response table.
3. **Chat History**: Previous conversations will be shown on the app and can be cleared using "Clear Session" button.
### Source:
- **Site**: The source app is deployed on **HuggingFace** with this [link](https://huggingface.co/spaces/eagle0504/searchbot).
### Credits:
- **Developer**: [Yiqiao Yin](https://www.y-yin.io/) | [App URL](https://huggingface.co/spaces/eagle0504/serpapi-demo) | [LinkedIn](https://www.linkedin.com/in/yiqiaoyin/) | [YouTube](https://youtube.com/YiqiaoYin/)
Enjoy chatting with SearchBot!
"""
)
# Example:
st.success("Example: Yiqiao Yin.")
st.success("Example: Weather in Westchester, NY today")
st.success("Example: Latest news about Tesla")
st.success(
"Example: Taking medicine during pregnancy (you can select WebMD to filter only results from WebMD)"
)
# Input
src_key_word = st.selectbox(
"Source of page you prefer?",
(
"Google",
"Google Finance",
"Google Scholar",
"Yahoo",
"WSJ",
"Bloomberg",
"NYTimes",
"Economist",
"WebMD",
"BetterHelp",
"Zocdoc",
"Clevelandclinic",
"Drugs.com",
"EMedicineHealth.com",
"Reddit",
),
)
src_key_word = "" if src_key_word == "Google" else src_key_word
num = st.number_input(
"Number of src to display", value=7, step=1, placeholder="Type a number..."
)
location = st.selectbox(
"Where would you like to search from?",
(
"New York, New York, United States",
"Los Angeles, California, United States",
"Chicago, Illinois, United States",
"Houston, Texas, United States",
"Phoenix, Arizona, United States",
"Philadelphia, Pennsylvania, United States",
"San Antonio, Texas, United States",
"San Diego, California, United States",
"Dallas, Texas, United States",
"San Jose, California, United States",
"Austin, Texas, United States",
"Jacksonville, Florida, United States",
"Fort Worth, Texas, United States",
"Columbus, Ohio, United States",
"Charlotte, North Carolina, United States",
"San Francisco, California, United States",
"Indianapolis, Indiana, United States",
"Seattle, Washington, United States",
"Denver, Colorado, United States",
"Washington, D.C., United States",
"Boston, Massachusetts, United States",
"El Paso, Texas, United States",
"Nashville, Tennessee, United States",
"Detroit, Michigan, United States",
"Oklahoma City, Oklahoma, United States",
"Portland, Oregon, United States",
"Las Vegas, Nevada, United States",
"Memphis, Tennessee, United States",
"Louisville, Kentucky, United States",
"Baltimore, Maryland, United States",
"Milwaukee, Wisconsin, United States",
"Albuquerque, New Mexico, United States",
"Tucson, Arizona, United States",
"Fresno, California, United States",
"Sacramento, California, United States",
"Mesa, Arizona, United States",
"Kansas City, Missouri, United States",
"Atlanta, Georgia, United States",
"Omaha, Nebraska, United States",
"Colorado Springs, Colorado, United States",
),
)
only_use_chatbot = st.checkbox("Only use chatbot.")
# Add a button to clear the session state
if st.button("Clear Session"):
st.session_state.messages = []
st.rerun()
# Credit:
current_year = current_year() # This will print the current year
st.markdown(
f"""
<h6 style='text-align: left;'>Copyright Β© 2010-{current_year} Present Yiqiao Yin</h6>
""",
unsafe_allow_html=True,
)
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Ensure messages are a list of dictionaries
if not isinstance(st.session_state.messages, list):
st.session_state.messages = []
if not all(isinstance(msg, dict) for msg in st.session_state.messages):
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Front-end: Chat Panel - React to user input
if prompt := st.chat_input(
"π Ask any question or feel free to use the examples provided in the left sidebar."
):
# Display user message in chat message container
st.chat_message("user").markdown(prompt)
# Add user message to chat history
st.session_state.messages.append(
{
"role": "system",
"content": f"You are a helpful assistant. Year now is {current_year}",
}
)
st.session_state.messages.append({"role": "user", "content": prompt})
# API Call
query = src_key_word + " " + prompt
try:
with st.spinner("Wait for it..."):
if only_use_chatbot:
md_data = "<empty>"
response = "<empty>"
ref_table_string = "<empty>"
else:
md_data = invoke_search_api(
api_key=API_KEY, query=query, location=location, num=num
)
md_data = md_data["data"]
response = f"""
Please see search results below: \n{md_data}
"""
ref_table_string = response
# API Call
bot = ChatBot()
bot.history = (
st.session_state.messages.copy()
) # Update history from messages
response = bot.generate_response(
f"""
Here's user prompt: {prompt}
Here's relevant content: {response}
Answer user prompt based on the relevant content.
If relevant content is provided, it'd be a table with Title, Link, and Snippet. Use information from the Snippet.
If relevant content is <empty>, use your best judgement or chat history."""
)
except Exception as e:
st.warning(f"Failed to fetch data: {e}")
response = "We are fixing the API right now. Please check back later."
# Save audio
if response:
save_to_audio(response)
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.markdown(response, unsafe_allow_html=True)
st.audio("output.mp3", format="audio/mpeg", loop=True)
with st.expander("See references:", expanded=False):
st.markdown(ref_table_string)
# Add assistant response to chat history
final_response = f"""
{response}
{ref_table_string}"""
st.session_state.messages.append({"role": "assistant", "content": final_response})
|