Spaces:
Running
on
T4
Running
on
T4
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from teapotai import TeapotAI, TeapotAISettings
|
3 |
+
import hashlib
|
4 |
+
|
5 |
+
default_documents = default_documents = [
|
6 |
+
"The Eiffel Tower is located in Paris, France. It was built in 1889 and stands 330 meters tall. The tower was originally constructed for the 1889 Exposition Universelle (World’s Fair) and was the tallest man-made structure in the world at the time. Designed by Gustave Eiffel, the tower is made of wrought iron and has become a symbol of French engineering and artistry. Visitors from all over the world come to admire its intricate design and take in the panoramic views of Paris from its observation decks.",
|
7 |
+
|
8 |
+
"The Great Wall of China is a historic fortification that stretches over 13,000 miles. Originally built to protect Chinese states from invading forces, it was constructed over several centuries, with the earliest sections dating back to the 7th century BC. The wall is an extraordinary feat of ancient engineering, featuring watchtowers, barracks, and defensive gates. Today, it stands as one of the most famous landmarks in the world, attracting millions of visitors each year.",
|
9 |
+
|
10 |
+
"The Amazon Rainforest is the largest tropical rainforest in the world, covering over 5.5 million square kilometers. Spanning across nine countries in South America, the rainforest is home to an incredible array of plant and animal species, many of which are found nowhere else on Earth. The Amazon plays a vital role in regulating the global climate by producing oxygen and absorbing carbon dioxide. However, it is facing significant threats from deforestation and climate change.",
|
11 |
+
|
12 |
+
"The Grand Canyon is a natural landmark located in Arizona, USA, carved by the Colorado River. It stretches 277 miles long, up to 18 miles wide, and reaches depths of over a mile. The Grand Canyon’s vibrant rock layers reveal millions of years of geological history, making it a fascinating destination for geologists and tourists alike. The canyon's breathtaking views and unique landscape make it one of the most visited natural attractions in the world.",
|
13 |
+
|
14 |
+
"Mount Everest is the tallest mountain on Earth, located in the Himalayas along the border between Nepal and China. Standing at 8,848 meters above sea level, its peak is known as ‘the Roof of the World.’ Climbing Mount Everest is considered one of the most challenging feats in the world due to its extreme altitude, harsh weather, and difficult terrain. It continues to draw mountaineers and adventurers from across the globe, despite the many risks associated with summiting the mountain.",
|
15 |
+
|
16 |
+
"The Colosseum in Rome, Italy, is an ancient amphitheater known for its gladiator battles. Completed in 80 AD, the Colosseum was used for a variety of public spectacles, including animal hunts, mock naval battles, and executions. With a capacity to seat up to 50,000 spectators, it was the largest amphitheater in the Roman Empire. Today, it remains a symbol of Roman engineering and entertainment and attracts millions of visitors annually.",
|
17 |
+
|
18 |
+
"The Sahara Desert is the largest hot desert in the world, located in North Africa. Spanning over 9 million square kilometers, it is known for its vast sand dunes, extreme temperatures, and minimal rainfall. Despite the harsh conditions, the Sahara is home to a variety of life, including desert plants, animals, and nomadic human populations. The desert’s landscape is a stunning mix of rocky plateaus, vast sand dunes, and occasional oases.",
|
19 |
+
|
20 |
+
"The Nile River is the longest river in the world, flowing through northeastern Africa. It stretches over 6,600 kilometers and has been a vital resource for the civilizations of Egypt and Sudan for thousands of years. The river provides fertile land for agriculture in an otherwise arid region and has played a significant role in the development of these ancient cultures. Today, it remains an essential lifeline for the millions of people who live along its banks.",
|
21 |
+
|
22 |
+
"The Empire State Building is an iconic skyscraper in New York City that was completed in 1931 and stands at 1454 feet tall. Designed in the Art Deco style by architect William F. Lamb, it was the tallest building in the world until 1970. The Empire State Building features observation decks that offer stunning views of the city and remains an enduring symbol of New York’s skyline. It continues to attract millions of visitors from around the world each year.",
|
23 |
+
|
24 |
+
"The Pyramids of Giza are a group of ancient Egyptian structures located on the outskirts of Cairo. The Great Pyramid, built for Pharaoh Khufu, is the largest and one of the Seven Wonders of the Ancient World. These massive stone structures were constructed as tombs for the Pharaohs and their queens. The pyramids, along with the nearby Sphinx, are one of Egypt’s most famous tourist attractions, drawing visitors from across the globe.",
|
25 |
+
|
26 |
+
"The Taj Mahal is a stunning white marble mausoleum located in Agra, India. Built by Emperor Shah Jahan in memory of his wife Mumtaz Mahal, it is considered one of the finest examples of Mughal architecture. The Taj Mahal is known for its intricate designs, including detailed carvings and inlaid gemstones. It is a UNESCO World Heritage site and attracts millions of visitors annually for its beauty and historical significance.",
|
27 |
+
|
28 |
+
"The Sydney Opera House is a world-renowned performing arts center located in Sydney, Australia. Completed in 1973, the building is famous for its unique sail-like design and stunning location on Sydney Harbour. It is one of the most recognizable architectural landmarks in the world and hosts a wide range of performances, from opera and ballet to theater and concerts. The Opera House is a symbol of Australia’s vibrant cultural scene.",
|
29 |
+
|
30 |
+
"The Statue of Liberty is a colossal sculpture located on Liberty Island in New York Harbor. A gift from France to the United States in 1886, the statue symbolizes freedom and democracy. Standing at 305 feet tall from base to torch, it was the tallest structure in New York City when it was erected. Today, it remains one of the most famous landmarks in the world and is a symbol of hope and opportunity for millions of immigrants.",
|
31 |
+
|
32 |
+
"Machu Picchu is an ancient Inca citadel located high in the Andes Mountains of Peru. Built in the 15th century, it was a royal estate and a religious site for the Inca civilization. The site is renowned for its advanced dry-stone construction and stunning location, perched atop a mountain ridge with sweeping views of the surrounding landscape. Machu Picchu is one of the most important archaeological sites in South America and a UNESCO World Heritage site.",
|
33 |
+
|
34 |
+
"Stonehenge is a prehistoric monument located in Wiltshire, England. Believed to have been constructed between 3000 and 2000 BCE, Stonehenge consists of a ring of standing stones, some weighing up to 25 tons. Its purpose remains a mystery, though it is thought to have been used for religious or ceremonial purposes. Stonehenge attracts thousands of visitors each year who marvel at its ancient mystery and connection to early human history.",
|
35 |
+
|
36 |
+
"The Acropolis of Athens is an ancient citadel located on a rocky outcrop above the city of Athens, Greece. It is home to several ancient structures, including the Parthenon, a temple dedicated to the goddess Athena. The Acropolis is considered a symbol of classical Greek civilization and is one of the most important archaeological sites in the world. It attracts millions of visitors annually who come to admire its historical and architectural significance.",
|
37 |
+
|
38 |
+
"The Christ the Redeemer statue is a giant statue of Jesus Christ located in Rio de Janeiro, Brazil. Standing 98 feet tall and with outstretched arms, it overlooks the city from the peak of Corcovado Mountain. Completed in 1931, the statue is an iconic symbol of Christianity and Brazilian culture. It is one of the New Seven Wonders of the World and offers stunning views of Rio and its surrounding beaches.",
|
39 |
+
|
40 |
+
"The Kremlin is a fortified complex located in the heart of Moscow, Russia. It serves as the official residence of the Russian president and includes several palaces, cathedrals, and government buildings. The Kremlin has been the seat of Russian power for centuries, from Tsarist Russia to the Soviet Union and modern Russia. It is a UNESCO World Heritage site and a key symbol of Russian political and historical significance.",
|
41 |
+
|
42 |
+
"The Louvre Museum is one of the world’s largest and most famous art museums, located in Paris, France. Originally a royal palace, it became a museum in 1793 and now houses thousands of works of art, including the famous painting, the Mona Lisa. The Louvre's extensive collection spans from ancient civilizations to modern times. It remains one of the most visited museums in the world, attracting millions of art lovers annually."
|
43 |
+
]
|
44 |
+
|
45 |
+
# Function to handle the chat with TeapotAI
|
46 |
+
def handle_chat(user_input, teapot_ai):
|
47 |
+
response = teapot_ai.chat([
|
48 |
+
{
|
49 |
+
"role": "system",
|
50 |
+
"content": "You are an agent designed to answer facts about famous landmarks."
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"role": "user",
|
54 |
+
"content": user_input
|
55 |
+
}
|
56 |
+
])
|
57 |
+
return response
|
58 |
+
|
59 |
+
def suggestion_button(suggestion_text, teapot_ai):
|
60 |
+
if st.button(suggestion_text):
|
61 |
+
handle_chat(suggestion_text, teapot_ai)
|
62 |
+
|
63 |
+
# Function to hash documents
|
64 |
+
def hash_documents(documents):
|
65 |
+
return hashlib.sha256("\n".join(documents).encode("utf-8")).hexdigest()
|
66 |
+
|
67 |
+
# Streamlit app
|
68 |
+
def main():
|
69 |
+
st.set_page_config(page_title="TeapotAI Chat", page_icon=":robot_face:", layout="wide")
|
70 |
+
|
71 |
+
# Sidebar for document input
|
72 |
+
st.sidebar.header("Document Input (for RAG)")
|
73 |
+
user_documents = st.sidebar.text_area(
|
74 |
+
"Enter documents, each on a new line",
|
75 |
+
value="\n".join(default_documents)
|
76 |
+
)
|
77 |
+
|
78 |
+
# Parse the user input to get the documents (split by newline)
|
79 |
+
documents = user_documents.split("\n")
|
80 |
+
|
81 |
+
# Ensure non-empty documents
|
82 |
+
documents = [doc for doc in documents if doc.strip()]
|
83 |
+
|
84 |
+
# Check if documents have changed
|
85 |
+
new_documents_hash = hash_documents(documents)
|
86 |
+
|
87 |
+
# Load model if documents have changed, otherwise reuse the model from session_state
|
88 |
+
if "documents_hash" not in st.session_state or st.session_state.documents_hash != new_documents_hash:
|
89 |
+
with st.spinner('Loading Model and Embeddings...'):
|
90 |
+
teapot_ai = TeapotAI(documents=documents or default_documents, settings=TeapotAISettings(rag_num_results=3))
|
91 |
+
|
92 |
+
# Store the new hash and model in session state
|
93 |
+
st.session_state.documents_hash = new_documents_hash
|
94 |
+
st.session_state.teapot_ai = teapot_ai
|
95 |
+
else:
|
96 |
+
# Reuse the existing model
|
97 |
+
teapot_ai = st.session_state.teapot_ai
|
98 |
+
|
99 |
+
# Initialize session state and display the welcome message
|
100 |
+
if "messages" not in st.session_state:
|
101 |
+
st.session_state.messages = [{"role": "assistant", "content": "Hi, I am Teapot AI, how can I help you?"}]
|
102 |
+
|
103 |
+
# Display previous messages from chat history
|
104 |
+
for message in st.session_state.messages:
|
105 |
+
with st.chat_message(message["role"]):
|
106 |
+
st.markdown(message["content"])
|
107 |
+
|
108 |
+
# Accept user input
|
109 |
+
user_input = st.chat_input("Ask about famous landmarks")
|
110 |
+
|
111 |
+
s1, s2, s3 = st.columns([1, 2, 3])
|
112 |
+
with s1:
|
113 |
+
suggestion_button("How tall is the Eiffel Tower?", teapot_ai)
|
114 |
+
with s2:
|
115 |
+
suggestion_button("Extract the year the Eiffel Tower was constructed.", teapot_ai)
|
116 |
+
with s3:
|
117 |
+
suggestion_button("How large is the Death Star?", teapot_ai)
|
118 |
+
|
119 |
+
if user_input:
|
120 |
+
# Display user message in chat message container
|
121 |
+
with st.chat_message("user"):
|
122 |
+
st.markdown(user_input)
|
123 |
+
|
124 |
+
# Add user message to session state
|
125 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
126 |
+
with st.spinner('Generating Response...'):
|
127 |
+
# Get the answer from TeapotAI using chat functionality
|
128 |
+
response = handle_chat(user_input, teapot_ai)
|
129 |
+
|
130 |
+
# Display assistant response in chat message container
|
131 |
+
with st.chat_message("assistant"):
|
132 |
+
st.markdown(response)
|
133 |
+
|
134 |
+
# Add assistant response to session state
|
135 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
136 |
+
st.markdown("### Suggested Questions")
|
137 |
+
|
138 |
+
|
139 |
+
|
140 |
+
# Run the app
|
141 |
+
if __name__ == "__main__":
|
142 |
+
main()
|